@jjh32456/longlive 2.1.0 → 2.3.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 +108 -1
- package/QUICKSTART.md +7 -7
- package/README.en.md +13 -1
- package/README.md +26 -8
- package/SPEC.md +6 -5
- package/build-info.json +143 -73
- package/cordis.patch.yml +2 -0
- package/docs/ARCHITECTURE.md +6 -3
- package/docs/CONFIG.md +25 -1
- package/docs/FAQ.md +2 -2
- package/docs/FEATURES.md +125 -2
- package/docs/INDEX-FRESHNESS.md +8 -1
- package/docs/OPERATIONS.md +63 -2
- package/docs/QUICKSTART.md +2 -2
- package/docs/README.en.md +1 -1
- package/docs/TROUBLESHOOTING.md +1 -1
- package/package.json +10 -2
- package/scripts/assert-install.mjs +124 -0
- package/scripts/backlog-report.mjs +98 -0
- package/scripts/install-230.mjs +787 -0
- package/scripts/lib/eng-common.mjs +428 -0
- package/scripts/rebuild-index.mjs +148 -0
- package/scripts/restore-drill.mjs +351 -0
- package/scripts/run-autoresolve.mjs +123 -0
- package/scripts/watchdog-230.mjs +379 -0
- package/src/config.js +7 -0
- package/src/features.js +35 -0
- package/src/gate/action-gate.js +545 -0
- package/src/memory/backup-retention.mjs +823 -0
- package/src/memory/cards.js +73 -12
- package/src/memory/conflict-scan.mjs +356 -0
- package/src/memory/conflicts.js +202 -9
- package/src/memory/consolidate.js +537 -35
- package/src/memory/decay.js +133 -19
- package/src/memory/event-index.js +62 -4
- package/src/memory/forget-scheduler.mjs +303 -0
- package/src/memory/forget-v2.js +94 -8
- package/src/memory/index-cache.mjs +216 -0
- package/src/memory/index.js +179 -16
- package/src/memory/lock.js +53 -12
- package/src/memory/maintenance.js +295 -19
- package/src/memory/recall-feedback.mjs +159 -17
- package/src/memory/recall-v2.js +5 -3
- package/src/memory/recall.js +10 -4
- package/src/memory/state.js +446 -38
- package/src/memory/task-state.mjs +569 -0
- package/src/recall/brain.mjs +55 -6
- package/src/recall/continuity-volatile.mjs +195 -1
- package/src/recall/index.js +8 -0
- package/src/tools.js +141 -21
- package/src/ui/routes-readonly.js +63 -5
package/src/memory/cards.js
CHANGED
|
@@ -44,6 +44,9 @@ import {
|
|
|
44
44
|
} from './state.js';
|
|
45
45
|
import { sourceStamp, stampExtras, MANUAL_SESSION } from './provenance.js';
|
|
46
46
|
import { CARD_DIRS, manifestPath, refreshManifest } from './manifest.js';
|
|
47
|
+
// 2.3.0 W2.2:写卡后的自动冲突扫描(候选落盘 / conflicts_with 边 / 再巩固收口)。
|
|
48
|
+
// 运行时才调用,模块环(conflict-scan → conflicts → records → cards)不会在求值期取到未初始化绑定。
|
|
49
|
+
import { applyWriteConflictScan } from './conflict-scan.mjs';
|
|
47
50
|
|
|
48
51
|
const REL_PATTERN = /^(topics|journal|procedures)\/[^\r\n]+\.md$/i;
|
|
49
52
|
// The conflict marker is a single-line list. A comma or bracket inside a path
|
|
@@ -67,6 +70,14 @@ function normalizeKey(value) {
|
|
|
67
70
|
return text.toLowerCase();
|
|
68
71
|
}
|
|
69
72
|
|
|
73
|
+
/** frontmatter 里 `[a, b]` 或裸 `a` 形态的单行列表 → 去重前的字符串数组。 */
|
|
74
|
+
function parseCardList(value) {
|
|
75
|
+
const text = String(value ?? '').trim();
|
|
76
|
+
if (text === '') return [];
|
|
77
|
+
const inner = /^\[(.*)\]$/.test(text) ? text.slice(1, -1) : text;
|
|
78
|
+
return inner.split(',').map((part) => part.trim()).filter(Boolean);
|
|
79
|
+
}
|
|
80
|
+
|
|
70
81
|
/**
|
|
71
82
|
* Normalize a card path to POSIX-relative form and refuse anything that is not
|
|
72
83
|
* a markdown card in topics/, journal/ or procedures/.
|
|
@@ -217,21 +228,31 @@ function formatCardList(rels) {
|
|
|
217
228
|
* restored from the pre-write backup if it moved. Returns
|
|
218
229
|
* `{rel, changed, backup?, backupRel?, sha256}`.
|
|
219
230
|
*/
|
|
220
|
-
export function appendConflictWith(root, oldRel, newRel, { now = new Date() } = {}) {
|
|
231
|
+
export function appendConflictWith(root, oldRel, newRel, { now = new Date(), supersededBy = null } = {}) {
|
|
221
232
|
const abs = resolveInside(root, oldRel);
|
|
222
233
|
if (!fs.existsSync(abs)) {
|
|
223
234
|
throw memoryError('E_CARD_NOT_FOUND', `冲突标记目标不存在:${oldRel}`);
|
|
224
235
|
}
|
|
225
236
|
const text = fs.readFileSync(abs, 'utf8');
|
|
226
237
|
const before = parseFrontmatter(text);
|
|
227
|
-
const
|
|
228
|
-
const
|
|
229
|
-
?
|
|
230
|
-
: (
|
|
231
|
-
|
|
232
|
-
|
|
238
|
+
const current = parseCardList(before.extras.conflict_with ?? '');
|
|
239
|
+
const supersededTarget = supersededBy === null || supersededBy === undefined || String(supersededBy).trim() === ''
|
|
240
|
+
? null
|
|
241
|
+
: String(supersededBy).trim();
|
|
242
|
+
const supersededCurrent = parseCardList(before.extras.superseded_by ?? '');
|
|
243
|
+
const nextSuperseded = supersededTarget === null || supersededCurrent.includes(supersededTarget)
|
|
244
|
+
? supersededCurrent
|
|
245
|
+
: [...supersededCurrent, supersededTarget];
|
|
246
|
+
// 2.3.0 W2.2:同一次事务里写 conflict_with(双向冲突标记)与 superseded_by(旧结论被新卡取代),
|
|
247
|
+
// 旧卡正文一个字节都不动;两者都已存在则整卡不改(幂等)。
|
|
248
|
+
const addConflict = !current.includes(newRel);
|
|
249
|
+
const addSuperseded = supersededTarget !== null && !supersededCurrent.includes(supersededTarget);
|
|
250
|
+
if (!addConflict && !addSuperseded) {
|
|
251
|
+
return { rel: oldRel, changed: false, superseded: false, sha256: sha256Text(text) };
|
|
233
252
|
}
|
|
234
|
-
const
|
|
253
|
+
const extrasUpdate = { conflict_with: formatCardList([...current, newRel]) };
|
|
254
|
+
if (nextSuperseded.length > 0) extrasUpdate.superseded_by = formatCardList(nextSuperseded);
|
|
255
|
+
const updated = updateExtras(text, extrasUpdate);
|
|
235
256
|
const backup = backupFile(root, abs, { now });
|
|
236
257
|
try {
|
|
237
258
|
writeFileAtomic(root, abs, updated, { backup: false, now });
|
|
@@ -245,6 +266,7 @@ export function appendConflictWith(root, oldRel, newRel, { now = new Date() } =
|
|
|
245
266
|
return {
|
|
246
267
|
rel: oldRel,
|
|
247
268
|
changed: true,
|
|
269
|
+
superseded: addSuperseded,
|
|
248
270
|
backup: backup.path,
|
|
249
271
|
backupRel: backup.rel,
|
|
250
272
|
sha256: sha256Text(readBack),
|
|
@@ -354,10 +376,11 @@ export function writeCard(rootOrSpec, specOrOptions = {}, maybeOptions = {}) {
|
|
|
354
376
|
const fields = normalizeFields(root, spec, title, now);
|
|
355
377
|
const extras = normalizeExtras(root, spec, stampInput);
|
|
356
378
|
if (conflictRels.length > 0) {
|
|
357
|
-
const explicit =
|
|
358
|
-
? extras.conflict.trim().slice(1, -1).split(',').map((part) => part.trim()).filter(Boolean)
|
|
359
|
-
: [];
|
|
379
|
+
const explicit = parseCardList(extras.conflict ?? '');
|
|
360
380
|
extras.conflict = formatCardList([...explicit, ...conflictRels]);
|
|
381
|
+
// 2.3.0 W2.2:新卡正面记 supersedes(它取代了哪些旧结论),旧卡反面记 superseded_by。
|
|
382
|
+
const supersedes = parseCardList(extras.supersedes ?? '');
|
|
383
|
+
extras.supersedes = formatCardList([...new Set([...supersedes, ...conflictRels])]);
|
|
361
384
|
}
|
|
362
385
|
|
|
363
386
|
const text = buildCardText(fields, extras, body);
|
|
@@ -371,7 +394,7 @@ export function writeCard(rootOrSpec, specOrOptions = {}, maybeOptions = {}) {
|
|
|
371
394
|
const marked = [];
|
|
372
395
|
try {
|
|
373
396
|
for (const conflict of conflicts) {
|
|
374
|
-
marked.push(appendConflictWith(root, conflict.rel, rel, { now }));
|
|
397
|
+
marked.push(appendConflictWith(root, conflict.rel, rel, { now, supersededBy: rel }));
|
|
375
398
|
}
|
|
376
399
|
} catch (error) {
|
|
377
400
|
// All-or-nothing from the caller's point of view: remove the new card and
|
|
@@ -390,6 +413,27 @@ export function writeCard(rootOrSpec, specOrOptions = {}, maybeOptions = {}) {
|
|
|
390
413
|
: memoryError('E_CARD_VERIFY', `冲突标记失败,新卡已回滚:${rel}`, error);
|
|
391
414
|
}
|
|
392
415
|
|
|
416
|
+
// 2.3.0 W2.2:卡与 superseded 标记都已落盘后,自动记录冲突候选并形成 conflicts_with 边
|
|
417
|
+
// (幂等;失败只返回 warning,不回滚已成立的新卡/标记——候选留 pending 供 memory_conflicts 裁决)。
|
|
418
|
+
let conflictScan = null;
|
|
419
|
+
const conflictWarnings = [];
|
|
420
|
+
try {
|
|
421
|
+
conflictScan = applyWriteConflictScan({
|
|
422
|
+
memoryRoot: root,
|
|
423
|
+
newCard: { rel, title: fields.title, key: candidateKey },
|
|
424
|
+
conflicts,
|
|
425
|
+
config: isPlainObject(options.config) ? options.config : {},
|
|
426
|
+
now,
|
|
427
|
+
});
|
|
428
|
+
if (conflictScan.ok === false) {
|
|
429
|
+
conflictWarnings.push({ code: conflictScan.code ?? 'E_HG_CONFLICT_SCAN', message: conflictScan.message ?? null });
|
|
430
|
+
}
|
|
431
|
+
for (const warning of conflictScan.warnings ?? []) conflictWarnings.push(warning);
|
|
432
|
+
} catch (error) {
|
|
433
|
+
conflictScan = null;
|
|
434
|
+
conflictWarnings.push({ code: error?.code ?? 'E_HG_CONFLICT_SCAN', message: error?.message ?? String(error) });
|
|
435
|
+
}
|
|
436
|
+
|
|
393
437
|
let manifest = null;
|
|
394
438
|
let manifestWarning = null;
|
|
395
439
|
try {
|
|
@@ -416,6 +460,23 @@ export function writeCard(rootOrSpec, specOrOptions = {}, maybeOptions = {}) {
|
|
|
416
460
|
source: { session: stamp.source_session, turn: stamp.source_turn, written_at: stamp.written_at },
|
|
417
461
|
conflicts: conflicts.map((row) => ({ rel: row.rel, title: row.title, reasons: row.reasons })),
|
|
418
462
|
conflictWith: marked.map((row) => row.rel),
|
|
463
|
+
supersedes: conflictRels,
|
|
464
|
+
supersededBy: marked.filter((row) => row.superseded === true).map((row) => row.rel),
|
|
465
|
+
conflictCandidates: conflictScan && conflictScan.file
|
|
466
|
+
? {
|
|
467
|
+
file: relativePath(root, conflictScan.file),
|
|
468
|
+
written: conflictScan.written ?? 0,
|
|
469
|
+
pending: conflictScan.pending ?? null,
|
|
470
|
+
accepted: conflictScan.accepted ?? 0,
|
|
471
|
+
edges: Array.isArray(conflictScan.edges) ? conflictScan.edges.length : 0,
|
|
472
|
+
disabled: conflictScan.disabled === true,
|
|
473
|
+
}
|
|
474
|
+
: null,
|
|
475
|
+
conflictEdges: (conflictScan?.edges ?? []).map((row) => (row.ok === true
|
|
476
|
+
? { from: row.from, to: row.to, ...(row.duplicate === true ? { duplicate: true } : {}) }
|
|
477
|
+
: { from: row.from, to: row.to, ok: false, code: row.code ?? 'E_HG_EDGE_WRITE' })),
|
|
478
|
+
conflictScan,
|
|
479
|
+
...(conflictWarnings.length === 0 ? {} : { conflictWarnings }),
|
|
419
480
|
manifest,
|
|
420
481
|
...(manifestWarning === null ? {} : { manifestWarning }),
|
|
421
482
|
};
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// conflict-scan.mjs — 2.3.0 W2.2「写入时自动冲突检测 + 再巩固」接线层。
|
|
3
|
+
//
|
|
4
|
+
// 融合点(复用 2.0.0 已有件,不造第二套冲突机制):
|
|
5
|
+
// ① 卡写入:cards.js writeCard → detectConflicts(已有)→
|
|
6
|
+
// recordWriteConflictCandidates(conflicts.js 新增)→ appendConflictCandidates(已有)
|
|
7
|
+
// → `.longlive/conflicts/candidates.jsonl`(append-only,pending 上限/保留期沿用旧口径);
|
|
8
|
+
// ② 再巩固:writeCard 用 appendConflictWith(已有)一次事务写入旧卡
|
|
9
|
+
// frontmatter `conflict_with` + `superseded_by`(正文不删不改),新卡写 `supersedes`;
|
|
10
|
+
// ③ 本模块在卡全部落盘后 appendConflictEdge(已有)写 1 条 conflicts_with 边 +
|
|
11
|
+
// 1 行 kind=conflict-accept 审计(source='card-write'),并把该卡对候选记 accepted
|
|
12
|
+
// (reason='auto-supersede',区别于用户裁决);
|
|
13
|
+
// ④ 旧卡 `superseded_by` 被 lifecycle.migrateHistorical(autoDetect:true) 已有逻辑识别 →
|
|
14
|
+
// 标 lifecycle: historical → recall/trust 历史过滤;归档仍由该迁移器负责,不在这里删/移卡;
|
|
15
|
+
// ⑤ maintenance.js 每日槽 conflictScan 调 runDailyConflictScan:runConflictCandidateJob(已有,
|
|
16
|
+
// 按天幂等)+ reconcileConflictCandidates(把端点消失/已有边/端点已 superseded 的 pending
|
|
17
|
+
// 候选归档,幂等),全部失败返回 ok:false,由维护槽记 lastConflictScanError,不抛穿。
|
|
18
|
+
//
|
|
19
|
+
// 隐私:本模块只传递卡 rel 与固定原因码;候选行 evidence 仅 {source, a:{rel,role,reasons},
|
|
20
|
+
// b:{rel,role,reasons}},不含标题/正文/摘要/邮箱/绝对路径(见 conflicts.js
|
|
21
|
+
// recordWriteConflictCandidates)。边/审计沿用 appendConflictEdge 既有脱敏口径。
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
|
|
24
|
+
import fs from 'node:fs';
|
|
25
|
+
import path from 'node:path';
|
|
26
|
+
|
|
27
|
+
import {
|
|
28
|
+
CONFLICT_WRITE_REASON,
|
|
29
|
+
appendConflictCandidates,
|
|
30
|
+
appendConflictEdge,
|
|
31
|
+
conflictPairKey,
|
|
32
|
+
readConflictCandidates,
|
|
33
|
+
recordWriteConflictCandidates,
|
|
34
|
+
runConflictCandidateJob,
|
|
35
|
+
} from './conflicts.js';
|
|
36
|
+
import { loadEdges } from '../recall/edges.js';
|
|
37
|
+
|
|
38
|
+
/** 写卡扫描的来源标签(边 source / 审计 source 都写它,便于和人工 accept 区分)。 */
|
|
39
|
+
export const WRITE_SCAN_SOURCE = 'card-write';
|
|
40
|
+
/** 写卡扫描写边时的 actor 标签。 */
|
|
41
|
+
export const WRITE_SCAN_ACTOR = 'card-write';
|
|
42
|
+
/** 维护槽对账时写归档行的 actor 标签。 */
|
|
43
|
+
export const RECONCILE_ACTOR = 'maintenance-conflict-scan';
|
|
44
|
+
/** 边已写成功、只是审计行失败/重复的码:冲突事实成立,候选按 accepted 收口而不是留 pending。 */
|
|
45
|
+
const EDGE_OK_CODES = new Set(['E_HG_EDGE_DUP', 'E_HG_EDGE_AUDIT']);
|
|
46
|
+
|
|
47
|
+
function errorCodeOf(error, fallback) {
|
|
48
|
+
const code = typeof error?.code === 'string' && error.code.trim() !== '' ? error.code.trim() : '';
|
|
49
|
+
return code === '' ? fallback : code;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function errorMessageOf(error) {
|
|
53
|
+
return String(error?.message ?? error);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function resolveRootOrNull(memoryRoot) {
|
|
57
|
+
if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') return '';
|
|
58
|
+
return path.resolve(memoryRoot);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function cardAbsPath(root, rel) {
|
|
62
|
+
return path.join(root, ...String(rel).split('/'));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function cardFileExists(root, rel) {
|
|
66
|
+
try {
|
|
67
|
+
return fs.statSync(cardAbsPath(root, rel)).isFile();
|
|
68
|
+
} catch {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 旧卡 frontmatter 是否已有 superseded_by/replaced_by(与 lifecycle.migrateHistorical 同口径)。 */
|
|
74
|
+
function cardHasSupersededFlag(root, rel) {
|
|
75
|
+
try {
|
|
76
|
+
const text = fs.readFileSync(cardAbsPath(root, rel), 'utf8');
|
|
77
|
+
return /^[ \t]*(superseded_by|replaced_by)[ \t]*:/m.test(text);
|
|
78
|
+
} catch {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** 读已落盘冲突边:返回 {ok, pairs:Set<conflictPairKey>};读失败给 ok:false 但不抛。 */
|
|
84
|
+
function loadConflictEdgePairs(memoryRoot) {
|
|
85
|
+
try {
|
|
86
|
+
const store = loadEdges({ memoryRoot });
|
|
87
|
+
const edges = Array.isArray(store) ? store : Array.isArray(store?.edges) ? store.edges : [];
|
|
88
|
+
const pairs = new Set();
|
|
89
|
+
for (const edge of edges) {
|
|
90
|
+
if (!edge || String(edge.type ?? '').trim() !== 'conflicts_with') continue;
|
|
91
|
+
const key = conflictPairKey(edge.from, edge.to);
|
|
92
|
+
if (key !== '\u0000') pairs.add(key);
|
|
93
|
+
}
|
|
94
|
+
return { ok: true, pairs };
|
|
95
|
+
} catch (error) {
|
|
96
|
+
return { ok: false, pairs: new Set(), code: errorCodeOf(error, 'E_HG_EDGE_READ') };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 写卡后的自动冲突扫描(cards.js 在卡与 superseded 标记全部落盘后调用)。
|
|
102
|
+
* - recordWriteConflictCandidates 先落候选(失败返回 ok:false,cards.js 只警告不回滚卡);
|
|
103
|
+
* - 候选就绪后逐对 appendConflictEdge:成功 / 重复 / 审计失败都按「冲突事实成立」收口,
|
|
104
|
+
* 把候选记 accepted(reason='auto-supersede');其它写边失败保留 pending 等人裁决;
|
|
105
|
+
* - 任何异常都收敛成返回值,不向写卡路径抛。
|
|
106
|
+
*/
|
|
107
|
+
export function applyWriteConflictScan({
|
|
108
|
+
memoryRoot,
|
|
109
|
+
newCard = null,
|
|
110
|
+
conflicts = [],
|
|
111
|
+
config = {},
|
|
112
|
+
now = new Date(),
|
|
113
|
+
writeEdges = true,
|
|
114
|
+
} = {}) {
|
|
115
|
+
const root = resolveRootOrNull(memoryRoot);
|
|
116
|
+
if (root === '') {
|
|
117
|
+
return { ok: false, code: 'E_HG_NO_MEMORY_ROOT', message: 'E_HG_NO_MEMORY_ROOT: memoryRoot required', disabled: false, written: 0, pending: null, candidates: [], edges: [], accepted: 0, warnings: [] };
|
|
118
|
+
}
|
|
119
|
+
const warnings = [];
|
|
120
|
+
let recorded;
|
|
121
|
+
try {
|
|
122
|
+
recorded = recordWriteConflictCandidates({ memoryRoot: root, newCard, conflicts, config, now });
|
|
123
|
+
} catch (error) {
|
|
124
|
+
return {
|
|
125
|
+
ok: false,
|
|
126
|
+
code: errorCodeOf(error, 'E_HG_CONFLICT_WRITE'),
|
|
127
|
+
message: errorMessageOf(error),
|
|
128
|
+
disabled: false,
|
|
129
|
+
written: 0,
|
|
130
|
+
pending: null,
|
|
131
|
+
candidates: [],
|
|
132
|
+
edges: [],
|
|
133
|
+
accepted: 0,
|
|
134
|
+
warnings,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
const base = {
|
|
138
|
+
ok: recorded.ok !== false,
|
|
139
|
+
disabled: recorded.disabled === true,
|
|
140
|
+
file: recorded.file ?? null,
|
|
141
|
+
written: recorded.written ?? 0,
|
|
142
|
+
pending: recorded.pending ?? null,
|
|
143
|
+
candidates: recorded.candidates ?? [],
|
|
144
|
+
skipped: recorded.skipped ?? [],
|
|
145
|
+
};
|
|
146
|
+
if (recorded.ok === false) {
|
|
147
|
+
return {
|
|
148
|
+
...base,
|
|
149
|
+
code: recorded.code ?? 'E_HG_CONFLICT_WRITE',
|
|
150
|
+
message: recorded.message ?? null,
|
|
151
|
+
edges: [],
|
|
152
|
+
accepted: 0,
|
|
153
|
+
warnings,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
const edges = [];
|
|
157
|
+
const acceptedCandidates = [];
|
|
158
|
+
const candidates = base.candidates;
|
|
159
|
+
if (writeEdges && candidates.length > 0) {
|
|
160
|
+
for (const candidate of candidates) {
|
|
161
|
+
try {
|
|
162
|
+
const result = appendConflictEdge(
|
|
163
|
+
root,
|
|
164
|
+
{
|
|
165
|
+
from: candidate.aCard,
|
|
166
|
+
to: candidate.bCard,
|
|
167
|
+
type: 'conflicts_with',
|
|
168
|
+
evidence: null,
|
|
169
|
+
source: WRITE_SCAN_SOURCE,
|
|
170
|
+
},
|
|
171
|
+
{ actor: WRITE_SCAN_ACTOR, now },
|
|
172
|
+
);
|
|
173
|
+
edges.push({ from: candidate.aCard, to: candidate.bCard, ok: true, duplicate: false, edgeId: result?.auditRow?.edgeId ?? null });
|
|
174
|
+
acceptedCandidates.push(candidate);
|
|
175
|
+
} catch (error) {
|
|
176
|
+
const code = errorCodeOf(error, 'E_HG_EDGE_WRITE');
|
|
177
|
+
if (EDGE_OK_CODES.has(code)) {
|
|
178
|
+
edges.push({ from: candidate.aCard, to: candidate.bCard, ok: true, duplicate: code === 'E_HG_EDGE_DUP', code });
|
|
179
|
+
acceptedCandidates.push(candidate);
|
|
180
|
+
if (code === 'E_HG_EDGE_AUDIT') {
|
|
181
|
+
warnings.push({ code, message: 'edge written but audit row missing (fail-closed accepted)', aCard: candidate.aCard, bCard: candidate.bCard });
|
|
182
|
+
}
|
|
183
|
+
} else {
|
|
184
|
+
edges.push({ from: candidate.aCard, to: candidate.bCard, ok: false, code, message: errorMessageOf(error) });
|
|
185
|
+
warnings.push({ code, message: errorMessageOf(error), aCard: candidate.aCard, bCard: candidate.bCard });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
let ledger = null;
|
|
191
|
+
if (acceptedCandidates.length > 0) {
|
|
192
|
+
try {
|
|
193
|
+
const appended = appendConflictCandidates({
|
|
194
|
+
memoryRoot: root,
|
|
195
|
+
candidates: acceptedCandidates.map((candidate) => ({
|
|
196
|
+
id: candidate.id,
|
|
197
|
+
aCard: candidate.aCard,
|
|
198
|
+
bCard: candidate.bCard,
|
|
199
|
+
sharedTerms: candidate.sharedTerms,
|
|
200
|
+
confidence: candidate.confidence,
|
|
201
|
+
evidence: candidate.evidence,
|
|
202
|
+
})),
|
|
203
|
+
config,
|
|
204
|
+
now,
|
|
205
|
+
state: 'accepted',
|
|
206
|
+
reason: CONFLICT_WRITE_REASON,
|
|
207
|
+
actor: WRITE_SCAN_ACTOR,
|
|
208
|
+
});
|
|
209
|
+
ledger = appended;
|
|
210
|
+
if (appended?.ok === false) warnings.push({ code: appended.code ?? 'E_HG_CONFLICT_WRITE', message: appended.message ?? null });
|
|
211
|
+
} catch (error) {
|
|
212
|
+
warnings.push({ code: errorCodeOf(error, 'E_HG_CONFLICT_WRITE'), message: errorMessageOf(error) });
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
...base,
|
|
217
|
+
edges,
|
|
218
|
+
accepted: acceptedCandidates.length,
|
|
219
|
+
autoSuperseded: acceptedCandidates.map((candidate) => candidate.id),
|
|
220
|
+
ledger: ledger ? { file: ledger.file, written: ledger.written, pending: ledger.pending } : null,
|
|
221
|
+
warnings,
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* pending 候选对账(维护槽用,只归档不改卡):
|
|
227
|
+
* - endpoint-missing:任一卡文件已不存在;
|
|
228
|
+
* - edge-present:recall/edges.jsonl 已有该卡对 conflicts_with 边(人工 accept 或写卡自动形成);
|
|
229
|
+
* - endpoint-superseded:任一卡 frontmatter 已 superseded_by/replaced_by(旧卡已被新结论取代)。
|
|
230
|
+
* 归档 = append 一行 state='archived',reason='scan-<原因>';不改 pending 上限/保留期;幂等。
|
|
231
|
+
*/
|
|
232
|
+
export function reconcileConflictCandidates({ memoryRoot, config = {}, now = new Date(), actor = RECONCILE_ACTOR } = {}) {
|
|
233
|
+
const root = resolveRootOrNull(memoryRoot);
|
|
234
|
+
if (root === '') {
|
|
235
|
+
return { ok: false, code: 'E_HG_NO_MEMORY_ROOT', message: 'E_HG_NO_MEMORY_ROOT: memoryRoot required', scanned: 0, archived: 0, groups: [], warnings: [] };
|
|
236
|
+
}
|
|
237
|
+
let ledger;
|
|
238
|
+
try {
|
|
239
|
+
ledger = readConflictCandidates({ memoryRoot: root, config, now });
|
|
240
|
+
} catch (error) {
|
|
241
|
+
return { ok: false, code: errorCodeOf(error, 'E_HG_CONFLICT_READ'), message: errorMessageOf(error), scanned: 0, archived: 0, groups: [], warnings: [] };
|
|
242
|
+
}
|
|
243
|
+
const edgeState = loadConflictEdgePairs(root);
|
|
244
|
+
const warnings = [];
|
|
245
|
+
if (edgeState.ok !== true) {
|
|
246
|
+
warnings.push({ code: edgeState.code ?? 'E_HG_EDGE_READ', message: 'edge store unreadable: skip edge-present grouping' });
|
|
247
|
+
}
|
|
248
|
+
const groups = new Map();
|
|
249
|
+
const pending = ledger.pending ?? [];
|
|
250
|
+
for (const row of pending) {
|
|
251
|
+
let reason = null;
|
|
252
|
+
if (!cardFileExists(root, row.aCard) || !cardFileExists(root, row.bCard)) {
|
|
253
|
+
reason = 'endpoint-missing';
|
|
254
|
+
} else if (edgeState.ok === true && edgeState.pairs.has(conflictPairKey(row.aCard, row.bCard))) {
|
|
255
|
+
reason = 'edge-present';
|
|
256
|
+
} else if (cardHasSupersededFlag(root, row.aCard) || cardHasSupersededFlag(root, row.bCard)) {
|
|
257
|
+
reason = 'endpoint-superseded';
|
|
258
|
+
}
|
|
259
|
+
if (reason === null) continue;
|
|
260
|
+
const list = groups.get(reason) ?? [];
|
|
261
|
+
list.push({ id: row.id, aCard: row.aCard, bCard: row.bCard, sharedTerms: [], confidence: null });
|
|
262
|
+
groups.set(reason, list);
|
|
263
|
+
}
|
|
264
|
+
const archived = [];
|
|
265
|
+
for (const [reason, candidates] of groups) {
|
|
266
|
+
const rowReason = `scan-${reason}`;
|
|
267
|
+
try {
|
|
268
|
+
const appended = appendConflictCandidates({
|
|
269
|
+
memoryRoot: root,
|
|
270
|
+
candidates,
|
|
271
|
+
config,
|
|
272
|
+
now,
|
|
273
|
+
state: 'archived',
|
|
274
|
+
reason: rowReason,
|
|
275
|
+
actor,
|
|
276
|
+
});
|
|
277
|
+
if (appended?.ok === false) {
|
|
278
|
+
warnings.push({ code: appended.code ?? 'E_HG_CONFLICT_WRITE', message: appended.message ?? null, reason: rowReason });
|
|
279
|
+
} else {
|
|
280
|
+
archived.push({ reason: rowReason, count: candidates.length, written: appended.written });
|
|
281
|
+
}
|
|
282
|
+
} catch (error) {
|
|
283
|
+
warnings.push({ code: errorCodeOf(error, 'E_HG_CONFLICT_WRITE'), message: errorMessageOf(error), reason: rowReason });
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
const archivedCount = archived.reduce((sum, item) => sum + item.count, 0);
|
|
287
|
+
return {
|
|
288
|
+
ok: warnings.length === 0,
|
|
289
|
+
scanned: pending.length,
|
|
290
|
+
archived: archivedCount,
|
|
291
|
+
groups: archived,
|
|
292
|
+
...(edgeState.ok === true ? {} : { edgeRead: false }),
|
|
293
|
+
warnings,
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* 每日冲突维护槽(maintenance.js B6 调用):候选检测(按天幂等)+ pending 对账。
|
|
299
|
+
* 任一步失败只把 ok 置 false 并记在 steps 里,绝不抛穿给维护槽/调度器。
|
|
300
|
+
*/
|
|
301
|
+
export function runDailyConflictScan({ memoryRoot, config = {}, now = new Date(), logger = null } = {}) {
|
|
302
|
+
const root = resolveRootOrNull(memoryRoot);
|
|
303
|
+
if (root === '') {
|
|
304
|
+
return { ok: false, code: 'E_HG_NO_MEMORY_ROOT', message: 'E_HG_NO_MEMORY_ROOT: memoryRoot required', steps: {} };
|
|
305
|
+
}
|
|
306
|
+
const at = now instanceof Date ? now.toISOString() : new Date(now ?? Date.now()).toISOString();
|
|
307
|
+
const steps = {};
|
|
308
|
+
let ok = true;
|
|
309
|
+
try {
|
|
310
|
+
const job = runConflictCandidateJob({ memoryRoot: root, config, now });
|
|
311
|
+
if (job?.skipped === true) {
|
|
312
|
+
steps.candidates = { status: 'skipped', reason: job.reason ?? 'already-ran-today' };
|
|
313
|
+
} else if (job?.ok === false) {
|
|
314
|
+
ok = false;
|
|
315
|
+
steps.candidates = { status: 'failed', code: job.code ?? 'E_HG_CONFLICT_JOB', message: job.message ?? null };
|
|
316
|
+
} else {
|
|
317
|
+
steps.candidates = {
|
|
318
|
+
status: 'ran',
|
|
319
|
+
created: job?.created ?? 0,
|
|
320
|
+
archived: job?.archived ?? 0,
|
|
321
|
+
pending: job?.pending ?? null,
|
|
322
|
+
considered: job?.considered ?? null,
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
} catch (error) {
|
|
326
|
+
ok = false;
|
|
327
|
+
steps.candidates = { status: 'failed', code: errorCodeOf(error, 'E_HG_CONFLICT_JOB'), message: errorMessageOf(error) };
|
|
328
|
+
}
|
|
329
|
+
try {
|
|
330
|
+
const rec = reconcileConflictCandidates({ memoryRoot: root, config, now });
|
|
331
|
+
if (rec.ok === true) {
|
|
332
|
+
steps.reconcile = { status: 'ran', scanned: rec.scanned ?? 0, archived: rec.archived ?? 0, groups: rec.groups ?? [] };
|
|
333
|
+
} else {
|
|
334
|
+
ok = false;
|
|
335
|
+
steps.reconcile = {
|
|
336
|
+
status: 'failed',
|
|
337
|
+
code: rec.code ?? 'E_HG_CONFLICT_RECONCILE',
|
|
338
|
+
message: rec.message ?? null,
|
|
339
|
+
scanned: rec.scanned ?? 0,
|
|
340
|
+
archived: rec.archived ?? 0,
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
} catch (error) {
|
|
344
|
+
ok = false;
|
|
345
|
+
steps.reconcile = { status: 'failed', code: errorCodeOf(error, 'E_HG_CONFLICT_RECONCILE'), message: errorMessageOf(error) };
|
|
346
|
+
}
|
|
347
|
+
const result = { ok, at, steps };
|
|
348
|
+
if (typeof logger === 'function') {
|
|
349
|
+
try {
|
|
350
|
+
logger(`[conflict-scan] ${ok ? 'ok' : 'failed'} ${JSON.stringify(steps)}`);
|
|
351
|
+
} catch {
|
|
352
|
+
/* 日志失败不影响槽结果 */
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
return result;
|
|
356
|
+
}
|