@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
@@ -22,10 +22,59 @@ import {
22
22
  } from './state.js';
23
23
  import { scanCards } from './index.js';
24
24
  import { writeCard } from './cards.js';
25
+ // 2.2.0 lane A:自动建卡前做隐私/凭证扫描(复用召回面的隐私门,异常 fail-closed)。
26
+ import { privacyScan } from '../recall/privacy.mjs';
25
27
 
26
28
  const RESOLVED_STATUS = new Set(['accepted', 'rejected', 'superseded']);
27
29
  const AFFECT_KEYWORD = /^affect\b/i;
28
30
 
31
+ // ---- 2.2.0 lane A: automatic distillation policy --------------------------
32
+ // Calibrated against the live backlog analysis
33
+ // (427 pending proposals). The policy is mechanical on purpose: no semantic
34
+ // similarity, no coverage ratio, no probability. The only reasons that can
35
+ // auto-resolve a proposal are exact identity (same id / same content key /
36
+ // same paragraph anchor / same claim line), the structural anomalies measured
37
+ // in the analysis (T0), and the small clean no-target set (T1).
38
+ //
39
+ // T0 结构异常 -> auto-reject(原文仍在 journal,reject 不丢内容)
40
+ // T1 无目标 + 短段 + 干净 + 源文校验 -> auto-accept(写新卡,带 contentKey + 源文 sha)
41
+ // T3 事实/更正/隐私类、有目标(待人工合并)、源对不上 -> 留 pending
42
+ const AUTO_ACCEPT_NEW_PER_DAY = 10;
43
+ const AUTO_MUTATIONS_PER_DAY = 100;
44
+ const AUTO_SAFE_SPAN_MAX = 10;
45
+ const AUTO_SAFE_TEXT_MIN = 40;
46
+ const AUTO_SAFE_TEXT_MAX = 800;
47
+ const AUTO_OVERSIZED_SPAN = 100;
48
+ const AUTO_MIN_TEXT = 18;
49
+ // BACKLOG-ANALYSIS.md 附录 F:29 条结构异常提案背后的机械判据,正则逐字沿用,
50
+ // 这样审计里的 reject 理由可以逐条回溯到分析报告。
51
+ const AUTO_FLOW_PATTERN = /auto[::-]?land|自动落盘|轮次\s*\d+\s*·|turn\s*\d+|无落盘证据|无工具证据/i;
52
+ const AUTO_WAIT_PATTERN = /无新指令|无新动作|等待红队|待命|空闲|未回复|无变化/;
53
+ const AUTO_HUMAN_PATTERN = /更正|纠正|纠错|勘误|冲突|矛盾|隐私|密码|凭据|作废|推翻|改判|造假|错误|删卡|遗忘|forget/i;
54
+
55
+ /**
56
+ * 2.3.0 lane pipeline(W1-4):自动消化单元上限。
57
+ *
58
+ * `config.autoResolve.maxSpan` / `config.autoResolve.maxText` 走 raw passthrough
59
+ * (不新增 schemastery 叶子,照 features.js 里 hardgate.wake 的同一种做法),
60
+ * 缺省回落到冻结的 AUTO_SAFE_SPAN_MAX / AUTO_SAFE_TEXT_MAX。数值只做机械钳制
61
+ * (行数 1..200、字符 AUTO_SAFE_TEXT_MIN..8000),不是靠分布切出来的阈值。
62
+ */
63
+ function boundedInt(value, fallback, min, max) {
64
+ const number = Number(value);
65
+ if (!Number.isFinite(number)) return fallback;
66
+ return Math.min(max, Math.max(min, Math.floor(number)));
67
+ }
68
+
69
+ function autoUnitLimits(config = {}) {
70
+ const candidates = [config?.autoResolve, config?.autoMaintenance?.autoResolve];
71
+ const row = candidates.find((item) => item && typeof item === 'object' && !Array.isArray(item)) ?? {};
72
+ return {
73
+ maxSpan: boundedInt(row.maxSpan, AUTO_SAFE_SPAN_MAX, 1, 200),
74
+ maxText: boundedInt(row.maxText, AUTO_SAFE_TEXT_MAX, AUTO_SAFE_TEXT_MIN, 8000),
75
+ };
76
+ }
77
+
29
78
  function collapse(text) {
30
79
  return String(text ?? '').replace(/\s+/g, ' ').trim();
31
80
  }
@@ -114,6 +163,49 @@ function splitEntryGroups(lines) {
114
163
  return groups;
115
164
  }
116
165
 
166
+ /**
167
+ * 段落内按行切块:只要「行号跨度 > maxSpan」或「归一化字符数 > maxText」就继续切,
168
+ * 每个块的 startLine/endLine 都来自真实行号,不伪造锚点。单行本身超 maxText 时按
169
+ * 字符切,行锚点仍是同一行(autoResolve 重读整行会判 text_size,留人工,不属于静默错误)。
170
+ */
171
+ function splitOversizedUnit(unit, { maxSpan = 0, maxText = 0 } = {}) {
172
+ const spanCap = Number.isFinite(maxSpan) && maxSpan > 0 ? Math.floor(maxSpan) : Infinity;
173
+ const textCap = Number.isFinite(maxText) && maxText > 0 ? Math.floor(maxText) : Infinity;
174
+ const sourceLines = Array.isArray(unit.lines) && unit.lines.length ? unit.lines : null;
175
+ const span = unit.endLine - unit.startLine + 1;
176
+ const length = collapse(stripComments(unit.text)).length;
177
+ if (span <= spanCap && length <= textCap) return [unit];
178
+ if (!sourceLines) return [unit];
179
+
180
+ const chunks = [];
181
+ let chunk = [];
182
+ const flush = () => {
183
+ if (!chunk.length) return;
184
+ const text = chunk.map((line) => line.text).join('\n').trim();
185
+ if (text) chunks.push({ text, startLine: chunk[0].number, endLine: chunk[chunk.length - 1].number });
186
+ chunk = [];
187
+ };
188
+ for (const line of sourceLines) {
189
+ if (chunk.length) {
190
+ const nextSpan = line.number - chunk[0].number + 1;
191
+ const nextText = `${chunk.map((item) => item.text).join('\n')}\n${line.text}`;
192
+ if (nextSpan > spanCap || collapse(stripComments(nextText)).length > textCap) flush();
193
+ }
194
+ if (!chunk.length && collapse(stripComments(line.text)).length > textCap) {
195
+ const raw = String(line.text);
196
+ for (let start = 0; start < raw.length; start += textCap) {
197
+ const piece = raw.slice(start, start + textCap);
198
+ if (!piece.trim()) continue;
199
+ chunks.push({ text: piece, startLine: line.number, endLine: line.number });
200
+ }
201
+ continue;
202
+ }
203
+ chunk.push(line);
204
+ }
205
+ flush();
206
+ return chunks.length ? chunks : [unit];
207
+ }
208
+
117
209
  /**
118
210
  * Paragraphs of a journal file. Headings are dropped; a block that holds only
119
211
  * HTML comments (the usual `<!-- affect: N | reason -->` on its own line)
@@ -122,8 +214,11 @@ function splitEntryGroups(lines) {
122
214
  * Returns `{ text, startLine, endLine }` where the line numbers are 1-based
123
215
  * inside `body`, shifted by `lineOffset` when the caller wants file lines.
124
216
  * `splitEntries` (off by default) cuts a compact block into its entry units.
217
+ *
218
+ * 2.3.0 lane pipeline:`maxSpan` / `maxText` >0 时,超过上限的段落在返回前切成
219
+ * 多个单元(行锚点保留在真实行号上)。只影响提案流,不改 journal 文件。
125
220
  */
126
- function paragraphUnits(body, { splitEntries = false, lineOffset = 0 } = {}) {
221
+ function paragraphUnits(body, { splitEntries = false, lineOffset = 0, maxSpan = 0, maxText = 0 } = {}) {
127
222
  const lines = String(body ?? '').split(/\r?\n/);
128
223
  const blocks = [];
129
224
  let block = null;
@@ -142,9 +237,10 @@ function paragraphUnits(body, { splitEntries = false, lineOffset = 0 } = {}) {
142
237
 
143
238
  const units = [];
144
239
  let pending = null;
145
- const attach = (target, text, lastLine) => {
240
+ const attach = (target, text, lastLine, lineList) => {
146
241
  target.text = `${target.text}\n${text}`;
147
242
  target.endLine = lastLine;
243
+ target.lines = [...(target.lines ?? []), ...lineList];
148
244
  };
149
245
  for (const raw of blocks) {
150
246
  const kept = raw.filter((line) => !/^\s{0,3}#{1,6}\s/.test(line.text));
@@ -152,8 +248,8 @@ function paragraphUnits(body, { splitEntries = false, lineOffset = 0 } = {}) {
152
248
  const cleaned = kept.map((line) => line.text).join('\n').trim();
153
249
  if (!collapse(stripComments(cleaned))) {
154
250
  const target = units[units.length - 1] ?? pending;
155
- if (target) attach(target, cleaned, kept[kept.length - 1].number);
156
- else pending = { text: cleaned, startLine: kept[0].number, endLine: kept[kept.length - 1].number };
251
+ if (target) attach(target, cleaned, kept[kept.length - 1].number, kept);
252
+ else pending = { text: cleaned, startLine: kept[0].number, endLine: kept[kept.length - 1].number, lines: kept };
157
253
  continue;
158
254
  }
159
255
  const groups = splitEntries ? splitEntryGroups(kept) : [kept];
@@ -167,21 +263,29 @@ function paragraphUnits(body, { splitEntries = false, lineOffset = 0 } = {}) {
167
263
  text: `${pending.text}\n${text}`,
168
264
  startLine: pending.startLine,
169
265
  endLine,
266
+ lines: [...(pending.lines ?? []), ...group],
170
267
  });
171
268
  pending = null;
172
269
  } else {
173
- units.push({ text, startLine, endLine });
270
+ units.push({ text, startLine, endLine, lines: group });
174
271
  }
175
272
  }
176
273
  }
177
- if (pending) units.push(pending);
178
- return units.map((unit) => ({
274
+ if (pending) units.push({ ...pending, lines: pending.lines ?? [] });
275
+ const capped = spanCapWanted(maxSpan, maxText)
276
+ ? units.flatMap((unit) => splitOversizedUnit(unit, { maxSpan, maxText }))
277
+ : units;
278
+ return capped.map((unit) => ({
179
279
  text: unit.text,
180
280
  startLine: unit.startLine + lineOffset,
181
281
  endLine: unit.endLine + lineOffset,
182
282
  }));
183
283
  }
184
284
 
285
+ function spanCapWanted(maxSpan, maxText) {
286
+ return (Number.isFinite(maxSpan) && maxSpan > 0) || (Number.isFinite(maxText) && maxText > 0);
287
+ }
288
+
185
289
  function parseAffectComment(comment) {
186
290
  const inner = comment.replace(/^<!--/, '').replace(/-->$/, '').trim();
187
291
  const rest = inner.replace(/^affect\b/i, '');
@@ -477,6 +581,117 @@ function lastDayOf(value) {
477
581
  return /^\d{4}-\d{2}-\d{2}/.test(value) ? value.slice(0, 10) : null;
478
582
  }
479
583
 
584
+ function sha256Text(text) {
585
+ return crypto.createHash('sha256').update(String(text ?? ''), 'utf8').digest('hex');
586
+ }
587
+
588
+ /** Stable content identity: the same paragraph always maps to the same 16 hex chars. */
589
+ function contentKeyOf(normalizedText) {
590
+ return sha256Text(normalizedText).slice(0, 16);
591
+ }
592
+
593
+ /** `<source journal>@<first line>` — a paragraph can only start once in an append-only journal. */
594
+ function sourceAnchorOf(entry) {
595
+ const rel = typeof entry?.source === 'string' ? entry.source.trim() : '';
596
+ const start = Number(entry?.lineStart);
597
+ return rel && Number.isInteger(start) && start > 0 ? `${rel}@${start}` : '';
598
+ }
599
+
600
+ function normalizeMatch(text) {
601
+ return collapse(stripComments(text)).toLowerCase();
602
+ }
603
+
604
+ function clampInt(value, fallback) {
605
+ const number = Number(value);
606
+ if (!Number.isFinite(number) || number < 1) return fallback;
607
+ return Math.min(Math.floor(number), 1000);
608
+ }
609
+
610
+ /**
611
+ * Re-read the journal line range a proposal points at. The journal is
612
+ * append-only, so the range stays valid; a missing file, a short file or an
613
+ * out-of-range start means the source drifted and the proposal must not be
614
+ * auto-accepted. One read per file per run (427 proposals over ~10 files).
615
+ */
616
+ function readSourceRange(root, entry, lineCache) {
617
+ const rel = typeof entry?.source === 'string' ? entry.source.trim() : '';
618
+ if (!rel) return null;
619
+ const start = Number(entry?.lineStart);
620
+ if (!Number.isInteger(start) || start < 1) return null;
621
+ const stopRaw = Number(entry?.lineEnd);
622
+ const stop = Number.isInteger(stopRaw) && stopRaw >= start ? stopRaw : start;
623
+ let lines = lineCache.get(rel);
624
+ if (lines === undefined) {
625
+ lines = null;
626
+ try {
627
+ const abs = resolveInside(root, rel);
628
+ if (fs.existsSync(abs)) lines = fs.readFileSync(abs, 'utf8').split(/\r?\n/);
629
+ } catch {
630
+ lines = null;
631
+ }
632
+ lineCache.set(rel, lines);
633
+ }
634
+ if (!lines || start > lines.length) return null;
635
+ const text = collapse(stripComments(lines.slice(start - 1, Math.min(stop, lines.length)).join('\n')));
636
+ return { rel, start, text, truncated: stop > lines.length };
637
+ }
638
+
639
+ /**
640
+ * Index used for "exact duplicate" detection. Only exact identity counts:
641
+ * contentKeys content_key written by an earlier auto-accept card
642
+ * sourceKeys source journal + first line of an earlier consolidated card
643
+ * claims normalized title / first body line of every topic card
644
+ * No token overlap, no similarity.
645
+ */
646
+ function buildAutoCardIndex(root) {
647
+ const index = {
648
+ contentKeys: new Map(),
649
+ sourceKeys: new Map(),
650
+ claims: new Map(),
651
+ };
652
+ let cards = [];
653
+ try {
654
+ cards = scanCards(root);
655
+ } catch {
656
+ cards = [];
657
+ }
658
+ for (const card of cards) {
659
+ if (!card || typeof card.rel !== 'string' || !card.rel.startsWith('topics/')) continue;
660
+ const extras = card.extras && typeof card.extras === 'object' ? card.extras : {};
661
+ const contentKey = typeof extras.content_key === 'string' ? extras.content_key.trim() : '';
662
+ if (contentKey) index.contentKeys.set(contentKey, card.rel);
663
+ const title = collapse(card.title ?? card.fields?.title ?? '');
664
+ if (title) index.claims.set(title.toLowerCase(), card.rel);
665
+ const firstLine = String(card.body ?? '')
666
+ .split(/\r?\n/)
667
+ .map((line) => collapse(line))
668
+ .find((line) => line !== '' && !line.startsWith('#'));
669
+ if (firstLine) index.claims.set(firstLine.toLowerCase(), card.rel);
670
+ const journal = typeof extras.source_journal === 'string' ? extras.source_journal.trim() : '';
671
+ const lines = /^(\d+)(?:-(\d+))?$/.exec(String(extras.source_lines ?? '').trim());
672
+ if (journal && lines) index.sourceKeys.set(`${journal}@${lines[1]}`, card.rel);
673
+ }
674
+ return index;
675
+ }
676
+
677
+ /**
678
+ * THE single card-writing path for an accepted proposal. Manual accept and the
679
+ * 2.2.0 automatic accept both call this (same writeCard, same frontmatter).
680
+ */
681
+ function writeAcceptedCard(root, entry, { now, rel, title, body, extras }) {
682
+ return writeCard(root, {
683
+ rel,
684
+ title,
685
+ body,
686
+ fields: {
687
+ date: entry.day ?? dayString(now),
688
+ tags: ['consolidation'],
689
+ salience: Number.isInteger(entry.salience) ? entry.salience : 3,
690
+ },
691
+ extras,
692
+ }, { now });
693
+ }
694
+
480
695
  function proposalBacklog(entries) {
481
696
  const list = Array.isArray(entries) ? entries.filter((entry) => entry && typeof entry.id === 'string') : [];
482
697
  const counts = { proposed: 0, accepted: 0, rejected: 0, superseded: 0 };
@@ -502,14 +717,27 @@ function proposalBacklog(entries) {
502
717
  };
503
718
  }
504
719
 
720
+ /**
721
+ * The consolidated pointer walks days in order and stops at the FIRST day that
722
+ * still has an unresolved proposal.
723
+ *
724
+ * 2.1.0 skipped such a day and kept advancing (`if ... continue`), which let the
725
+ * pointer jump over a pending middle day and made `lastConsolidated` mean
726
+ * "newest fully-resolved day" instead of "everything up to here is dealt with".
727
+ * 2.2.0 must not skip: pending entries of an older day stay visible until they
728
+ * are resolved (BACKLOG-ANALYSIS.md §3.5).
729
+ */
505
730
  function advanceLastConsolidated(state, entries) {
506
731
  const current = lastDayOf(state.lastConsolidated);
507
- const days = [...new Set(entries.map((entry) => entry.day).filter((day) => typeof day === 'string'))].sort();
732
+ const list = Array.isArray(entries) ? entries.filter((entry) => entry && typeof entry.day === 'string') : [];
733
+ const days = [...new Set(list.map((entry) => entry.day))].sort();
508
734
  let last = current;
509
735
  for (const day of days) {
510
736
  if (last !== null && day <= last) continue;
511
- const dayEntries = entries.filter((entry) => entry.day === day);
512
- if (dayEntries.length > 0 && dayEntries.every((entry) => RESOLVED_STATUS.has(entry.status))) last = day;
737
+ const dayEntries = list.filter((entry) => entry.day === day);
738
+ if (dayEntries.length === 0) continue;
739
+ if (!dayEntries.every((entry) => RESOLVED_STATUS.has(entry.status))) break;
740
+ last = day;
513
741
  }
514
742
  return last;
515
743
  }
@@ -554,21 +782,18 @@ export function resolveConsolidationProposal(args = {}, config = {}) {
554
782
  `- source: ${entry.source ?? 'journal'}${entry.lineStart ? `:${entry.lineStart}-${entry.lineEnd}` : ''}`,
555
783
  `- accepted_at: ${now.toISOString()}`,
556
784
  ].join('\n');
557
- card = writeCard(root, {
785
+ // 2.2.0 lane A: one card-writing path for manual accept AND auto-accept.
786
+ card = writeAcceptedCard(root, entry, {
787
+ now,
558
788
  rel,
559
789
  title,
560
790
  body,
561
- fields: {
562
- date: entry.day ?? dayString(now),
563
- tags: ['consolidation'],
564
- salience: Number.isInteger(entry.salience) ? entry.salience : 3,
565
- },
566
791
  extras: {
567
792
  consolidation_proposal: proposalIdValue,
568
793
  source_journal: entry.source ?? '',
569
794
  source_lines: entry.lineStart ? `${entry.lineStart}-${entry.lineEnd}` : '',
570
795
  },
571
- }, { now });
796
+ });
572
797
  entries[index] = { ...entry, status: 'accepted', resolvedAt: now.toISOString(), card: rel };
573
798
  } else {
574
799
  const reason = collapse(args.reason ?? '').slice(0, 300);
@@ -646,6 +871,9 @@ function memoryConsolidateLegacy(args = {}, config = {}) {
646
871
  // but cut points are only safe when the caller knows segment labels do not
647
872
  // overlap (F6 in the A-group manifest: A-14 L59-73 and A-15 L71-72 do overlap).
648
873
  const entrySplit = args.entrySplit === true;
874
+ // 2.3.0 lane pipeline(W1-3):提案在进入积压前就按 ≤maxSpan 行 / ≤maxText 字切好,
875
+ // 这样 autoResolve 面对的新提案本身可判;journal 文件不动,只切提案单元。
876
+ const unitLimits = autoUnitLimits(config);
649
877
  const newEntries = [];
650
878
  const allTopicCards = scanCards(root).filter((card) => card.rel.startsWith('topics/'));
651
879
  // Locked cards are core memory: they are never merge targets (and journal
@@ -657,7 +885,6 @@ function memoryConsolidateLegacy(args = {}, config = {}) {
657
885
  const proposals = [];
658
886
  const undated = [];
659
887
  const badAffect = [];
660
- const scannedDays = new Set();
661
888
  let entries = 0;
662
889
  let duplicates = 0;
663
890
 
@@ -669,15 +896,14 @@ function memoryConsolidateLegacy(args = {}, config = {}) {
669
896
  // paragraphUnits numbers lines inside the body; shift them to file lines.
670
897
  const lineOffset = text.slice(0, parsed.bodyStart).split(/\r?\n/).length - 1;
671
898
  if (sinceDay && !fileDay) {
672
- for (const unit of paragraphUnits(parsed.body, { lineOffset })) {
899
+ for (const unit of paragraphUnits(parsed.body, { lineOffset, ...unitLimits })) {
673
900
  undated.push({ source: rel, excerpt: collapse(stripComments(unit.text)).slice(0, 120) });
674
901
  }
675
902
  continue;
676
903
  }
677
904
  if (sinceDay && fileDay <= sinceDay) continue;
678
- if (fileDay) scannedDays.add(fileDay);
679
905
 
680
- for (const unit of paragraphUnits(parsed.body, { splitEntries: entrySplit, lineOffset })) {
906
+ for (const unit of paragraphUnits(parsed.body, { splitEntries: entrySplit, lineOffset, ...unitLimits })) {
681
907
  entries += 1;
682
908
  const paragraphText = collapse(stripComments(unit.text));
683
909
  const affect = parseAffect(unit.text);
@@ -734,23 +960,16 @@ function memoryConsolidateLegacy(args = {}, config = {}) {
734
960
  }
735
961
  }
736
962
 
737
- // The newest day this run actually scanned is the only candidate for the
738
- // incremental pointer. It moves only when every proposal recorded for that
739
- // day is resolved; newly proposed ids keep it pinned, which is the point.
740
- const candidateDay = [...scannedDays].sort().pop() ?? null;
963
+ // 2.2.0 lane A: the incremental pointer now walks every fully resolved day in
964
+ // order and stops at the first day that still has a pending proposal
965
+ // (advanceLastConsolidated never skips a middle day). 2.1.0 only considered
966
+ // the newest scanned day, so a backlog on an older day could never close.
741
967
  const currentLastDay = lastDayOf(state.lastConsolidated);
742
968
  const allEntries = [...seenProposals, ...newEntries];
743
969
  const backlog = proposalBacklog(allEntries);
744
- let lastConsolidated = state.lastConsolidated ?? null;
745
- let stateUpdated = false;
746
- if (candidateDay) {
747
- const dayEntries = allEntries.filter((entry) => entry.day === candidateDay);
748
- const unresolved = dayEntries.filter((entry) => !RESOLVED_STATUS.has(entry.status));
749
- if (dayEntries.length > 0 && unresolved.length === 0 && (!currentLastDay || candidateDay > currentLastDay)) {
750
- lastConsolidated = candidateDay;
751
- stateUpdated = true;
752
- }
753
- }
970
+ const advanced = advanceLastConsolidated(state, allEntries);
971
+ const lastConsolidated = advanced ?? state.lastConsolidated ?? null;
972
+ const stateUpdated = advanced !== currentLastDay;
754
973
 
755
974
  const stateChanged = newEntries.length > 0 || stateUpdated;
756
975
  let stateWrite = null;
@@ -811,8 +1030,291 @@ function memoryConsolidateLegacy(args = {}, config = {}) {
811
1030
  };
812
1031
  }
813
1032
 
1033
+ /**
1034
+ * 2.2.0 lane A: auto-resolve the consolidation backlog (maintenance-side).
1035
+ *
1036
+ * Called once per day by the maintenance job. It reads ONLY memory-state.json
1037
+ * plus the journal line ranges the proposals point at, and it writes ONLY:
1038
+ * - new `topics/consolidated/<contentKey>.md` cards (single writeCard path,
1039
+ * shared with the manual accept path),
1040
+ * - status transitions in `seenProposals`,
1041
+ * - one audit line per mutation,
1042
+ * - at most ONE state write per run.
1043
+ *
1044
+ * Only exact identity may auto-resolve a proposal (no semantic similarity, no
1045
+ * coverage ratio, no probability):
1046
+ * - same proposal id already resolved -> reject `auto: duplicate`
1047
+ * - same paragraph anchor already resolved -> reject `duplicate_reproposal`
1048
+ * - same content key already on a card -> reject `auto: duplicate`
1049
+ * - claim line equals an existing card title/first line -> reject `auto: duplicate`
1050
+ * Structural anomalies (T0, BACKLOG-ANALYSIS.md appendix A/F) auto-reject:
1051
+ * - oversized unit (>= 100 lines), too short (< 18 chars) -> reject
1052
+ * - auto/turn machine-flow lines, waiting lines -> reject
1053
+ * Clean no-target paragraphs auto-accept through the T1 gates:
1054
+ * target=null, span<=10, 40..800 chars, salience>=3, source re-read matches
1055
+ * the excerpt, privacyScan clean, per-run accept cap not reached.
1056
+ * Everything else stays `proposed` for a human (merge/更正/隐私/源漂移).
1057
+ *
1058
+ * `rules` = {accept:boolean, reject:boolean} switches the two decision classes
1059
+ * (duplicate detection is always on: an exact duplicate must never be accepted).
1060
+ *
1061
+ * Options: {root, now, maxAccept, maxAcceptNew, rules}
1062
+ * maxAccept total mutations (accept+reject) for this run, default 100
1063
+ * maxAcceptNew newly written cards for this run, default 10
1064
+ * Returns the run summary; `stateWritten` is false when nothing changed, so a
1065
+ * second run on the same day is a true no-op (idempotent).
1066
+ */
1067
+ export function autoResolveProposals(options = {}) {
1068
+ const root = options.root;
1069
+ if (typeof root !== 'string' || root === '') {
1070
+ throw memoryError('E_BAD_ARGUMENT', 'autoResolveProposals 需要 memoryRoot');
1071
+ }
1072
+ const now = options.now instanceof Date && !Number.isNaN(options.now.getTime()) ? options.now : new Date();
1073
+ const rules = options.rules && typeof options.rules === 'object' ? options.rules : {};
1074
+ const maxMutations = clampInt(options.maxAccept, AUTO_MUTATIONS_PER_DAY);
1075
+ const maxNewCards = clampInt(options.maxAcceptNew, AUTO_ACCEPT_NEW_PER_DAY);
1076
+ const allowReject = rules.reject !== false;
1077
+ const allowAccept = rules.accept !== false;
1078
+ // 2.3.0 lane pipeline(W1-4):maxSpan/maxText 由 config.autoResolve 透传
1079
+ // (maintenance 以 options 形式传入),缺省仍是冻结的 AUTO_SAFE_* 值。
1080
+ const unitLimits = {
1081
+ maxSpan: boundedInt(options.maxSpan, AUTO_SAFE_SPAN_MAX, 1, 200),
1082
+ maxText: boundedInt(options.maxText, AUTO_SAFE_TEXT_MAX, AUTO_SAFE_TEXT_MIN, 8000),
1083
+ };
1084
+
1085
+ const state = readState(root);
1086
+ const entries = (Array.isArray(state.seenProposals) ? state.seenProposals : [])
1087
+ .filter((entry) => entry && typeof entry.id === 'string');
1088
+ const pending = entries.filter((entry) => !RESOLVED_STATUS.has(entry.status));
1089
+ const ordered = [...pending].sort((a, b) => {
1090
+ const dayA = typeof a.day === 'string' ? a.day : '';
1091
+ const dayB = typeof b.day === 'string' ? b.day : '';
1092
+ if (dayA !== dayB) return dayA.localeCompare(dayB);
1093
+ return (Number(a.lineStart) || 0) - (Number(b.lineStart) || 0);
1094
+ });
1095
+
1096
+ const lineCache = new Map();
1097
+ const cardIndex = buildAutoCardIndex(root);
1098
+ const indexOf = new Map(entries.map((entry, index) => [entry, index]));
1099
+ const resolvedIds = new Set();
1100
+ const historyByAnchor = new Map();
1101
+ for (const entry of entries) {
1102
+ if (RESOLVED_STATUS.has(entry.status)) resolvedIds.add(entry.id);
1103
+ const anchor = sourceAnchorOf(entry);
1104
+ if (!anchor) continue;
1105
+ if (!historyByAnchor.has(anchor)) historyByAnchor.set(anchor, []);
1106
+ historyByAnchor.get(anchor).push(entry);
1107
+ }
1108
+
1109
+ const claimedContentKeys = new Set();
1110
+ const claimedAnchors = new Set();
1111
+ const reviewReasons = {};
1112
+ const cards = [];
1113
+ const mutations = [];
1114
+ let accepted = 0;
1115
+ let rejected = 0;
1116
+ let reviewed = 0;
1117
+
1118
+ for (const entry of ordered) {
1119
+ if (mutations.length >= maxMutations) break;
1120
+ const anchor = sourceAnchorOf(entry);
1121
+ const src = readSourceRange(root, entry, lineCache);
1122
+ const siblings = anchor ? (historyByAnchor.get(anchor) ?? []).filter((other) => other !== entry) : [];
1123
+ const resolvedSibling = siblings.find((other) => RESOLVED_STATUS.has(other.status)) ?? null;
1124
+ const peer = siblings.find((other) => !RESOLVED_STATUS.has(other.status)) ?? null;
1125
+
1126
+ let verdict;
1127
+ if (resolvedIds.has(entry.id) || (anchor !== '' && claimedAnchors.has(anchor))) {
1128
+ const skip = resolvedIds.has(entry.id) ? 'proposal-id-already-resolved' : 'same-run-anchor';
1129
+ verdict = { action: 'reject', rule: 'duplicate', reason: `auto: duplicate skip=${skip}` };
1130
+ } else if (!src) {
1131
+ verdict = { action: 'review', rule: 'source_unavailable', reason: 'source_unavailable' };
1132
+ } else {
1133
+ const text = src.text;
1134
+ const spanRaw = Number(entry.lineEnd);
1135
+ const span = Number.isInteger(spanRaw) && spanRaw >= src.start ? spanRaw - src.start + 1 : 1;
1136
+ const contentKey = contentKeyOf(text);
1137
+ const claimNorm = normalizeMatch(entry.excerpt ?? '');
1138
+ const cardRel = `topics/consolidated/${contentKey}.md`;
1139
+ const cardByContent = cardIndex.contentKeys.get(contentKey) ?? null;
1140
+ const cardBySource = anchor ? (cardIndex.sourceKeys.get(anchor) ?? null) : null;
1141
+ const claimCard = claimNorm ? (cardIndex.claims.get(claimNorm) ?? null) : null;
1142
+ if (cardByContent || cardBySource || claimCard || claimedContentKeys.has(contentKey)) {
1143
+ const skip = cardByContent ? `card:${cardByContent}`
1144
+ : cardBySource ? `card:${cardBySource}`
1145
+ : claimCard ? `claim:${claimCard}` : 'same-run-content';
1146
+ verdict = { action: 'reject', rule: 'duplicate', reason: `auto: duplicate skip=${skip}`, contentKey, anchor };
1147
+ } else if (resolvedSibling || peer) {
1148
+ const holder = resolvedSibling ?? peer;
1149
+ verdict = {
1150
+ action: 'reject',
1151
+ rule: 'duplicate_reproposal',
1152
+ reason: `duplicate_reproposal: same paragraph already ${resolvedSibling ? 'resolved' : 'pending'} as ${holder.id}`,
1153
+ contentKey,
1154
+ anchor,
1155
+ };
1156
+ } else if (allowReject && span >= AUTO_OVERSIZED_SPAN) {
1157
+ verdict = { action: 'reject', rule: 'oversized_unit', reason: `oversized_unit(span=${span}): journal paragraph too large; re-propose after entrySplit/fix`, contentKey, anchor };
1158
+ } else if (allowReject && text.length < AUTO_MIN_TEXT) {
1159
+ verdict = { action: 'reject', rule: 'unit_too_short', reason: `unit_too_short(norm=${text.length})`, contentKey, anchor };
1160
+ } else if (allowReject && AUTO_FLOW_PATTERN.test(text)) {
1161
+ verdict = { action: 'reject', rule: 'machine_flow_log', reason: 'machine_flow_log: auto:land/turn line; source-of-truth=.longlive/hardgate/land-log.jsonl', contentKey, anchor };
1162
+ } else if (allowReject && AUTO_WAIT_PATTERN.test(text)) {
1163
+ verdict = { action: 'reject', rule: 'no_new_instruction', reason: 'no_new_instruction: waiting line, no durable claim', contentKey, anchor };
1164
+ } else if (AUTO_HUMAN_PATTERN.test(text)) {
1165
+ verdict = { action: 'review', rule: 'needs_human', reason: 'needs_human: 事实/更正/隐私类关键词命中' };
1166
+ } else if (entry.target !== null && entry.target !== undefined && entry.target !== '') {
1167
+ verdict = { action: 'review', rule: 'merge_needed', reason: 'merge_needed: 已有目标卡,等人工合并' };
1168
+ } else if (span > unitLimits.maxSpan) {
1169
+ verdict = { action: 'review', rule: 'span_too_large', reason: `span=${span} 超出自动建卡上限 ${unitLimits.maxSpan}` };
1170
+ } else if (text.length < AUTO_SAFE_TEXT_MIN || text.length > unitLimits.maxText) {
1171
+ verdict = { action: 'review', rule: 'text_size', reason: `text_len=${text.length} 超出自动建卡区间 [${AUTO_SAFE_TEXT_MIN},${unitLimits.maxText}]` };
1172
+ } else if (!Number.isInteger(entry.salience) || entry.salience < 3) {
1173
+ verdict = { action: 'review', rule: 'low_salience', reason: `salience=${entry.salience ?? 'null'} < 3` };
1174
+ } else if (claimNorm === '' || !normalizeMatch(text).includes(claimNorm)) {
1175
+ // The stored excerpt is the picked claim (pickClaim), not necessarily a
1176
+ // prefix of the paragraph, so verify that the quoted claim still occurs
1177
+ // inside the re-read source range — an exact substring check, never a
1178
+ // similarity score.
1179
+ verdict = { action: 'review', rule: 'source_mismatch', reason: 'source_mismatch: 重读段落与提案摘录不一致(源可能已变更)' };
1180
+ } else if (fs.existsSync(resolveInside(root, cardRel))) {
1181
+ verdict = { action: 'reject', rule: 'duplicate', reason: `auto: duplicate skip=card-file:${cardRel}`, contentKey, anchor };
1182
+ } else if (privacyScan(text).verdict !== 'none') {
1183
+ verdict = { action: 'review', rule: 'privacy', reason: 'privacy: privacyScan 命中 local_only,不自动入卡' };
1184
+ } else if (!allowAccept || accepted >= maxNewCards) {
1185
+ verdict = { action: 'review', rule: 'accept_cap', reason: `accept_cap: 每日自动建卡上限 ${maxNewCards} 已到` };
1186
+ } else {
1187
+ verdict = { action: 'accept', rule: 'accept', contentKey, anchor, src, cardRel };
1188
+ }
1189
+ }
1190
+
1191
+ if (verdict.action === 'review') {
1192
+ reviewed += 1;
1193
+ reviewReasons[verdict.rule] = (reviewReasons[verdict.rule] ?? 0) + 1;
1194
+ continue;
1195
+ }
1196
+
1197
+ const entryIndex = indexOf.get(entry);
1198
+ if (verdict.action === 'accept') {
1199
+ const text = verdict.src.text;
1200
+ const stop = Math.max(verdict.src.start, Number(entry.lineEnd) || verdict.src.start);
1201
+ const sourceLines = `${verdict.src.start}-${stop}`;
1202
+ const sourceSha256 = sha256Text(text);
1203
+ const title = collapse(text).slice(0, 80);
1204
+ const body = [
1205
+ `# ${title}`,
1206
+ '',
1207
+ text,
1208
+ '',
1209
+ `- content_key: ${verdict.contentKey}`,
1210
+ `- source: ${verdict.src.rel}:${sourceLines}`,
1211
+ `- source_sha256: ${sourceSha256}`,
1212
+ `- proposal: ${entry.id}`,
1213
+ `- accepted_at: ${now.toISOString()}`,
1214
+ '- auto: accept (2.2.0 lane A: 无目标 + 短段 + 干净 + 源文校验)',
1215
+ ].join('\n');
1216
+ const card = writeAcceptedCard(root, entry, {
1217
+ now,
1218
+ rel: verdict.cardRel,
1219
+ title,
1220
+ body,
1221
+ extras: {
1222
+ content_key: verdict.contentKey,
1223
+ source_journal: verdict.src.rel,
1224
+ source_lines: sourceLines,
1225
+ source_sha256: sourceSha256,
1226
+ proposal_legacy_id: entry.id,
1227
+ auto: 'accept',
1228
+ },
1229
+ });
1230
+ const claimedAnchor = verdict.anchor || sourceAnchorOf(entry);
1231
+ entries[entryIndex] = {
1232
+ ...entry,
1233
+ status: 'accepted',
1234
+ resolvedAt: now.toISOString(),
1235
+ card: card.rel,
1236
+ auto: true,
1237
+ autoRule: 'accept',
1238
+ contentKey: verdict.contentKey,
1239
+ sourceSha256,
1240
+ };
1241
+ accepted += 1;
1242
+ claimedContentKeys.add(verdict.contentKey);
1243
+ if (claimedAnchor) claimedAnchors.add(claimedAnchor);
1244
+ mutations.push(entry.id);
1245
+ cards.push(card.rel);
1246
+ appendAudit(root, {
1247
+ action: 'memory_consolidate_accept',
1248
+ object: entry.id,
1249
+ result: `card=${card.rel} auto: ${verdict.rule}`,
1250
+ now,
1251
+ });
1252
+ } else {
1253
+ const reason = verdict.reason.slice(0, 300);
1254
+ entries[entryIndex] = {
1255
+ ...entry,
1256
+ status: 'rejected',
1257
+ resolvedAt: now.toISOString(),
1258
+ reason,
1259
+ auto: true,
1260
+ autoRule: verdict.rule,
1261
+ ...(verdict.contentKey ? { contentKey: verdict.contentKey } : {}),
1262
+ };
1263
+ rejected += 1;
1264
+ if (verdict.contentKey) claimedContentKeys.add(verdict.contentKey);
1265
+ const claimedAnchor = verdict.anchor || sourceAnchorOf(entry);
1266
+ if (claimedAnchor) claimedAnchors.add(claimedAnchor);
1267
+ mutations.push(entry.id);
1268
+ appendAudit(root, {
1269
+ action: 'memory_consolidate_reject',
1270
+ object: entry.id,
1271
+ result: `reason=${reason.slice(0, 200)} auto: ${verdict.rule}`,
1272
+ now,
1273
+ });
1274
+ }
1275
+ }
1276
+
1277
+ const previousLastConsolidated = lastDayOf(state.lastConsolidated);
1278
+ const lastConsolidated = advanceLastConsolidated(state, entries);
1279
+ const pointerMoved = lastConsolidated !== previousLastConsolidated;
1280
+ let write = null;
1281
+ if (mutations.length > 0 || pointerMoved) {
1282
+ write = updateState(root, {
1283
+ seenProposals: entries,
1284
+ ...(pointerMoved ? { lastConsolidated } : {}),
1285
+ }, { now });
1286
+ }
1287
+ const backlog = proposalBacklog(entries);
1288
+ return {
1289
+ ok: true,
1290
+ status: mutations.length > 0 ? 'auto-resolve' : 'noop',
1291
+ root,
1292
+ accepted,
1293
+ rejected,
1294
+ reviewed,
1295
+ reviewReasons,
1296
+ mutations: mutations.length,
1297
+ cards,
1298
+ audits: mutations.length,
1299
+ pending: backlog.pending,
1300
+ previousLastConsolidated,
1301
+ lastConsolidated,
1302
+ pointerMoved,
1303
+ capReached: mutations.length >= maxMutations,
1304
+ maxAccept: maxMutations,
1305
+ maxAcceptNew: maxNewCards,
1306
+ stateWritten: Boolean(write),
1307
+ write: write ? { sha256: write.write?.sha256 ?? null, bytes: write.write?.bytes ?? null } : null,
1308
+ backlog,
1309
+ message:
1310
+ `自动处理 ${mutations.length} 条(accept ${accepted} / reject ${rejected}),留人工 ${reviewed} 条;` +
1311
+ `pending=${backlog.pending};lastConsolidated=${lastConsolidated ?? 'null'}`,
1312
+ };
1313
+ }
1314
+
814
1315
  export {
815
1316
  contentTokens, buildCardIndex, cosineScore, coverageScore, pickQuote, pickClaim, paragraphUnits,
1317
+ proposalBacklog,
816
1318
  };
817
1319
 
818
1320
  /**