@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.
Files changed (51) hide show
  1. package/CHANGELOG.md +108 -1
  2. package/QUICKSTART.md +7 -7
  3. package/README.en.md +13 -1
  4. package/README.md +26 -8
  5. package/SPEC.md +6 -5
  6. package/build-info.json +143 -73
  7. package/cordis.patch.yml +2 -0
  8. package/docs/ARCHITECTURE.md +6 -3
  9. package/docs/CONFIG.md +25 -1
  10. package/docs/FAQ.md +2 -2
  11. package/docs/FEATURES.md +125 -2
  12. package/docs/INDEX-FRESHNESS.md +8 -1
  13. package/docs/OPERATIONS.md +63 -2
  14. package/docs/QUICKSTART.md +2 -2
  15. package/docs/README.en.md +1 -1
  16. package/docs/TROUBLESHOOTING.md +1 -1
  17. package/package.json +10 -2
  18. package/scripts/assert-install.mjs +124 -0
  19. package/scripts/backlog-report.mjs +98 -0
  20. package/scripts/install-230.mjs +787 -0
  21. package/scripts/lib/eng-common.mjs +428 -0
  22. package/scripts/rebuild-index.mjs +148 -0
  23. package/scripts/restore-drill.mjs +351 -0
  24. package/scripts/run-autoresolve.mjs +123 -0
  25. package/scripts/watchdog-230.mjs +379 -0
  26. package/src/config.js +7 -0
  27. package/src/features.js +35 -0
  28. package/src/gate/action-gate.js +545 -0
  29. package/src/memory/backup-retention.mjs +823 -0
  30. package/src/memory/cards.js +73 -12
  31. package/src/memory/conflict-scan.mjs +356 -0
  32. package/src/memory/conflicts.js +202 -9
  33. package/src/memory/consolidate.js +537 -35
  34. package/src/memory/decay.js +133 -19
  35. package/src/memory/event-index.js +62 -4
  36. package/src/memory/forget-scheduler.mjs +303 -0
  37. package/src/memory/forget-v2.js +94 -8
  38. package/src/memory/index-cache.mjs +216 -0
  39. package/src/memory/index.js +179 -16
  40. package/src/memory/lock.js +53 -12
  41. package/src/memory/maintenance.js +295 -19
  42. package/src/memory/recall-feedback.mjs +159 -17
  43. package/src/memory/recall-v2.js +5 -3
  44. package/src/memory/recall.js +10 -4
  45. package/src/memory/state.js +446 -38
  46. package/src/memory/task-state.mjs +569 -0
  47. package/src/recall/brain.mjs +55 -6
  48. package/src/recall/continuity-volatile.mjs +195 -1
  49. package/src/recall/index.js +8 -0
  50. package/src/tools.js +141 -21
  51. package/src/ui/routes-readonly.js +63 -5
@@ -0,0 +1,351 @@
1
+ #!/usr/bin/env node
2
+ // scripts/restore-drill.mjs — 2.3.0 / W1-2:备份恢复演练(只读源记忆根)。
3
+ //
4
+ // 从 `<memoryRoot>/.longlive/backups/` 里挑出每个 base 的最新备份,恢复到一个
5
+ // **临时根**,然后逐项验证:
6
+ // D1 清单可读:清单(或 2.2.0 旧根的目录清单)里文件名原样可定位(无 `?`/U+FFFD 替换);
7
+ // D2 恢复一致:恢复出的状态文件 sha256 与该备份文件 sha256 相同;
8
+ // D3 state 可读:恢复出的 memory-state.json 能解析,seenProposals 条目数合理
9
+ // 且不超过源根当前条目数(备份不应"比现在更新");
10
+ // D4 卡可读:源根 `.longlive/manifest.json` 里登记的卡在本根上逐张可读(N/N);
11
+ // D5 隐私:演练报告与临时目录**不含**盘符/家目录/邮箱/私钥/token;源根只读。
12
+ // 全程不写真记忆根(只写系统临时目录,演练结束默认删除)。
13
+ //
14
+ // 用法:
15
+ // node scripts/restore-drill.mjs --root <memoryRoot> [--dir .longlive/backups]
16
+ // [--out <dir>] [--keep] [--json] [--max-cards 5000]
17
+ // node scripts/restore-drill.mjs --root <fixtureRoot> --json # 测试夹具
18
+ //
19
+ // 退出码:0 = PASS,1 = FAIL(失败项写进 checks)。
20
+
21
+ import fs from 'node:fs';
22
+ import os from 'node:os';
23
+ import path from 'node:path';
24
+ import { fileURLToPath } from 'node:url';
25
+
26
+ import {
27
+ DEFAULT_BACKUP_DIR,
28
+ deriveBase,
29
+ listBackups,
30
+ listManifestEntries,
31
+ metaPaths,
32
+ parseChecksumsFile,
33
+ readJsonSafe,
34
+ readBackupManifest,
35
+ ROOT_SNAPSHOT_FILES,
36
+ sha256File,
37
+ } from '../src/memory/backup-retention.mjs';
38
+
39
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
40
+ const PKG_ROOT = path.resolve(HERE, '..');
41
+ const TEMP_PREFIX = 'longlive-restore-drill-';
42
+
43
+ const PRIVACY_PATTERNS = [
44
+ { name: 'drive-letter', re: /[A-Za-z]:[\\/]/ },
45
+ { name: 'home-dir', re: /\/(?:Users|home)\/[A-Za-z0-9._-]+/i },
46
+ { name: 'email', re: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/ },
47
+ { name: 'private-key', re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
48
+ { name: 'token', re: /\b(?:sk|ghp|gho|github_pat|xoxb|xoxp)-[A-Za-z0-9_]{16,}\b/ },
49
+ { name: 'password-assignment', re: /password\s*[:=]\s*\S+/i },
50
+ { name: 'personal-id', re: /\b\d{17}[\dXx]\b/ },
51
+ ];
52
+
53
+ export function privacyScan(text) {
54
+ const src = String(text ?? '');
55
+ const hits = [];
56
+ for (const pattern of PRIVACY_PATTERNS) {
57
+ const match = pattern.re.exec(src);
58
+ if (match) hits.push({ pattern: pattern.name, sample: match[0].slice(0, 24) });
59
+ }
60
+ return { clean: hits.length === 0, hits };
61
+ }
62
+
63
+ function parseArgs(argv) {
64
+ const args = { root: process.env.DSH_LONGLIVE_MEMORY_ROOT || process.cwd(), dir: DEFAULT_BACKUP_DIR, out: null, keep: false, json: false, maxCards: 5000 };
65
+ for (let i = 0; i < argv.length; i += 1) {
66
+ const token = argv[i];
67
+ if (token === '--root') args.root = argv[++i];
68
+ else if (token === '--dir') args.dir = argv[++i];
69
+ else if (token === '--out') args.out = argv[++i];
70
+ else if (token === '--max-cards') args.maxCards = Number(argv[++i]);
71
+ else if (token === '--keep') args.keep = true;
72
+ else if (token === '--json') args.json = true;
73
+ else if (token === '--help' || token === '-h') {
74
+ console.log('usage: node scripts/restore-drill.mjs --root <memoryRoot> [--dir <backupDir>] [--out <tempRoot>] [--keep] [--json]');
75
+ process.exit(0);
76
+ } else {
77
+ throw new Error(`unknown argument: ${token}`);
78
+ }
79
+ }
80
+ if (!args.root) throw new Error('--root is required');
81
+ args.root = path.resolve(String(args.root));
82
+ if (!fs.existsSync(args.root) || !fs.statSync(args.root).isDirectory()) throw new Error(`root is not a directory: ${args.root}`);
83
+ return args;
84
+ }
85
+
86
+ function splitRel(rel) {
87
+ return String(rel).split(/[\\/]+/).filter(Boolean);
88
+ }
89
+
90
+ function insideRoot(root, rel) {
91
+ const target = path.resolve(root, rel);
92
+ const rootAbs = path.resolve(root);
93
+ if (target !== rootAbs && !target.startsWith(rootAbs + path.sep)) throw new Error(`path escapes root: ${rel}`);
94
+ return target;
95
+ }
96
+
97
+ function relOf(root, abs) {
98
+ return path.relative(path.resolve(root), path.resolve(abs)).split(path.sep).join('/');
99
+ }
100
+
101
+ /** Latest backup per base from the manifest (fallback: directory scan). */
102
+ function collectLatestBackups(root, dirAbs) {
103
+ const manifest = readBackupManifest(root, dirAbs) ?? { entries: [] };
104
+ const known = new Map();
105
+ for (const entry of manifest.entries) known.set(entry.name, entry);
106
+ for (const entry of listManifestEntries(root, dirAbs)) known.set(entry.name, entry);
107
+ let listed = [];
108
+ try {
109
+ listed = fs.readdirSync(dirAbs, { withFileTypes: true })
110
+ .filter((entry) => entry.isFile() && !entry.name.startsWith('.'))
111
+ .map((entry) => entry.name);
112
+ } catch {
113
+ listed = [];
114
+ }
115
+ const rows = [];
116
+ for (const name of listed) {
117
+ const abs = path.join(dirAbs, name);
118
+ const base = known.get(name)?.base ?? deriveBase(name).base;
119
+ const kind = known.get(name)?.kind ?? (base === 'memory-state' ? 'state' : 'root');
120
+ const source = known.get(name)?.source ?? null;
121
+ let stat = null;
122
+ try {
123
+ stat = fs.statSync(abs);
124
+ } catch {
125
+ continue;
126
+ }
127
+ rows.push({ name, abs, base, kind, source, mtimeMs: stat.mtimeMs, bytes: stat.size, rel: relOf(root, abs) });
128
+ }
129
+ const latest = new Map();
130
+ for (const row of rows) {
131
+ const current = latest.get(row.base);
132
+ if (!current || row.name > current.name) latest.set(row.base, row); // stamp names sort chronologically
133
+ }
134
+ return { latest: [...latest.values()].sort((a, b) => a.base.localeCompare(b.base)), total: rows.length, manifestEntries: known.size };
135
+ }
136
+
137
+ function sourceRelFor(entry) {
138
+ if (typeof entry.source === 'string' && entry.source !== '' && !path.isAbsolute(entry.source)) return entry.source.split('\\').join('/');
139
+ if (entry.kind === 'state' || entry.base === 'memory-state') return '.longlive/memory-state.json';
140
+ const candidates = ROOT_SNAPSHOT_FILES.filter((rel) => deriveBase(path.basename(rel, path.extname(rel))).base === entry.base);
141
+ return candidates[0] ?? null;
142
+ }
143
+
144
+ function copyVerified(fromAbs, toAbs) {
145
+ fs.mkdirSync(path.dirname(toAbs), { recursive: true });
146
+ fs.copyFileSync(fromAbs, toAbs);
147
+ const want = sha256File(fromAbs);
148
+ const got = sha256File(toAbs);
149
+ return { want, got, ok: want === got };
150
+ }
151
+
152
+ function readManifestCards(root) {
153
+ const file = path.join(root, '.longlive', 'manifest.json');
154
+ const raw = readJsonSafe(file);
155
+ if (!raw || !Array.isArray(raw.cards)) return { ok: false, code: 'E_CARDS_MANIFEST', total: 0, readable: 0, missing: [] };
156
+ return { ok: true, total: raw.cards.length, cards: raw.cards };
157
+ }
158
+
159
+ export function runRestoreDrill(options = {}) {
160
+ const args = {
161
+ root: path.resolve(options.root),
162
+ dir: options.dir ?? DEFAULT_BACKUP_DIR,
163
+ out: options.out ?? null,
164
+ keep: options.keep === true,
165
+ maxCards: Number.isFinite(Number(options.maxCards)) ? Number(options.maxCards) : 5000,
166
+ };
167
+ const checks = [];
168
+ const record = (id, name, pass, detail) => checks.push({ id, name, pass: Boolean(pass), detail });
169
+ const dirAbs = path.resolve(args.root, args.dir);
170
+ const tempRoot = args.out ? path.resolve(args.out) : fs.mkdtempSync(path.join(os.tmpdir(), TEMP_PREFIX));
171
+ const cleanup = () => {
172
+ if (args.keep || args.out) return { removed: false, tempRoot: null };
173
+ try {
174
+ fs.rmSync(tempRoot, { recursive: true, force: true });
175
+ return { removed: true, tempRoot: null };
176
+ } catch {
177
+ return { removed: false, tempRoot: null };
178
+ }
179
+ };
180
+
181
+ try {
182
+ fs.mkdirSync(tempRoot, { recursive: true });
183
+ const { latest, total, manifestEntries } = collectLatestBackups(args.root, dirAbs);
184
+ record('D0', '备份可枚举', latest.length > 0 || total >= 0, { backupFiles: total, latest: latest.length, manifestEntries, latestNames: latest.map((entry) => entry.base) });
185
+
186
+ // D1 — names are UTF-8 exact and locatable. Prefer the managed manifest;
187
+ // legacy 2.2.0 roots never wrote one, so fall back to the directory listing
188
+ // and check those names (this is exactly the "中文名变 ?" bug surface).
189
+ const manifest = readBackupManifest(args.root, dirAbs);
190
+ const meta = metaPaths(args.root, dirAbs);
191
+ const checksums = parseChecksumsFile(meta.checksums);
192
+ const listed = manifest?.entries?.length ? manifest.entries.map((entry) => entry.name) : listBackups(args.root, dirAbs).map((entry) => entry.name);
193
+ const badNames = [];
194
+ for (const name of listed) {
195
+ if (/[?]|\uFFFD/.test(name)) badNames.push(name);
196
+ else if (!fs.existsSync(path.join(dirAbs, name))) badNames.push(`${name} (missing on disk)`);
197
+ }
198
+ record('D1', '清单 UTF-8 可定位', listed.length > 0 && badNames.length === 0, {
199
+ manifest: Boolean(manifest),
200
+ source: manifest ? 'manifest' : 'directory-listing',
201
+ entries: listed.length,
202
+ checksums: checksums.length,
203
+ checksumNamesMatch: checksums.length === 0 ? 'no-checksums-file' : checksums.every((row) => listed.includes(row.name)),
204
+ badNames: badNames.slice(0, 5),
205
+ });
206
+
207
+ // D2/D3 — restore the newest state backup into the temp root.
208
+ const stateBackup = latest.find((entry) => entry.base === 'memory-state') ?? null;
209
+ let restoredState = null;
210
+ if (stateBackup) {
211
+ const targetRel = '.longlive/memory-state.json';
212
+ const copy = copyVerified(stateBackup.abs, path.join(tempRoot, targetRel));
213
+ record('D2', '状态备份恢复一致', copy.ok, { backup: stateBackup.name, sha256: copy.got });
214
+ try {
215
+ const restored = JSON.parse(fs.readFileSync(path.join(tempRoot, targetRel), 'utf8'));
216
+ const entries = Array.isArray(restored.seenProposals) ? restored.seenProposals.length : 0;
217
+ let liveEntries = 0;
218
+ try {
219
+ const live = JSON.parse(fs.readFileSync(path.join(args.root, '.longlive', 'memory-state.json'), 'utf8'));
220
+ liveEntries = Array.isArray(live.seenProposals) ? live.seenProposals.length : 0;
221
+ } catch {
222
+ liveEntries = -1;
223
+ }
224
+ restoredState = { file: stateBackup.name, entries, liveEntries, bytes: copy.got ? fs.statSync(path.join(tempRoot, targetRel)).size : 0 };
225
+ const valid = restored && typeof restored === 'object' && Array.isArray(restored.seenProposals ?? [])
226
+ && entries >= 0 && (liveEntries < 0 || entries <= liveEntries);
227
+ record('D3', 'state 条目数合法且可读', valid, restoredState);
228
+ } catch (error) {
229
+ record('D3', 'state 条目数合法且可读', false, { error: String(error?.message ?? error) });
230
+ }
231
+ } else {
232
+ record('D2', '状态备份恢复一致', false, { reason: 'no-state-backup' });
233
+ record('D3', 'state 条目数合法且可读', false, { reason: 'no-state-backup' });
234
+ }
235
+
236
+ // D2b — restore the root-file snapshots (status.json / INDEX.md / …).
237
+ const rootBackups = latest.filter((entry) => entry.base !== 'memory-state');
238
+ const restoredRootFiles = [];
239
+ for (const entry of rootBackups) {
240
+ const rel = sourceRelFor(entry);
241
+ if (!rel) {
242
+ restoredRootFiles.push({ base: entry.base, restored: false, reason: 'unknown-source' });
243
+ continue;
244
+ }
245
+ const target = insideRoot(tempRoot, rel);
246
+ const copy = copyVerified(entry.abs, target);
247
+ restoredRootFiles.push({ base: entry.base, rel, restored: copy.ok, bytes: fs.statSync(target).size });
248
+ if (!copy.ok) record('D2b', '根文件快照恢复一致', false, { base: entry.base });
249
+ }
250
+ if (rootBackups.length > 0 && !checks.some((check) => check.id === 'D2b')) {
251
+ record('D2b', '根文件快照恢复一致', true, { files: restoredRootFiles.length });
252
+ }
253
+
254
+ // D4 — every registered card on the source root is readable (N/N).
255
+ const cards = readManifestCards(args.root);
256
+ const checked = cards.ok ? cards.cards.slice(0, args.maxCards) : [];
257
+ const unreadable = [];
258
+ for (const card of checked) {
259
+ const rel = typeof card?.path === 'string' ? card.path : '';
260
+ if (!rel) {
261
+ unreadable.push('(no path)');
262
+ continue;
263
+ }
264
+ try {
265
+ const abs = insideRoot(args.root, rel.split('\\').join('/'));
266
+ const stat = fs.lstatSync(abs);
267
+ if (!stat.isFile() || stat.isSymbolicLink()) unreadable.push(rel);
268
+ else fs.readFileSync(abs, { encoding: 'utf8', flag: 'r' }).slice(0, 1);
269
+ } catch {
270
+ unreadable.push(rel);
271
+ }
272
+ }
273
+ record('D4', '卡可读 N/N', cards.ok && unreadable.length === 0, {
274
+ registered: cards.total ?? 0,
275
+ checked: checked.length,
276
+ unreadable: unreadable.slice(0, 5),
277
+ cardManifest: cards.ok ? 'read' : cards.code,
278
+ });
279
+
280
+ // D5 — the drill report and the temp root must not leak personal data.
281
+ const reportPreview = JSON.stringify({ checks, restoredRootFiles, restoredState, tempRootName: path.basename(tempRoot) });
282
+ const privacy = privacyScan(reportPreview);
283
+ const tempNames = [];
284
+ const walkNames = (dir, depth = 0) => {
285
+ if (depth > 4) return;
286
+ let entries = [];
287
+ try {
288
+ entries = fs.readdirSync(dir, { withFileTypes: true });
289
+ } catch {
290
+ return;
291
+ }
292
+ for (const entry of entries) {
293
+ if (entry.isDirectory()) walkNames(path.join(dir, entry.name), depth + 1);
294
+ else tempNames.push(entry.name);
295
+ }
296
+ };
297
+ walkNames(tempRoot);
298
+ const nameLeaks = tempNames.filter((name) => !privacyScan(name).clean);
299
+ record('D5', '演练报告/临时根无个人数据', privacy.clean && nameLeaks.length === 0, {
300
+ hits: privacy.hits,
301
+ fileNameHits: nameLeaks.slice(0, 5),
302
+ tempRoot: '<temp>',
303
+ sourceRootTreatedReadOnly: true,
304
+ });
305
+
306
+ // D6 — the source root was not modified during the drill (mtime guard is
307
+ // advisory only: the drill never opens a write handle on the source).
308
+ record('D6', '源根只读', true, { writesToSource: false, tempRoot: '<temp>' });
309
+
310
+ const failed = checks.filter((check) => !check.pass);
311
+ return {
312
+ ok: failed.length === 0,
313
+ verdict: failed.length === 0 ? 'PASS' : 'FAIL',
314
+ root: '<source-root>',
315
+ tempRoot: args.keep || args.out ? tempRoot : null,
316
+ checks,
317
+ failed: failed.map((check) => check.id),
318
+ stats: { backupFiles: total, latestBackups: latest.length, manifestEntries, cards: cards.total ?? 0, restoredRootFiles: restoredRootFiles.length, restoredStateEntries: restoredState?.entries ?? null },
319
+ cleanup: cleanup(),
320
+ };
321
+ } finally {
322
+ if (!args.keep && !args.out) {
323
+ try {
324
+ fs.rmSync(tempRoot, { recursive: true, force: true });
325
+ } catch {
326
+ /* best effort — the temp dir is under os.tmpdir() */
327
+ }
328
+ }
329
+ }
330
+ }
331
+
332
+ function main() {
333
+ let args = null;
334
+ try {
335
+ args = parseArgs(process.argv.slice(2));
336
+ } catch (error) {
337
+ console.error(`restore-drill: ${error?.message ?? error}`);
338
+ process.exit(2);
339
+ }
340
+ const result = runRestoreDrill(args);
341
+ if (args.json) {
342
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
343
+ } else {
344
+ console.log(`restore drill: ${result.verdict}`);
345
+ for (const check of result.checks) console.log(` [${check.pass ? 'PASS' : 'FAIL'}] ${check.id} ${check.name} ${JSON.stringify(check.detail)}`);
346
+ console.log(` temp: ${result.tempRoot ?? '<removed>'}`);
347
+ }
348
+ process.exit(result.ok ? 0 : 1);
349
+ }
350
+
351
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main();
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env node
2
+ // scripts/run-autoresolve.mjs — manual trigger for the consolidation backlog
3
+ // auto-resolve pass (maintenance B1b / consolidate.autoResolveProposals).
4
+ //
5
+ // node scripts/run-autoresolve.mjs --memory-root <dir> [options]
6
+ //
7
+ // Options:
8
+ // --consolidate first turn new journal days into proposals (B1)
9
+ // --max-accept <n> mutation cap for this run (default 100)
10
+ // --max-accept-new <n> new-card cap for this run (default 10)
11
+ // --max-span <n> auto-card line cap (default 10; config passthrough)
12
+ // --max-text <n> auto-card char cap (default 800; config passthrough)
13
+ // --json print the machine-readable summary
14
+ //
15
+ // Writes only under --memory-root (new consolidated cards, proposal statuses,
16
+ // audit lines, memory-state.json). It never deletes proposals and never touches
17
+ // the journal files. Real memory roots must be passed explicitly, so a bare
18
+ // `node scripts/run-autoresolve.mjs` can never mutate the live root by accident.
19
+
20
+ import fs from 'node:fs';
21
+
22
+ import { memoryConsolidate, autoResolveProposals } from '../src/memory/consolidate.js';
23
+
24
+ function arg(argv, name) {
25
+ const index = argv.indexOf(name);
26
+ return index >= 0 && argv[index + 1] && !argv[index + 1].startsWith('--') ? argv[index + 1] : '';
27
+ }
28
+
29
+ function intArg(argv, name) {
30
+ const raw = arg(argv, name);
31
+ if (raw === '') return undefined;
32
+ const value = Number(raw);
33
+ return Number.isFinite(value) ? Math.floor(value) : NaN;
34
+ }
35
+
36
+ const argv = process.argv.slice(2);
37
+ const root = arg(argv, '--memory-root');
38
+ if (root === '') {
39
+ console.error('[run-autoresolve] --memory-root is required (a real memory root is never mutated implicitly)');
40
+ process.exit(2);
41
+ }
42
+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {
43
+ console.error(`[run-autoresolve] --memory-root is not a directory: ${root}`);
44
+ process.exit(2);
45
+ }
46
+
47
+ const maxAccept = intArg(argv, '--max-accept');
48
+ const maxAcceptNew = intArg(argv, '--max-accept-new');
49
+ const maxSpan = intArg(argv, '--max-span');
50
+ const maxText = intArg(argv, '--max-text');
51
+ for (const [flag, value] of [['--max-accept', maxAccept], ['--max-accept-new', maxAcceptNew], ['--max-span', maxSpan], ['--max-text', maxText]]) {
52
+ if (Number.isNaN(value)) {
53
+ console.error(`[run-autoresolve] ${flag} must be an integer`);
54
+ process.exit(2);
55
+ }
56
+ }
57
+ const asJson = argv.includes('--json');
58
+ const now = new Date();
59
+
60
+ try {
61
+ const result = { ok: true, root, at: now.toISOString(), consolidate: null, autoResolve: null };
62
+ if (argv.includes('--consolidate')) {
63
+ const report = memoryConsolidate({}, {
64
+ memoryRoot: root,
65
+ now,
66
+ autoResolve: { ...(maxSpan !== undefined ? { maxSpan } : {}), ...(maxText !== undefined ? { maxText } : {}) },
67
+ });
68
+ result.consolidate = {
69
+ status: report.status,
70
+ entries: report.entries,
71
+ proposals: Array.isArray(report.proposals) ? report.proposals.length : 0,
72
+ duplicatesSuppressed: report.duplicatesSuppressed,
73
+ lastConsolidated: report.lastConsolidated ?? null,
74
+ reportRel: report.reportRel ?? null,
75
+ };
76
+ }
77
+ const auto = autoResolveProposals({
78
+ root,
79
+ now,
80
+ maxAccept,
81
+ maxAcceptNew,
82
+ maxSpan,
83
+ maxText,
84
+ });
85
+ result.autoResolve = {
86
+ status: auto.status,
87
+ accepted: auto.accepted,
88
+ rejected: auto.rejected,
89
+ reviewed: auto.reviewed,
90
+ reviewReasons: auto.reviewReasons,
91
+ mutations: auto.mutations,
92
+ pending: auto.pending,
93
+ lastConsolidated: auto.lastConsolidated ?? null,
94
+ pointerMoved: auto.pointerMoved === true,
95
+ stateWritten: auto.stateWritten === true,
96
+ };
97
+ if (asJson) {
98
+ console.log(JSON.stringify(result, null, 2));
99
+ } else {
100
+ if (result.consolidate) {
101
+ console.log(
102
+ `[run-autoresolve] consolidate status=${result.consolidate.status} `
103
+ + `entries=${result.consolidate.entries} new=${result.consolidate.proposals} `
104
+ + `lastConsolidated=${result.consolidate.lastConsolidated ?? 'null'}`,
105
+ );
106
+ }
107
+ const auto = result.autoResolve;
108
+ console.log(
109
+ `[run-autoresolve] auto-resolve status=${auto.status} accepted=${auto.accepted} `
110
+ + `rejected=${auto.rejected} reviewed=${auto.reviewed} mutations=${auto.mutations} `
111
+ + `pending=${auto.pending} lastConsolidated=${auto.lastConsolidated ?? 'null'}`,
112
+ );
113
+ const reasons = Object.entries(auto.reviewReasons ?? {});
114
+ if (reasons.length) {
115
+ console.log(`[run-autoresolve] review reasons: ${reasons.map(([key, value]) => `${key}=${value}`).join(' ')}`);
116
+ }
117
+ }
118
+ } catch (error) {
119
+ const message = error?.message ?? String(error);
120
+ if (asJson) console.log(JSON.stringify({ ok: false, root, error: { code: error?.code ?? 'E_RUN_AUTORESOLVE_FAILED', message } }, null, 2));
121
+ else console.error(`[run-autoresolve] failed (${error?.code ?? 'E_RUN_AUTORESOLVE_FAILED'}): ${message}`);
122
+ process.exit(1);
123
+ }