@jjh32456/longlive 2.1.0 → 2.2.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.
@@ -22,10 +22,36 @@ 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
+
29
55
  function collapse(text) {
30
56
  return String(text ?? '').replace(/\s+/g, ' ').trim();
31
57
  }
@@ -477,6 +503,117 @@ function lastDayOf(value) {
477
503
  return /^\d{4}-\d{2}-\d{2}/.test(value) ? value.slice(0, 10) : null;
478
504
  }
479
505
 
506
+ function sha256Text(text) {
507
+ return crypto.createHash('sha256').update(String(text ?? ''), 'utf8').digest('hex');
508
+ }
509
+
510
+ /** Stable content identity: the same paragraph always maps to the same 16 hex chars. */
511
+ function contentKeyOf(normalizedText) {
512
+ return sha256Text(normalizedText).slice(0, 16);
513
+ }
514
+
515
+ /** `<source journal>@<first line>` — a paragraph can only start once in an append-only journal. */
516
+ function sourceAnchorOf(entry) {
517
+ const rel = typeof entry?.source === 'string' ? entry.source.trim() : '';
518
+ const start = Number(entry?.lineStart);
519
+ return rel && Number.isInteger(start) && start > 0 ? `${rel}@${start}` : '';
520
+ }
521
+
522
+ function normalizeMatch(text) {
523
+ return collapse(stripComments(text)).toLowerCase();
524
+ }
525
+
526
+ function clampInt(value, fallback) {
527
+ const number = Number(value);
528
+ if (!Number.isFinite(number) || number < 1) return fallback;
529
+ return Math.min(Math.floor(number), 1000);
530
+ }
531
+
532
+ /**
533
+ * Re-read the journal line range a proposal points at. The journal is
534
+ * append-only, so the range stays valid; a missing file, a short file or an
535
+ * out-of-range start means the source drifted and the proposal must not be
536
+ * auto-accepted. One read per file per run (427 proposals over ~10 files).
537
+ */
538
+ function readSourceRange(root, entry, lineCache) {
539
+ const rel = typeof entry?.source === 'string' ? entry.source.trim() : '';
540
+ if (!rel) return null;
541
+ const start = Number(entry?.lineStart);
542
+ if (!Number.isInteger(start) || start < 1) return null;
543
+ const stopRaw = Number(entry?.lineEnd);
544
+ const stop = Number.isInteger(stopRaw) && stopRaw >= start ? stopRaw : start;
545
+ let lines = lineCache.get(rel);
546
+ if (lines === undefined) {
547
+ lines = null;
548
+ try {
549
+ const abs = resolveInside(root, rel);
550
+ if (fs.existsSync(abs)) lines = fs.readFileSync(abs, 'utf8').split(/\r?\n/);
551
+ } catch {
552
+ lines = null;
553
+ }
554
+ lineCache.set(rel, lines);
555
+ }
556
+ if (!lines || start > lines.length) return null;
557
+ const text = collapse(stripComments(lines.slice(start - 1, Math.min(stop, lines.length)).join('\n')));
558
+ return { rel, start, text, truncated: stop > lines.length };
559
+ }
560
+
561
+ /**
562
+ * Index used for "exact duplicate" detection. Only exact identity counts:
563
+ * contentKeys content_key written by an earlier auto-accept card
564
+ * sourceKeys source journal + first line of an earlier consolidated card
565
+ * claims normalized title / first body line of every topic card
566
+ * No token overlap, no similarity.
567
+ */
568
+ function buildAutoCardIndex(root) {
569
+ const index = {
570
+ contentKeys: new Map(),
571
+ sourceKeys: new Map(),
572
+ claims: new Map(),
573
+ };
574
+ let cards = [];
575
+ try {
576
+ cards = scanCards(root);
577
+ } catch {
578
+ cards = [];
579
+ }
580
+ for (const card of cards) {
581
+ if (!card || typeof card.rel !== 'string' || !card.rel.startsWith('topics/')) continue;
582
+ const extras = card.extras && typeof card.extras === 'object' ? card.extras : {};
583
+ const contentKey = typeof extras.content_key === 'string' ? extras.content_key.trim() : '';
584
+ if (contentKey) index.contentKeys.set(contentKey, card.rel);
585
+ const title = collapse(card.title ?? card.fields?.title ?? '');
586
+ if (title) index.claims.set(title.toLowerCase(), card.rel);
587
+ const firstLine = String(card.body ?? '')
588
+ .split(/\r?\n/)
589
+ .map((line) => collapse(line))
590
+ .find((line) => line !== '' && !line.startsWith('#'));
591
+ if (firstLine) index.claims.set(firstLine.toLowerCase(), card.rel);
592
+ const journal = typeof extras.source_journal === 'string' ? extras.source_journal.trim() : '';
593
+ const lines = /^(\d+)(?:-(\d+))?$/.exec(String(extras.source_lines ?? '').trim());
594
+ if (journal && lines) index.sourceKeys.set(`${journal}@${lines[1]}`, card.rel);
595
+ }
596
+ return index;
597
+ }
598
+
599
+ /**
600
+ * THE single card-writing path for an accepted proposal. Manual accept and the
601
+ * 2.2.0 automatic accept both call this (same writeCard, same frontmatter).
602
+ */
603
+ function writeAcceptedCard(root, entry, { now, rel, title, body, extras }) {
604
+ return writeCard(root, {
605
+ rel,
606
+ title,
607
+ body,
608
+ fields: {
609
+ date: entry.day ?? dayString(now),
610
+ tags: ['consolidation'],
611
+ salience: Number.isInteger(entry.salience) ? entry.salience : 3,
612
+ },
613
+ extras,
614
+ }, { now });
615
+ }
616
+
480
617
  function proposalBacklog(entries) {
481
618
  const list = Array.isArray(entries) ? entries.filter((entry) => entry && typeof entry.id === 'string') : [];
482
619
  const counts = { proposed: 0, accepted: 0, rejected: 0, superseded: 0 };
@@ -502,14 +639,27 @@ function proposalBacklog(entries) {
502
639
  };
503
640
  }
504
641
 
642
+ /**
643
+ * The consolidated pointer walks days in order and stops at the FIRST day that
644
+ * still has an unresolved proposal.
645
+ *
646
+ * 2.1.0 skipped such a day and kept advancing (`if ... continue`), which let the
647
+ * pointer jump over a pending middle day and made `lastConsolidated` mean
648
+ * "newest fully-resolved day" instead of "everything up to here is dealt with".
649
+ * 2.2.0 must not skip: pending entries of an older day stay visible until they
650
+ * are resolved (BACKLOG-ANALYSIS.md §3.5).
651
+ */
505
652
  function advanceLastConsolidated(state, entries) {
506
653
  const current = lastDayOf(state.lastConsolidated);
507
- const days = [...new Set(entries.map((entry) => entry.day).filter((day) => typeof day === 'string'))].sort();
654
+ const list = Array.isArray(entries) ? entries.filter((entry) => entry && typeof entry.day === 'string') : [];
655
+ const days = [...new Set(list.map((entry) => entry.day))].sort();
508
656
  let last = current;
509
657
  for (const day of days) {
510
658
  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;
659
+ const dayEntries = list.filter((entry) => entry.day === day);
660
+ if (dayEntries.length === 0) continue;
661
+ if (!dayEntries.every((entry) => RESOLVED_STATUS.has(entry.status))) break;
662
+ last = day;
513
663
  }
514
664
  return last;
515
665
  }
@@ -554,21 +704,18 @@ export function resolveConsolidationProposal(args = {}, config = {}) {
554
704
  `- source: ${entry.source ?? 'journal'}${entry.lineStart ? `:${entry.lineStart}-${entry.lineEnd}` : ''}`,
555
705
  `- accepted_at: ${now.toISOString()}`,
556
706
  ].join('\n');
557
- card = writeCard(root, {
707
+ // 2.2.0 lane A: one card-writing path for manual accept AND auto-accept.
708
+ card = writeAcceptedCard(root, entry, {
709
+ now,
558
710
  rel,
559
711
  title,
560
712
  body,
561
- fields: {
562
- date: entry.day ?? dayString(now),
563
- tags: ['consolidation'],
564
- salience: Number.isInteger(entry.salience) ? entry.salience : 3,
565
- },
566
713
  extras: {
567
714
  consolidation_proposal: proposalIdValue,
568
715
  source_journal: entry.source ?? '',
569
716
  source_lines: entry.lineStart ? `${entry.lineStart}-${entry.lineEnd}` : '',
570
717
  },
571
- }, { now });
718
+ });
572
719
  entries[index] = { ...entry, status: 'accepted', resolvedAt: now.toISOString(), card: rel };
573
720
  } else {
574
721
  const reason = collapse(args.reason ?? '').slice(0, 300);
@@ -657,7 +804,6 @@ function memoryConsolidateLegacy(args = {}, config = {}) {
657
804
  const proposals = [];
658
805
  const undated = [];
659
806
  const badAffect = [];
660
- const scannedDays = new Set();
661
807
  let entries = 0;
662
808
  let duplicates = 0;
663
809
 
@@ -675,7 +821,6 @@ function memoryConsolidateLegacy(args = {}, config = {}) {
675
821
  continue;
676
822
  }
677
823
  if (sinceDay && fileDay <= sinceDay) continue;
678
- if (fileDay) scannedDays.add(fileDay);
679
824
 
680
825
  for (const unit of paragraphUnits(parsed.body, { splitEntries: entrySplit, lineOffset })) {
681
826
  entries += 1;
@@ -734,23 +879,16 @@ function memoryConsolidateLegacy(args = {}, config = {}) {
734
879
  }
735
880
  }
736
881
 
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;
882
+ // 2.2.0 lane A: the incremental pointer now walks every fully resolved day in
883
+ // order and stops at the first day that still has a pending proposal
884
+ // (advanceLastConsolidated never skips a middle day). 2.1.0 only considered
885
+ // the newest scanned day, so a backlog on an older day could never close.
741
886
  const currentLastDay = lastDayOf(state.lastConsolidated);
742
887
  const allEntries = [...seenProposals, ...newEntries];
743
888
  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
- }
889
+ const advanced = advanceLastConsolidated(state, allEntries);
890
+ const lastConsolidated = advanced ?? state.lastConsolidated ?? null;
891
+ const stateUpdated = advanced !== currentLastDay;
754
892
 
755
893
  const stateChanged = newEntries.length > 0 || stateUpdated;
756
894
  let stateWrite = null;
@@ -811,8 +949,285 @@ function memoryConsolidateLegacy(args = {}, config = {}) {
811
949
  };
812
950
  }
813
951
 
952
+ /**
953
+ * 2.2.0 lane A: auto-resolve the consolidation backlog (maintenance-side).
954
+ *
955
+ * Called once per day by the maintenance job. It reads ONLY memory-state.json
956
+ * plus the journal line ranges the proposals point at, and it writes ONLY:
957
+ * - new `topics/consolidated/<contentKey>.md` cards (single writeCard path,
958
+ * shared with the manual accept path),
959
+ * - status transitions in `seenProposals`,
960
+ * - one audit line per mutation,
961
+ * - at most ONE state write per run.
962
+ *
963
+ * Only exact identity may auto-resolve a proposal (no semantic similarity, no
964
+ * coverage ratio, no probability):
965
+ * - same proposal id already resolved -> reject `auto: duplicate`
966
+ * - same paragraph anchor already resolved -> reject `duplicate_reproposal`
967
+ * - same content key already on a card -> reject `auto: duplicate`
968
+ * - claim line equals an existing card title/first line -> reject `auto: duplicate`
969
+ * Structural anomalies (T0, BACKLOG-ANALYSIS.md appendix A/F) auto-reject:
970
+ * - oversized unit (>= 100 lines), too short (< 18 chars) -> reject
971
+ * - auto/turn machine-flow lines, waiting lines -> reject
972
+ * Clean no-target paragraphs auto-accept through the T1 gates:
973
+ * target=null, span<=10, 40..800 chars, salience>=3, source re-read matches
974
+ * the excerpt, privacyScan clean, per-run accept cap not reached.
975
+ * Everything else stays `proposed` for a human (merge/更正/隐私/源漂移).
976
+ *
977
+ * `rules` = {accept:boolean, reject:boolean} switches the two decision classes
978
+ * (duplicate detection is always on: an exact duplicate must never be accepted).
979
+ *
980
+ * Options: {root, now, maxAccept, maxAcceptNew, rules}
981
+ * maxAccept total mutations (accept+reject) for this run, default 100
982
+ * maxAcceptNew newly written cards for this run, default 10
983
+ * Returns the run summary; `stateWritten` is false when nothing changed, so a
984
+ * second run on the same day is a true no-op (idempotent).
985
+ */
986
+ export function autoResolveProposals(options = {}) {
987
+ const root = options.root;
988
+ if (typeof root !== 'string' || root === '') {
989
+ throw memoryError('E_BAD_ARGUMENT', 'autoResolveProposals 需要 memoryRoot');
990
+ }
991
+ const now = options.now instanceof Date && !Number.isNaN(options.now.getTime()) ? options.now : new Date();
992
+ const rules = options.rules && typeof options.rules === 'object' ? options.rules : {};
993
+ const maxMutations = clampInt(options.maxAccept, AUTO_MUTATIONS_PER_DAY);
994
+ const maxNewCards = clampInt(options.maxAcceptNew, AUTO_ACCEPT_NEW_PER_DAY);
995
+ const allowReject = rules.reject !== false;
996
+ const allowAccept = rules.accept !== false;
997
+
998
+ const state = readState(root);
999
+ const entries = (Array.isArray(state.seenProposals) ? state.seenProposals : [])
1000
+ .filter((entry) => entry && typeof entry.id === 'string');
1001
+ const pending = entries.filter((entry) => !RESOLVED_STATUS.has(entry.status));
1002
+ const ordered = [...pending].sort((a, b) => {
1003
+ const dayA = typeof a.day === 'string' ? a.day : '';
1004
+ const dayB = typeof b.day === 'string' ? b.day : '';
1005
+ if (dayA !== dayB) return dayA.localeCompare(dayB);
1006
+ return (Number(a.lineStart) || 0) - (Number(b.lineStart) || 0);
1007
+ });
1008
+
1009
+ const lineCache = new Map();
1010
+ const cardIndex = buildAutoCardIndex(root);
1011
+ const indexOf = new Map(entries.map((entry, index) => [entry, index]));
1012
+ const resolvedIds = new Set();
1013
+ const historyByAnchor = new Map();
1014
+ for (const entry of entries) {
1015
+ if (RESOLVED_STATUS.has(entry.status)) resolvedIds.add(entry.id);
1016
+ const anchor = sourceAnchorOf(entry);
1017
+ if (!anchor) continue;
1018
+ if (!historyByAnchor.has(anchor)) historyByAnchor.set(anchor, []);
1019
+ historyByAnchor.get(anchor).push(entry);
1020
+ }
1021
+
1022
+ const claimedContentKeys = new Set();
1023
+ const claimedAnchors = new Set();
1024
+ const reviewReasons = {};
1025
+ const cards = [];
1026
+ const mutations = [];
1027
+ let accepted = 0;
1028
+ let rejected = 0;
1029
+ let reviewed = 0;
1030
+
1031
+ for (const entry of ordered) {
1032
+ if (mutations.length >= maxMutations) break;
1033
+ const anchor = sourceAnchorOf(entry);
1034
+ const src = readSourceRange(root, entry, lineCache);
1035
+ const siblings = anchor ? (historyByAnchor.get(anchor) ?? []).filter((other) => other !== entry) : [];
1036
+ const resolvedSibling = siblings.find((other) => RESOLVED_STATUS.has(other.status)) ?? null;
1037
+ const peer = siblings.find((other) => !RESOLVED_STATUS.has(other.status)) ?? null;
1038
+
1039
+ let verdict;
1040
+ if (resolvedIds.has(entry.id) || (anchor !== '' && claimedAnchors.has(anchor))) {
1041
+ const skip = resolvedIds.has(entry.id) ? 'proposal-id-already-resolved' : 'same-run-anchor';
1042
+ verdict = { action: 'reject', rule: 'duplicate', reason: `auto: duplicate skip=${skip}` };
1043
+ } else if (!src) {
1044
+ verdict = { action: 'review', rule: 'source_unavailable', reason: 'source_unavailable' };
1045
+ } else {
1046
+ const text = src.text;
1047
+ const spanRaw = Number(entry.lineEnd);
1048
+ const span = Number.isInteger(spanRaw) && spanRaw >= src.start ? spanRaw - src.start + 1 : 1;
1049
+ const contentKey = contentKeyOf(text);
1050
+ const claimNorm = normalizeMatch(entry.excerpt ?? '');
1051
+ const cardRel = `topics/consolidated/${contentKey}.md`;
1052
+ const cardByContent = cardIndex.contentKeys.get(contentKey) ?? null;
1053
+ const cardBySource = anchor ? (cardIndex.sourceKeys.get(anchor) ?? null) : null;
1054
+ const claimCard = claimNorm ? (cardIndex.claims.get(claimNorm) ?? null) : null;
1055
+ if (cardByContent || cardBySource || claimCard || claimedContentKeys.has(contentKey)) {
1056
+ const skip = cardByContent ? `card:${cardByContent}`
1057
+ : cardBySource ? `card:${cardBySource}`
1058
+ : claimCard ? `claim:${claimCard}` : 'same-run-content';
1059
+ verdict = { action: 'reject', rule: 'duplicate', reason: `auto: duplicate skip=${skip}`, contentKey, anchor };
1060
+ } else if (resolvedSibling || peer) {
1061
+ const holder = resolvedSibling ?? peer;
1062
+ verdict = {
1063
+ action: 'reject',
1064
+ rule: 'duplicate_reproposal',
1065
+ reason: `duplicate_reproposal: same paragraph already ${resolvedSibling ? 'resolved' : 'pending'} as ${holder.id}`,
1066
+ contentKey,
1067
+ anchor,
1068
+ };
1069
+ } else if (allowReject && span >= AUTO_OVERSIZED_SPAN) {
1070
+ verdict = { action: 'reject', rule: 'oversized_unit', reason: `oversized_unit(span=${span}): journal paragraph too large; re-propose after entrySplit/fix`, contentKey, anchor };
1071
+ } else if (allowReject && text.length < AUTO_MIN_TEXT) {
1072
+ verdict = { action: 'reject', rule: 'unit_too_short', reason: `unit_too_short(norm=${text.length})`, contentKey, anchor };
1073
+ } else if (allowReject && AUTO_FLOW_PATTERN.test(text)) {
1074
+ 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 };
1075
+ } else if (allowReject && AUTO_WAIT_PATTERN.test(text)) {
1076
+ verdict = { action: 'reject', rule: 'no_new_instruction', reason: 'no_new_instruction: waiting line, no durable claim', contentKey, anchor };
1077
+ } else if (AUTO_HUMAN_PATTERN.test(text)) {
1078
+ verdict = { action: 'review', rule: 'needs_human', reason: 'needs_human: 事实/更正/隐私类关键词命中' };
1079
+ } else if (entry.target !== null && entry.target !== undefined && entry.target !== '') {
1080
+ 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}]` };
1085
+ } else if (!Number.isInteger(entry.salience) || entry.salience < 3) {
1086
+ verdict = { action: 'review', rule: 'low_salience', reason: `salience=${entry.salience ?? 'null'} < 3` };
1087
+ } else if (claimNorm === '' || !normalizeMatch(text).includes(claimNorm)) {
1088
+ // The stored excerpt is the picked claim (pickClaim), not necessarily a
1089
+ // prefix of the paragraph, so verify that the quoted claim still occurs
1090
+ // inside the re-read source range — an exact substring check, never a
1091
+ // similarity score.
1092
+ verdict = { action: 'review', rule: 'source_mismatch', reason: 'source_mismatch: 重读段落与提案摘录不一致(源可能已变更)' };
1093
+ } else if (fs.existsSync(resolveInside(root, cardRel))) {
1094
+ verdict = { action: 'reject', rule: 'duplicate', reason: `auto: duplicate skip=card-file:${cardRel}`, contentKey, anchor };
1095
+ } else if (privacyScan(text).verdict !== 'none') {
1096
+ verdict = { action: 'review', rule: 'privacy', reason: 'privacy: privacyScan 命中 local_only,不自动入卡' };
1097
+ } else if (!allowAccept || accepted >= maxNewCards) {
1098
+ verdict = { action: 'review', rule: 'accept_cap', reason: `accept_cap: 每日自动建卡上限 ${maxNewCards} 已到` };
1099
+ } else {
1100
+ verdict = { action: 'accept', rule: 'accept', contentKey, anchor, src, cardRel };
1101
+ }
1102
+ }
1103
+
1104
+ if (verdict.action === 'review') {
1105
+ reviewed += 1;
1106
+ reviewReasons[verdict.rule] = (reviewReasons[verdict.rule] ?? 0) + 1;
1107
+ continue;
1108
+ }
1109
+
1110
+ const entryIndex = indexOf.get(entry);
1111
+ if (verdict.action === 'accept') {
1112
+ const text = verdict.src.text;
1113
+ const stop = Math.max(verdict.src.start, Number(entry.lineEnd) || verdict.src.start);
1114
+ const sourceLines = `${verdict.src.start}-${stop}`;
1115
+ const sourceSha256 = sha256Text(text);
1116
+ const title = collapse(text).slice(0, 80);
1117
+ const body = [
1118
+ `# ${title}`,
1119
+ '',
1120
+ text,
1121
+ '',
1122
+ `- content_key: ${verdict.contentKey}`,
1123
+ `- source: ${verdict.src.rel}:${sourceLines}`,
1124
+ `- source_sha256: ${sourceSha256}`,
1125
+ `- proposal: ${entry.id}`,
1126
+ `- accepted_at: ${now.toISOString()}`,
1127
+ '- auto: accept (2.2.0 lane A: 无目标 + 短段 + 干净 + 源文校验)',
1128
+ ].join('\n');
1129
+ const card = writeAcceptedCard(root, entry, {
1130
+ now,
1131
+ rel: verdict.cardRel,
1132
+ title,
1133
+ body,
1134
+ extras: {
1135
+ content_key: verdict.contentKey,
1136
+ source_journal: verdict.src.rel,
1137
+ source_lines: sourceLines,
1138
+ source_sha256: sourceSha256,
1139
+ proposal_legacy_id: entry.id,
1140
+ auto: 'accept',
1141
+ },
1142
+ });
1143
+ const claimedAnchor = verdict.anchor || sourceAnchorOf(entry);
1144
+ entries[entryIndex] = {
1145
+ ...entry,
1146
+ status: 'accepted',
1147
+ resolvedAt: now.toISOString(),
1148
+ card: card.rel,
1149
+ auto: true,
1150
+ autoRule: 'accept',
1151
+ contentKey: verdict.contentKey,
1152
+ sourceSha256,
1153
+ };
1154
+ accepted += 1;
1155
+ claimedContentKeys.add(verdict.contentKey);
1156
+ if (claimedAnchor) claimedAnchors.add(claimedAnchor);
1157
+ mutations.push(entry.id);
1158
+ cards.push(card.rel);
1159
+ appendAudit(root, {
1160
+ action: 'memory_consolidate_accept',
1161
+ object: entry.id,
1162
+ result: `card=${card.rel} auto: ${verdict.rule}`,
1163
+ now,
1164
+ });
1165
+ } else {
1166
+ const reason = verdict.reason.slice(0, 300);
1167
+ entries[entryIndex] = {
1168
+ ...entry,
1169
+ status: 'rejected',
1170
+ resolvedAt: now.toISOString(),
1171
+ reason,
1172
+ auto: true,
1173
+ autoRule: verdict.rule,
1174
+ ...(verdict.contentKey ? { contentKey: verdict.contentKey } : {}),
1175
+ };
1176
+ rejected += 1;
1177
+ if (verdict.contentKey) claimedContentKeys.add(verdict.contentKey);
1178
+ const claimedAnchor = verdict.anchor || sourceAnchorOf(entry);
1179
+ if (claimedAnchor) claimedAnchors.add(claimedAnchor);
1180
+ mutations.push(entry.id);
1181
+ appendAudit(root, {
1182
+ action: 'memory_consolidate_reject',
1183
+ object: entry.id,
1184
+ result: `reason=${reason.slice(0, 200)} auto: ${verdict.rule}`,
1185
+ now,
1186
+ });
1187
+ }
1188
+ }
1189
+
1190
+ const previousLastConsolidated = lastDayOf(state.lastConsolidated);
1191
+ const lastConsolidated = advanceLastConsolidated(state, entries);
1192
+ const pointerMoved = lastConsolidated !== previousLastConsolidated;
1193
+ let write = null;
1194
+ if (mutations.length > 0 || pointerMoved) {
1195
+ write = updateState(root, {
1196
+ seenProposals: entries,
1197
+ ...(pointerMoved ? { lastConsolidated } : {}),
1198
+ }, { now });
1199
+ }
1200
+ const backlog = proposalBacklog(entries);
1201
+ return {
1202
+ ok: true,
1203
+ status: mutations.length > 0 ? 'auto-resolve' : 'noop',
1204
+ root,
1205
+ accepted,
1206
+ rejected,
1207
+ reviewed,
1208
+ reviewReasons,
1209
+ mutations: mutations.length,
1210
+ cards,
1211
+ audits: mutations.length,
1212
+ pending: backlog.pending,
1213
+ previousLastConsolidated,
1214
+ lastConsolidated,
1215
+ pointerMoved,
1216
+ capReached: mutations.length >= maxMutations,
1217
+ maxAccept: maxMutations,
1218
+ maxAcceptNew: maxNewCards,
1219
+ stateWritten: Boolean(write),
1220
+ write: write ? { sha256: write.write?.sha256 ?? null, bytes: write.write?.bytes ?? null } : null,
1221
+ backlog,
1222
+ message:
1223
+ `自动处理 ${mutations.length} 条(accept ${accepted} / reject ${rejected}),留人工 ${reviewed} 条;` +
1224
+ `pending=${backlog.pending};lastConsolidated=${lastConsolidated ?? 'null'}`,
1225
+ };
1226
+ }
1227
+
814
1228
  export {
815
1229
  contentTokens, buildCardIndex, cosineScore, coverageScore, pickQuote, pickClaim, paragraphUnits,
1230
+ proposalBacklog,
816
1231
  };
817
1232
 
818
1233
  /**
@@ -29,6 +29,11 @@ export const INDEX_FILE = 'INDEX.md';
29
29
  export const PROCEDURES_HEADING = `### 程序性(${PROCEDURES_DIR}/)`;
30
30
 
31
31
  const SCAN_DIRS = ['topics', 'journal'];
32
+ /**
33
+ * 召回面扫描目录:卡片面 + procedures(程序卡)。索引面(memoryIndex)仍用
34
+ * SCAN_DIRS,procedures 由 scanProcedures 单独计入「程序性」表,避免重复计数。
35
+ */
36
+ export const RECALL_SCAN_DIRS = Object.freeze(['topics', 'journal', PROCEDURES_DIR]);
32
37
  export const RAW_DIRS = ['raw', 'topics/raw'];
33
38
  export const RAW_INDEX_POLICY = 'excluded-by-default';
34
39
  export const RAW_OPT_IN_FIELD = 'index';
@@ -141,6 +146,24 @@ function resolveReadCardArgs(first, second) {
141
146
  return { root, abs };
142
147
  }
143
148
 
149
+ /** 程序卡 trigger 是动作词数组(`[发布, 部署]`),也兼容裸字符串(`发布`)。 */
150
+ function procedureTriggerTags(value) {
151
+ if (Array.isArray(value)) return value.map((item) => collapse(item)).filter(Boolean);
152
+ let text = collapse(value);
153
+ if (!text) return [];
154
+ // parseFrontmatter 不解析内联数组,extras.trigger 可能是整段 `[发布, publish, npm]` 字符串。
155
+ text = text.replace(/^\[/, '').replace(/\]$/, '');
156
+ return text.split(',').map((item) => item.trim().replace(/^["']|["']$/g, '')).filter(Boolean);
157
+ }
158
+
159
+ function mergeProcedureTags(existing, trigger) {
160
+ const merged = Array.isArray(existing) ? existing.map((item) => collapse(item)).filter(Boolean) : [];
161
+ for (const tag of procedureTriggerTags(trigger)) {
162
+ if (!merged.some((item) => item.toLowerCase() === tag.toLowerCase())) merged.push(tag);
163
+ }
164
+ return merged;
165
+ }
166
+
144
167
  /**
145
168
  * 读一张卡:frontmatter + 正文。正文按 C 召回面口径带 body(≤1,200 码点,
146
169
  * 超长 bodyTruncated:true,另给 bodyChars);local_only / 隐私卡正文与摘要一律
@@ -152,7 +175,11 @@ export function readCard(first, second) {
152
175
  const text = fs.readFileSync(abs, 'utf8');
153
176
  const parsed = parseFrontmatter(text);
154
177
  const rel = relFromAbs(abs, root);
155
- const title = collapse(parsed.fields.title || firstHeading(parsed.body) || path.basename(abs, '.md')) || '(无题)';
178
+ // 程序卡(procedures/)frontmatter 用 name / trigger,没有 title / tags:
179
+ // 把 name 映射成 title、trigger 映射成 tags,否则召回打分吃不到标题 +5 / tags +3。
180
+ const isProcedure = rel.replace(/\\/g, '/').startsWith(`${PROCEDURES_DIR}/`);
181
+ const title = collapse(parsed.fields.title || parsed.extras?.name || firstHeading(parsed.body) || path.basename(abs, '.md')) || '(无题)';
182
+ const tags = isProcedure ? mergeProcedureTags(parsed.fields.tags, parsed.extras?.trigger) : parsed.fields.tags;
156
183
  const rawBody = String(parsed.body ?? '').trim();
157
184
  const localOnly = truthyFlag(parsed.fields.local_only) || truthyFlag(parsed.extras?.local_only);
158
185
  const bodyChars = Array.from(rawBody).length;
@@ -170,8 +197,9 @@ export function readCard(first, second) {
170
197
  title,
171
198
  summary: localOnly ? CARD_BODY_HIDDEN : firstSummaryLine(parsed.body),
172
199
  legacy: parsed.legacy,
173
- fields: parsed.fields,
200
+ fields: isProcedure ? { ...parsed.fields, tags } : parsed.fields,
174
201
  extras: parsed.extras ?? {},
202
+ ...(isProcedure ? { procedure: true } : {}),
175
203
  body,
176
204
  bodyChars: localOnly ? 0 : Array.from(body).length,
177
205
  bodyTruncated,
@@ -188,9 +216,10 @@ function shouldSkipScanRel(rel) {
188
216
  }
189
217
 
190
218
  /** All cards under `topics/` (incl. `topics/auto/`) and `journal/`, archive excluded. */
191
- export function scanCards(root) {
219
+ export function scanCards(root, options = {}) {
220
+ const dirs = Array.isArray(options?.dirs) && options.dirs.length > 0 ? options.dirs : SCAN_DIRS;
192
221
  const cards = [];
193
- for (const dir of SCAN_DIRS) {
222
+ for (const dir of dirs) {
194
223
  for (const abs of listMarkdownFiles(root, dir)) {
195
224
  const rel = relativePath(root, abs);
196
225
  if (shouldSkipScanRel(rel)) continue;