@jjh32456/longlive 2.2.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 (47) hide show
  1. package/CHANGELOG.md +79 -0
  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 +132 -67
  7. package/cordis.patch.yml +1 -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 +104 -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/features.js +14 -0
  27. package/src/gate/action-gate.js +234 -45
  28. package/src/memory/backup-retention.mjs +823 -0
  29. package/src/memory/cards.js +73 -12
  30. package/src/memory/conflict-scan.mjs +356 -0
  31. package/src/memory/conflicts.js +202 -9
  32. package/src/memory/consolidate.js +100 -13
  33. package/src/memory/decay.js +133 -19
  34. package/src/memory/event-index.js +62 -4
  35. package/src/memory/forget-scheduler.mjs +303 -0
  36. package/src/memory/forget-v2.js +94 -8
  37. package/src/memory/index-cache.mjs +216 -0
  38. package/src/memory/index.js +149 -15
  39. package/src/memory/lock.js +53 -12
  40. package/src/memory/maintenance.js +172 -17
  41. package/src/memory/recall-feedback.mjs +159 -17
  42. package/src/memory/state.js +446 -38
  43. package/src/memory/task-state.mjs +569 -0
  44. package/src/recall/brain.mjs +8 -1
  45. package/src/recall/continuity-volatile.mjs +131 -1
  46. package/src/tools.js +108 -33
  47. package/src/ui/routes-readonly.js +63 -5
@@ -159,8 +159,9 @@ export function unifiedConflicts({ memoryRoot, includeLifecycle = false } = {})
159
159
  // ∧ 该卡对尚无 conflicts_with 边
160
160
  // ∧ 结论行/frontmatter 不是完全同文(同文是重复而非冲突)
161
161
  // → 只产候选,不改卡、不合并、不写 history。上限 maxPairs(32) 对。
162
- // - 候选落盘:`.longlive/hardgate/conflict-candidates.jsonl`(append-only;
163
- // pending <= maxPending(200) 且 90 天保留;卡对去重;archived 行只移出队列不删历史)。
162
+ // - 候选落盘:`.longlive/conflicts/candidates.jsonl`(append-only;pending <= maxPending(200)
163
+ // 且 90 天保留;卡对去重;archived 行只移出队列不删历史)。2.0.0–2.2.0 旧账本
164
+ // `.longlive/hardgate/conflict-candidates.jsonl` 只读兼容合并(同一卡对:新账本行胜)。
164
165
  // - accept:appendConflictEdge 校验双卡存在 + type 白名单 + 幂等去重;向
165
166
  // `.longlive/recall/edges.jsonl` append 恰 1 条边;向 `.longlive/hardgate/auto-authz.jsonl`
166
167
  // append 恰 1 行 kind=conflict-accept 审计;返回 {ok,edge,auditPath}。
@@ -171,7 +172,12 @@ export function unifiedConflicts({ memoryRoot, includeLifecycle = false } = {})
171
172
  export const CONFLICT_CANDIDATE_SCHEMA = 'conflict-candidates/v1';
172
173
  /** 1.8.x prep 草案写过的 schema:读取时兼容,避免旧行被当坏行。 */
173
174
  const LEGACY_CONFLICT_CANDIDATE_SCHEMA = 'hardgate-conflict-candidate/v1';
174
- export const CONFLICT_CANDIDATES_REL = '.longlive/hardgate/conflict-candidates.jsonl';
175
+ /** 2.3.0 W2.2:写卡自动产出的候选与人工 accept 共用一本账,落在记忆根的 conflicts 目录。 */
176
+ export const CONFLICT_CANDIDATES_REL = '.longlive/conflicts/candidates.jsonl';
177
+ /** 2.0.0–2.2.0 旧账本:只读兼容(升级后的记忆根里仍有 pending 行),新行一律写 CONFLICT_CANDIDATES_REL。 */
178
+ export const LEGACY_CONFLICT_CANDIDATES_REL = '.longlive/hardgate/conflict-candidates.jsonl';
179
+ /** 写卡自动形成 conflicts_with 边时,给该卡对候选记的 accepted 原因码(不是用户裁决)。 */
180
+ export const CONFLICT_WRITE_REASON = 'auto-supersede';
175
181
  export const CONFLICT_LAST_RUN_REL = '.longlive/hardgate/last-run/conflict-candidates.json';
176
182
  export const CONFLICT_CANDIDATE_REASON = 'rule-v1';
177
183
  export const CONFLICT_ACCEPT_KIND = 'conflict-accept';
@@ -610,6 +616,10 @@ export function conflictCandidatesPathOf(memoryRoot) {
610
616
  return path.join(resolveMemoryRoot(memoryRoot), ...CONFLICT_CANDIDATES_REL.split('/'));
611
617
  }
612
618
 
619
+ export function legacyConflictCandidatesPathOf(memoryRoot) {
620
+ return path.join(resolveMemoryRoot(memoryRoot), ...LEGACY_CONFLICT_CANDIDATES_REL.split('/'));
621
+ }
622
+
613
623
  export function conflictLastRunPathOf(memoryRoot) {
614
624
  return path.join(resolveMemoryRoot(memoryRoot), ...CONFLICT_LAST_RUN_REL.split('/'));
615
625
  }
@@ -621,15 +631,19 @@ function isCandidateSchema(schema) {
621
631
  /**
622
632
  * 读候选账本。append-only:同一卡对以最后一行状态为准(pending/accepted/rejected/archived)。
623
633
  * pending 只算「latest 状态 = pending 且未过 retentionDays」的行;坏行计数不抛。
634
+ * 2.3.0 W2.2:本读取兼容旧账本(`.longlive/hardgate/conflict-candidates.jsonl`),按
635
+ * 「旧账本先、新账本后」合并,同一卡对以新账本行胜(升级后不会丢旧 pending,也不会双计)。
624
636
  */
625
637
  export function readConflictCandidates({ memoryRoot, config = {}, now = new Date() } = {}) {
626
638
  const root = resolveMemoryRoot(memoryRoot);
627
639
  const cfg = conflictCfgOf(config);
628
640
  const file = path.join(root, ...CONFLICT_CANDIDATES_REL.split('/'));
641
+ const legacyFile = path.join(root, ...LEGACY_CONFLICT_CANDIDATES_REL.split('/'));
629
642
  const store = readJsonlRows(file);
643
+ const legacyStore = legacyFile === file ? { rows: [], bad: 0, missing: true } : readJsonlRows(legacyFile);
630
644
  const rows = [];
631
- let bad = store.bad;
632
- for (const row of store.rows) {
645
+ let bad = store.bad + legacyStore.bad;
646
+ for (const row of [...legacyStore.rows, ...store.rows]) {
633
647
  if (isCandidateSchema(row?.schema) && typeof row.id === 'string' && typeof row.aCard === 'string' && typeof row.bCard === 'string') rows.push(row);
634
648
  else bad += 1;
635
649
  }
@@ -647,7 +661,19 @@ export function readConflictCandidates({ memoryRoot, config = {}, now = new Date
647
661
  const fresh = !Number.isFinite(atMs) || retentionMs === 0 || nowMs - atMs <= retentionMs;
648
662
  if (fresh) pending.push(row);
649
663
  }
650
- return { ok: true, file, rows, bad, missing: store.missing, byPair, pending, pendingCount: pending.length };
664
+ return {
665
+ ok: true,
666
+ file,
667
+ legacyFile,
668
+ legacyMissing: legacyStore.missing,
669
+ legacyRows: legacyStore.rows.length,
670
+ rows,
671
+ bad,
672
+ missing: store.missing,
673
+ byPair,
674
+ pending,
675
+ pendingCount: pending.length,
676
+ };
651
677
  }
652
678
 
653
679
  /**
@@ -690,7 +716,9 @@ export function appendConflictCandidates({
690
716
  aCard,
691
717
  bCard,
692
718
  sharedTerms: Array.isArray(candidate?.sharedTerms) ? candidate.sharedTerms.map(String) : [],
693
- confidence: Number.isFinite(Number(candidate?.confidence)) ? Number(candidate.confidence) : null,
719
+ confidence: candidate?.confidence === null || candidate?.confidence === undefined
720
+ ? null
721
+ : (Number.isFinite(Number(candidate.confidence)) ? Number(candidate.confidence) : null),
694
722
  evidence: candidate?.evidence && typeof candidate.evidence === 'object' ? candidate.evidence : { a: null, b: null },
695
723
  reason: state === 'pending' ? CONFLICT_CANDIDATE_REASON : String(reason ?? state),
696
724
  state,
@@ -722,6 +750,110 @@ export function appendConflictCandidates({
722
750
  }
723
751
  }
724
752
 
753
+ // ---- 写卡路径候选(2.3.0 W2.2:写入时自动检测 → 落盘 → memory_conflicts 可见) -----
754
+
755
+ /** 写卡检测能产出的 reason 码(cards.js detectConflicts 的三种因果,不是概率)。 */
756
+ const WRITE_CONFLICT_REASONS = new Set(['same-slug', 'same-title', 'same-key-opposite-conclusion']);
757
+ /** 写卡路径的卡 rel 白名单:只接受卡目录 + 无换行/反斜杠/.. 的相对路径。 */
758
+ const WRITE_CONFLICT_REL_PATTERN = /^(topics|journal|procedures)\/[^\r\n\\]+\.md$/i;
759
+
760
+ function writeConflictCardRel(value, memoryRoot) {
761
+ const rel = conflictCardRel(value, memoryRoot);
762
+ if (rel === '' || rel.includes('..') || !WRITE_CONFLICT_REL_PATTERN.test(rel)) return '';
763
+ return rel;
764
+ }
765
+
766
+ /**
767
+ * 卡片写入/合并后的自动冲突检测落盘(2.3.0 W2.2)。
768
+ * - 输入是 cards.js detectConflicts 的返回([{rel, title, reasons}])与刚写的新卡 {rel};
769
+ * - 候选只含 rel 与固定 reason 码 + 来源标签,**不落标题/正文/摘要**(隐私:候选不含个人数据);
770
+ * - 走 appendConflictCandidates → `.longlive/conflicts/candidates.jsonl`(pending 去重/上限/保留期同人工路径);
771
+ * - 只记候选,不改卡、不写边(边由 conflict-scan 在卡落盘成功后写;失败时候选留 pending 供人裁决)。
772
+ * 返回 {ok, disabled?, file, written, pending, candidates, skipped, code?};写盘失败返回 ok:false 不抛。
773
+ */
774
+ export function recordWriteConflictCandidates({
775
+ memoryRoot,
776
+ newCard = null,
777
+ conflicts = [],
778
+ config = {},
779
+ now = new Date(),
780
+ maxPairs = null,
781
+ } = {}) {
782
+ const root = resolveMemoryRoot(memoryRoot);
783
+ const cfg = conflictCfgOf(config);
784
+ const file = conflictCandidatesPathOf(root);
785
+ if (cfg.enabled === false) {
786
+ const ledger = readConflictCandidates({ memoryRoot: root, config, now });
787
+ return { ok: true, disabled: true, file: ledger.file, written: 0, pending: ledger.pendingCount, candidates: [], skipped: [] };
788
+ }
789
+ const newRel = writeConflictCardRel(newCard?.rel, root);
790
+ if (newRel === '') {
791
+ return {
792
+ ok: false,
793
+ disabled: false,
794
+ code: 'E_HG_CONFLICT_TARGET',
795
+ message: 'E_HG_CONFLICT_TARGET: newCard.rel must be a topics/ journal/ procedures/ card rel',
796
+ file,
797
+ written: 0,
798
+ pending: null,
799
+ candidates: [],
800
+ skipped: [],
801
+ };
802
+ }
803
+ const cap = Math.max(0, Number(maxPairs ?? cfg.maxPairs) || 0);
804
+ const candidates = [];
805
+ const skipped = [];
806
+ const seen = new Set();
807
+ for (const conflict of Array.isArray(conflicts) ? conflicts : []) {
808
+ if (candidates.length >= cap) break;
809
+ const oldRel = writeConflictCardRel(conflict?.rel, root);
810
+ if (oldRel === '' || oldRel === newRel) {
811
+ skipped.push({ rel: String(conflict?.rel ?? ''), reason: oldRel === newRel ? 'self' : 'unsafe-rel' });
812
+ continue;
813
+ }
814
+ const reasons = (Array.isArray(conflict?.reasons) ? conflict.reasons : [])
815
+ .map((reason) => String(reason))
816
+ .filter((reason) => WRITE_CONFLICT_REASONS.has(reason));
817
+ if (reasons.length === 0) {
818
+ skipped.push({ rel: oldRel, reason: 'unknown-reason' });
819
+ continue;
820
+ }
821
+ const pairKey = conflictPairKey(newRel, oldRel);
822
+ if (seen.has(pairKey)) continue;
823
+ seen.add(pairKey);
824
+ const ordered = newRel <= oldRel ? [newRel, oldRel] : [oldRel, newRel];
825
+ candidates.push({
826
+ id: conflictCandidateId(newRel, oldRel),
827
+ aCard: ordered[0],
828
+ bCard: ordered[1],
829
+ sharedTerms: [],
830
+ confidence: null,
831
+ evidence: {
832
+ source: 'card-write/v1',
833
+ a: { rel: newRel, role: 'new-card', reasons },
834
+ b: { rel: oldRel, role: 'old-card', reasons },
835
+ },
836
+ });
837
+ }
838
+ const appended = appendConflictCandidates({ memoryRoot: root, candidates, config, now, state: 'pending' });
839
+ const recorded = {
840
+ ok: appended.ok !== false,
841
+ disabled: false,
842
+ file: appended.file,
843
+ written: appended.written,
844
+ archived: appended.archived,
845
+ pending: appended.pending,
846
+ corrupt: appended.corrupt,
847
+ candidates,
848
+ skipped,
849
+ };
850
+ if (appended.ok === false) {
851
+ recorded.code = appended.code;
852
+ recorded.message = appended.message;
853
+ }
854
+ return recorded;
855
+ }
856
+
725
857
  export function readConflictLastRun(memoryRoot) {
726
858
  try {
727
859
  const parsed = JSON.parse(fs.readFileSync(conflictLastRunPathOf(memoryRoot), 'utf8'));
@@ -983,22 +1115,83 @@ export function memoryConflicts(args = {}) {
983
1115
  const view = unifiedConflicts({ memoryRoot: root, includeLifecycle: args?.includeLifecycle === true });
984
1116
  const detected = detectConflictCandidates({ memoryRoot: root, config });
985
1117
  const ledger = readConflictCandidates({ memoryRoot: root, config });
1118
+ // 2.3.0 W2.2:写卡路径产出的候选与边检测候选合成一个待确认视图(同卡对以账本行为准),
1119
+ // 候选字段只含 rel/固定 reason 码/来源标签,不渲染正文(隐私)。
1120
+ const merged = new Map();
1121
+ const writePending = [];
1122
+ for (const row of ledger.pending) {
1123
+ const candidate = {
1124
+ id: row.id,
1125
+ aCard: row.aCard,
1126
+ bCard: row.bCard,
1127
+ sharedTerms: Array.isArray(row.sharedTerms) ? row.sharedTerms.map(String) : [],
1128
+ confidence: row.confidence === null || row.confidence === undefined
1129
+ ? null
1130
+ : (Number.isFinite(Number(row.confidence)) ? Number(row.confidence) : null),
1131
+ evidence: row.evidence && typeof row.evidence === 'object' ? row.evidence : null,
1132
+ // 账本里两条来源并存:写卡路径行带 evidence.source='card-write/v1';
1133
+ // 每日检测行(rule-v1)没有 evidence.source,按 reason 还原为检测来源,避免误标成写卡产物。
1134
+ source: typeof row.evidence?.source === 'string'
1135
+ ? row.evidence.source
1136
+ : (row.reason === CONFLICT_WRITE_REASON ? 'card-write' : CONFLICT_CANDIDATE_REASON),
1137
+ state: 'pending',
1138
+ };
1139
+ writePending.push(candidate);
1140
+ merged.set(conflictPairKey(row.aCard, row.bCard), candidate);
1141
+ }
1142
+ for (const candidate of detected.candidates ?? []) {
1143
+ const key = conflictPairKey(candidate.aCard, candidate.bCard);
1144
+ if (!merged.has(key)) merged.set(key, candidate);
1145
+ }
1146
+ const candidates = [...merged.values()].sort((left, right) => String(left.id).localeCompare(String(right.id)));
1147
+ const autoSuperseded = [...ledger.byPair.values()]
1148
+ .filter((row) => row.state === 'accepted' && row.reason === CONFLICT_WRITE_REASON)
1149
+ .map((row) => ({ id: row.id, aCard: row.aCard, bCard: row.bCard, at: row.at ?? null, state: 'accepted', reason: row.reason }));
986
1150
  return {
987
1151
  ok: true,
988
1152
  action: 'list',
989
1153
  ...view,
990
- candidates: detected.candidates ?? [],
1154
+ candidates,
991
1155
  counts: detected.counts ?? emptyConflictCounts(),
992
1156
  pairView: detected.pairView ?? null,
993
1157
  edgeView: detected.edgeView ?? null,
994
1158
  skippedReasons: detected.skippedReasons ?? {},
995
1159
  limits: detected.limits ?? null,
1160
+ writeConflicts: {
1161
+ pending: writePending,
1162
+ pendingCount: writePending.length,
1163
+ autoSuperseded,
1164
+ autoSupersededCount: autoSuperseded.length,
1165
+ },
996
1166
  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 },
1167
+ ledger: {
1168
+ file: ledger.file,
1169
+ legacyFile: ledger.legacyFile,
1170
+ legacyRows: ledger.legacyRows,
1171
+ missing: ledger.missing,
1172
+ bad: ledger.bad,
1173
+ rows: ledger.rows.length,
1174
+ },
998
1175
  };
999
1176
  }
1000
1177
  if (action === 'accept') {
1001
1178
  const target = resolveConflictTarget(args, root);
1179
+ const before = readConflictCandidates({ memoryRoot: root, config });
1180
+ const pairRow = before.byPair.get(conflictPairKey(target.aCard, target.bCard));
1181
+ if (pairRow && pairRow.state === 'accepted') {
1182
+ // 写卡自动形成的冲突边已经把该卡对置 accepted:重复 accept 幂等返回,不再写第二条边/审计。
1183
+ return {
1184
+ ok: true,
1185
+ action: 'accept',
1186
+ accepted: true,
1187
+ alreadyAccepted: true,
1188
+ id: pairRow.id,
1189
+ aCard: pairRow.aCard,
1190
+ bCard: pairRow.bCard,
1191
+ edge: null,
1192
+ ledger: { file: before.file, written: 0, pending: before.pendingCount, state: 'accepted' },
1193
+ };
1194
+ }
1002
1195
  const accepted = appendConflictEdge(
1003
1196
  root,
1004
1197
  {
@@ -52,6 +52,29 @@ const AUTO_FLOW_PATTERN = /auto[::-]?land|自动落盘|轮次\s*\d+\s*·|turn\
52
52
  const AUTO_WAIT_PATTERN = /无新指令|无新动作|等待红队|待命|空闲|未回复|无变化/;
53
53
  const AUTO_HUMAN_PATTERN = /更正|纠正|纠错|勘误|冲突|矛盾|隐私|密码|凭据|作废|推翻|改判|造假|错误|删卡|遗忘|forget/i;
54
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
+
55
78
  function collapse(text) {
56
79
  return String(text ?? '').replace(/\s+/g, ' ').trim();
57
80
  }
@@ -140,6 +163,49 @@ function splitEntryGroups(lines) {
140
163
  return groups;
141
164
  }
142
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
+
143
209
  /**
144
210
  * Paragraphs of a journal file. Headings are dropped; a block that holds only
145
211
  * HTML comments (the usual `<!-- affect: N | reason -->` on its own line)
@@ -148,8 +214,11 @@ function splitEntryGroups(lines) {
148
214
  * Returns `{ text, startLine, endLine }` where the line numbers are 1-based
149
215
  * inside `body`, shifted by `lineOffset` when the caller wants file lines.
150
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 文件。
151
220
  */
152
- function paragraphUnits(body, { splitEntries = false, lineOffset = 0 } = {}) {
221
+ function paragraphUnits(body, { splitEntries = false, lineOffset = 0, maxSpan = 0, maxText = 0 } = {}) {
153
222
  const lines = String(body ?? '').split(/\r?\n/);
154
223
  const blocks = [];
155
224
  let block = null;
@@ -168,9 +237,10 @@ function paragraphUnits(body, { splitEntries = false, lineOffset = 0 } = {}) {
168
237
 
169
238
  const units = [];
170
239
  let pending = null;
171
- const attach = (target, text, lastLine) => {
240
+ const attach = (target, text, lastLine, lineList) => {
172
241
  target.text = `${target.text}\n${text}`;
173
242
  target.endLine = lastLine;
243
+ target.lines = [...(target.lines ?? []), ...lineList];
174
244
  };
175
245
  for (const raw of blocks) {
176
246
  const kept = raw.filter((line) => !/^\s{0,3}#{1,6}\s/.test(line.text));
@@ -178,8 +248,8 @@ function paragraphUnits(body, { splitEntries = false, lineOffset = 0 } = {}) {
178
248
  const cleaned = kept.map((line) => line.text).join('\n').trim();
179
249
  if (!collapse(stripComments(cleaned))) {
180
250
  const target = units[units.length - 1] ?? pending;
181
- if (target) attach(target, cleaned, kept[kept.length - 1].number);
182
- 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 };
183
253
  continue;
184
254
  }
185
255
  const groups = splitEntries ? splitEntryGroups(kept) : [kept];
@@ -193,21 +263,29 @@ function paragraphUnits(body, { splitEntries = false, lineOffset = 0 } = {}) {
193
263
  text: `${pending.text}\n${text}`,
194
264
  startLine: pending.startLine,
195
265
  endLine,
266
+ lines: [...(pending.lines ?? []), ...group],
196
267
  });
197
268
  pending = null;
198
269
  } else {
199
- units.push({ text, startLine, endLine });
270
+ units.push({ text, startLine, endLine, lines: group });
200
271
  }
201
272
  }
202
273
  }
203
- if (pending) units.push(pending);
204
- 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) => ({
205
279
  text: unit.text,
206
280
  startLine: unit.startLine + lineOffset,
207
281
  endLine: unit.endLine + lineOffset,
208
282
  }));
209
283
  }
210
284
 
285
+ function spanCapWanted(maxSpan, maxText) {
286
+ return (Number.isFinite(maxSpan) && maxSpan > 0) || (Number.isFinite(maxText) && maxText > 0);
287
+ }
288
+
211
289
  function parseAffectComment(comment) {
212
290
  const inner = comment.replace(/^<!--/, '').replace(/-->$/, '').trim();
213
291
  const rest = inner.replace(/^affect\b/i, '');
@@ -793,6 +871,9 @@ function memoryConsolidateLegacy(args = {}, config = {}) {
793
871
  // but cut points are only safe when the caller knows segment labels do not
794
872
  // overlap (F6 in the A-group manifest: A-14 L59-73 and A-15 L71-72 do overlap).
795
873
  const entrySplit = args.entrySplit === true;
874
+ // 2.3.0 lane pipeline(W1-3):提案在进入积压前就按 ≤maxSpan 行 / ≤maxText 字切好,
875
+ // 这样 autoResolve 面对的新提案本身可判;journal 文件不动,只切提案单元。
876
+ const unitLimits = autoUnitLimits(config);
796
877
  const newEntries = [];
797
878
  const allTopicCards = scanCards(root).filter((card) => card.rel.startsWith('topics/'));
798
879
  // Locked cards are core memory: they are never merge targets (and journal
@@ -815,14 +896,14 @@ function memoryConsolidateLegacy(args = {}, config = {}) {
815
896
  // paragraphUnits numbers lines inside the body; shift them to file lines.
816
897
  const lineOffset = text.slice(0, parsed.bodyStart).split(/\r?\n/).length - 1;
817
898
  if (sinceDay && !fileDay) {
818
- for (const unit of paragraphUnits(parsed.body, { lineOffset })) {
899
+ for (const unit of paragraphUnits(parsed.body, { lineOffset, ...unitLimits })) {
819
900
  undated.push({ source: rel, excerpt: collapse(stripComments(unit.text)).slice(0, 120) });
820
901
  }
821
902
  continue;
822
903
  }
823
904
  if (sinceDay && fileDay <= sinceDay) continue;
824
905
 
825
- for (const unit of paragraphUnits(parsed.body, { splitEntries: entrySplit, lineOffset })) {
906
+ for (const unit of paragraphUnits(parsed.body, { splitEntries: entrySplit, lineOffset, ...unitLimits })) {
826
907
  entries += 1;
827
908
  const paragraphText = collapse(stripComments(unit.text));
828
909
  const affect = parseAffect(unit.text);
@@ -994,6 +1075,12 @@ export function autoResolveProposals(options = {}) {
994
1075
  const maxNewCards = clampInt(options.maxAcceptNew, AUTO_ACCEPT_NEW_PER_DAY);
995
1076
  const allowReject = rules.reject !== false;
996
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
+ };
997
1084
 
998
1085
  const state = readState(root);
999
1086
  const entries = (Array.isArray(state.seenProposals) ? state.seenProposals : [])
@@ -1078,10 +1165,10 @@ export function autoResolveProposals(options = {}) {
1078
1165
  verdict = { action: 'review', rule: 'needs_human', reason: 'needs_human: 事实/更正/隐私类关键词命中' };
1079
1166
  } else if (entry.target !== null && entry.target !== undefined && entry.target !== '') {
1080
1167
  verdict = { action: 'review', rule: 'merge_needed', reason: 'merge_needed: 已有目标卡,等人工合并' };
1081
- } else if (span > AUTO_SAFE_SPAN_MAX) {
1082
- verdict = { action: 'review', rule: 'span_too_large', reason: `span=${span} 超出自动建卡上限 ${AUTO_SAFE_SPAN_MAX}` };
1083
- } else if (text.length < AUTO_SAFE_TEXT_MIN || text.length > AUTO_SAFE_TEXT_MAX) {
1084
- verdict = { action: 'review', rule: 'text_size', reason: `text_len=${text.length} 超出自动建卡区间 [${AUTO_SAFE_TEXT_MIN},${AUTO_SAFE_TEXT_MAX}]` };
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}]` };
1085
1172
  } else if (!Number.isInteger(entry.salience) || entry.salience < 3) {
1086
1173
  verdict = { action: 'review', rule: 'low_salience', reason: `salience=${entry.salience ?? 'null'} < 3` };
1087
1174
  } else if (claimNorm === '' || !normalizeMatch(text).includes(claimNorm)) {