@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.
@@ -26,8 +26,8 @@ import crypto from 'node:crypto';
26
26
 
27
27
  import { dayString, isoStamp } from './frontmatter.js';
28
28
  import { memoryRootFromConfig, resolveInside, relativePath } from './paths.js';
29
- import { ensureDir, writeFileAtomic } from './state.js';
30
- import { memoryConsolidate } from './consolidate.js';
29
+ import { ensureDir, readState, writeFileAtomic } from './state.js';
30
+ import { memoryConsolidate, autoResolveProposals, proposalBacklog } from './consolidate.js';
31
31
  import { memoryForget } from './forget.js';
32
32
  import { proposeForget, FORGET_SUGGESTIONS_REL } from './forget-v2.js';
33
33
  import { runConclusionDistillJob } from './conclusion-distill.js';
@@ -38,6 +38,9 @@ import { probePending as probeMigrationPending } from './migrate-200.js';
38
38
 
39
39
  export const SCHEDULE_VERSION = 1;
40
40
  export const SCHEDULE_REL = path.join('.longlive', 'bridge', 'schedule.json');
41
+ // 2.2.0 lane A: small backlog sidecar so recall/status can read the proposal
42
+ // backlog without parsing the (300KB+) memory-state.json on every step.
43
+ export const BACKLOG_REL = path.join('.longlive', 'bridge', 'backlog.json');
41
44
  export const LOCK_REL = path.join('.longlive', 'bridge', 'schedule.lock');
42
45
  export const PENDING_REPORT_PREFIX = 'forget-pending-';
43
46
  export const RUN_HISTORY_LIMIT = 30;
@@ -76,8 +79,45 @@ function warnTo(logger, message) {
76
79
  }
77
80
  }
78
81
 
79
- function toClock(now) {
80
- if (typeof now === 'function') {
82
+ /**
83
+ * 2.2.0 lane A: auto-resolve knobs may arrive through an existing raw
84
+ * passthrough (`autoResolve: {enabled, maxAccept, maxAcceptNew}`); no new
85
+ * schema leaf is added, and when nothing is configured the consolidate.js
86
+ * defaults (100 mutations / 10 new cards per run) apply.
87
+ */
88
+ function autoResolveOptions(config) {
89
+ const rows = [config?.autoResolve, config?.autoMaintenance?.autoResolve];
90
+ for (const row of rows) {
91
+ if (row && typeof row === 'object' && !Array.isArray(row)) return row;
92
+ }
93
+ return {};
94
+ }
95
+
96
+ /**
97
+ * 2.2.0 lane A: the small backlog sidecar. Readers (recall/status) can stat this
98
+ * file instead of parsing the 300KB+ memory-state.json on every step.
99
+ * Atomic tmp+rename through writeFileAtomic; no backup needed (rebuildable).
100
+ */
101
+ function writeBacklogSidecar(root, { now = new Date(), day = null } = {}) {
102
+ const file = resolveInside(root, BACKLOG_REL);
103
+ const state = readState(root);
104
+ const backlog = proposalBacklog(Array.isArray(state.seenProposals) ? state.seenProposals : []);
105
+ const payload = {
106
+ day: day ?? dayString(now),
107
+ total: backlog.total,
108
+ pending: backlog.pending,
109
+ resolved: backlog.resolved,
110
+ accepted: backlog.accepted,
111
+ rejected: backlog.rejected,
112
+ lastConsolidated: state.lastConsolidated ?? null,
113
+ at: isoStamp(now),
114
+ };
115
+ ensureDir(root, path.dirname(file));
116
+ const write = writeFileAtomic(root, file, `${JSON.stringify(payload, null, 2)}\n`, { backup: false, now });
117
+ return { rel: relativePath(root, file), ...payload, sha256: write.sha256, bytes: write.bytes };
118
+ }
119
+
120
+ function toClock(now) { if (typeof now === 'function') {
81
121
  return () => {
82
122
  const value = now();
83
123
  const date = value instanceof Date ? value : new Date(value);
@@ -98,6 +138,10 @@ function emptyState() {
98
138
  lastConsolidateReport: null,
99
139
  lastConsolidateProposals: null,
100
140
  lastConsolidateError: null,
141
+ // 2.2.0 lane A:提案积压自动处理(consolidate.autoResolveProposals)的每日槽。
142
+ lastAutoResolveAt: null,
143
+ lastAutoResolveResult: null,
144
+ lastAutoResolveError: null,
101
145
  lastForgetDate: null,
102
146
  lastForgetAt: null,
103
147
  lastForgetPending: null,
@@ -141,12 +185,12 @@ function normalizeState(raw) {
141
185
  'lastConsolidateAt', 'lastConsolidateReport',
142
186
  'lastForgetAt', 'lastForgetPending', 'lastForgetSuggestionsAt',
143
187
  'lastConclusionDistillAt', 'lastArchiveStateAt', 'lastArchiveStateStatus',
144
- 'lastMigrate200At', 'lastMigrate200Status',
188
+ 'lastMigrate200At', 'lastMigrate200Status', 'lastAutoResolveAt',
145
189
  'lastRunAt', 'lastRunDay', 'lastTrigger',
146
190
  ]) {
147
191
  if (raw[key] == null || typeof raw[key] === 'string') state[key] = raw[key] ?? null;
148
192
  }
149
- for (const key of ['lastConsolidateError', 'lastForgetError', 'lastForgetSuggestionsError', 'lastConclusionDistillError', 'lastArchiveStateError', 'lastMigrate200Error']) {
193
+ for (const key of ['lastConsolidateError', 'lastForgetError', 'lastForgetSuggestionsError', 'lastConclusionDistillError', 'lastArchiveStateError', 'lastMigrate200Error', 'lastAutoResolveError']) {
150
194
  const value = raw[key];
151
195
  if (value == null) {
152
196
  state[key] = null;
@@ -176,6 +220,16 @@ function normalizeState(raw) {
176
220
  skipped: Number(raw.lastConclusionDistillResult.skipped) || 0,
177
221
  }
178
222
  : null;
223
+ state.lastAutoResolveResult = raw.lastAutoResolveResult
224
+ && typeof raw.lastAutoResolveResult === 'object'
225
+ && !Array.isArray(raw.lastAutoResolveResult)
226
+ ? {
227
+ accepted: Number(raw.lastAutoResolveResult.accepted) || 0,
228
+ rejected: Number(raw.lastAutoResolveResult.rejected) || 0,
229
+ reviewed: Number(raw.lastAutoResolveResult.reviewed) || 0,
230
+ pending: Number(raw.lastAutoResolveResult.pending) || 0,
231
+ }
232
+ : null;
179
233
  state.runs = Array.isArray(raw.runs)
180
234
  ? raw.runs.filter((entry) => entry && typeof entry === 'object').slice(-RUN_HISTORY_LIMIT)
181
235
  : [];
@@ -475,6 +529,7 @@ function runDailyMaintenanceSync({
475
529
  day,
476
530
  trigger,
477
531
  consolidate: null,
532
+ autoResolve: null,
478
533
  forget: null,
479
534
  forgetSuggestions: null,
480
535
  conclusionDistill: null,
@@ -565,6 +620,51 @@ function runDailyMaintenanceSync({
565
620
  }
566
621
  }
567
622
 
623
+ // ---- B1b: 2.2.0 lane A — 提案积压自动处理 ----------------------------
624
+ // 「全量入库,取舍交给遗忘机制」:维护跑完 consolidate 后,把提案积压自动
625
+ // 消化一部分——只对完全重复/结构异常 reject、对干净无目标段 accept,其余
626
+ // 留人工。失败只记 autoResolve 错误,不影响 B2-B7,也不改 consolidate 状态。
627
+ if (needConsolidate && summary.consolidate?.status === 'ran') {
628
+ const autoCfg = autoResolveOptions(config);
629
+ if (autoCfg.enabled !== false) {
630
+ try {
631
+ const auto = autoResolveProposals({
632
+ root,
633
+ now: at,
634
+ maxAccept: autoCfg.maxAccept,
635
+ maxAcceptNew: autoCfg.maxAcceptNew,
636
+ });
637
+ summary.autoResolve = {
638
+ status: auto.status,
639
+ accepted: auto.accepted,
640
+ rejected: auto.rejected,
641
+ reviewed: auto.reviewed,
642
+ pending: auto.pending,
643
+ mutations: auto.mutations,
644
+ lastConsolidated: auto.lastConsolidated ?? null,
645
+ pointerMoved: auto.pointerMoved === true,
646
+ stateWritten: auto.stateWritten === true,
647
+ reviewReasons: auto.reviewReasons ?? {},
648
+ };
649
+ state.lastAutoResolveAt = isoStamp(at);
650
+ state.lastAutoResolveResult = {
651
+ accepted: auto.accepted,
652
+ rejected: auto.rejected,
653
+ reviewed: auto.reviewed,
654
+ pending: auto.pending,
655
+ };
656
+ state.lastAutoResolveError = null;
657
+ } catch (error) {
658
+ summary.autoResolve = { status: 'failed', ...errorInfo(error) };
659
+ state.lastAutoResolveError = { ...errorInfo(error), at: isoStamp(at), day };
660
+ warnTo(
661
+ logger,
662
+ `[auto-maintenance] autoResolve 失败(${summary.autoResolve.code})— ${summary.autoResolve.message};提案保持原状,不影响对话`,
663
+ );
664
+ }
665
+ }
666
+ }
667
+
568
668
  // ---- B2: forget dry-run + pending list --------------------------------
569
669
  if (needForget) {
570
670
  try {
@@ -803,9 +903,30 @@ function runDailyMaintenanceSync({
803
903
  ...(summary.archiveState?.status === 'failed' ? { archiveStateError: summary.archiveState.code } : {}),
804
904
  ...(summary.migrate200?.state ? { migrate200State: summary.migrate200.state } : {}),
805
905
  ...(summary.rotation ? { rotationArchived: summary.rotation.archived ?? 0 } : {}),
906
+ autoResolve: summary.autoResolve?.status ?? 'skipped',
907
+ ...(summary.autoResolve && summary.autoResolve.status !== 'failed'
908
+ ? {
909
+ autoAccepted: summary.autoResolve.accepted ?? 0,
910
+ autoRejected: summary.autoResolve.rejected ?? 0,
911
+ autoPending: summary.autoResolve.pending ?? 0,
912
+ }
913
+ : {}),
914
+ ...(summary.autoResolve?.status === 'failed' ? { autoResolveError: summary.autoResolve.code } : {}),
806
915
  },
807
916
  ].slice(-RUN_HISTORY_LIMIT);
808
917
 
918
+ // 2.2.0 lane A: backlog sidecar (<1KB) so recall/status never parse the
919
+ // 300KB+ memory-state.json just to show "how much is pending".
920
+ try {
921
+ summary.backlog = writeBacklogSidecar(root, { now: at, day });
922
+ } catch (error) {
923
+ summary.backlog = { status: 'failed', ...errorInfo(error) };
924
+ warnTo(
925
+ logger,
926
+ `[auto-maintenance] backlog sidecar 写入失败(${summary.backlog.code})— 不影响维护结果`,
927
+ );
928
+ }
929
+
809
930
  try {
810
931
  const written = writeScheduleState(root, state, { now: at });
811
932
  summary.state = written.state;
@@ -11,7 +11,7 @@
11
11
 
12
12
  import { memoryError, memoryRootFromConfig } from './paths.js';
13
13
  import { memoryRecall } from './recall.js';
14
- import { scanCards } from './index.js';
14
+ import { scanCards, RECALL_SCAN_DIRS } from './index.js';
15
15
  import { appendAuditRecord } from './audit-records.js';
16
16
  // M11: 统一召回入口(brain.mjs)——空命中时给出候选线索,不改变 hits/证据门形状。
17
17
  import { selectCards as brainSelectCards } from '../recall/brain.mjs';
@@ -132,7 +132,8 @@ export function recallV2(args = {}, config = {}) {
132
132
  const root = memoryRootFromConfig(config);
133
133
 
134
134
  const recalled = memoryRecall({ query, topK: Math.max(topK, 5), status: includeForgotten ? 'any' : 'active' }, { memoryRoot: root });
135
- const cards = new Map((scanCards(root) || []).map((card) => [card.rel, card]));
135
+ // 召回面与 memoryRecall 一致:topics + journal + procedures(程序卡)。
136
+ const cards = new Map((scanCards(root, { dirs: RECALL_SCAN_DIRS }) || []).map((card) => [card.rel, card]));
136
137
  let hits = [];
137
138
  for (const row of Array.isArray(recalled.results) ? recalled.results : []) {
138
139
  if (row?.type === 'event') continue; // D2: event/AutoCard layer is cold archive, not recalled.
@@ -169,7 +170,8 @@ export function recallV2(args = {}, config = {}) {
169
170
  }
170
171
  const gate = evidenceGate({ hits, question: query });
171
172
  // 1.8.2 D2: no auto-card read; hits are curated cards only.
172
- const curatedHits = hits.slice(0, Math.min(2, topK));
173
+ // 2.2.0 lane-B:hits 截断 2→3,避免 procedure 命中被 topics 挤掉。
174
+ const curatedHits = hits.slice(0, Math.min(3, topK));
173
175
  hits = [...curatedHits].slice(0, topK);
174
176
  const finalGate = evidenceGate({ hits, question: query });
175
177
  const fastAnswer = finalGate.fastEligible ? buildFastAnswer({ question: query, hit: hits[0], gate: finalGate }) : null;
@@ -10,7 +10,7 @@
10
10
  // "never decay or merge", not "hidden".
11
11
 
12
12
  import { memoryError, memoryRootFromConfig } from './paths.js';
13
- import { scanCards } from './index.js';
13
+ import { scanCards, RECALL_SCAN_DIRS } from './index.js';
14
14
  import { readVerifiedCardAnchors } from './card-anchors.js';
15
15
  import { searchEventsReadOnly } from './event-index.js';
16
16
  import { isHistoricalQuery, readLifecycle } from './lifecycle.js';
@@ -24,6 +24,9 @@ export const RECALL_STATUSES = Object.freeze(['active', 'locked', 'archived', 'a
24
24
  // SPEC-1.8.11 D9:historical 卡在工具层同样要沉层(与 pre-step 注入的 lifecycleRank 一致),
25
25
  // 但工具层不改条数/过滤:只按权重改分数,同一 lifecycle 内原有分数序不变。
26
26
  export const HISTORICAL_SCORE_WEIGHT = 0.3;
27
+ // 程序卡(procedures/)在召回面给固定加成:动作类 query(发布/安装/回滚/删除…)
28
+ // 必中 procedure 卡;固定系数,不引入概率/阈值判据(工作区 AGENTS.md 第 21 条)。
29
+ export const PROCEDURE_SCORE_WEIGHT = 1.15;
27
30
 
28
31
  const CJK_RUN = /[\u3400-\u9fff]+/g;
29
32
  const ASCII_WORD = /[a-z0-9_]{2,}/g;
@@ -189,7 +192,8 @@ export function memoryRecall(args, config = {}) {
189
192
  // 显式历史查询(以前/旧版/被取代…)不降权;普通查询把 historical 卡乘权重沉下去。
190
193
  const historyQuery = isHistoricalQuery(query);
191
194
 
192
- const scanned = scanCards(root);
195
+ // 召回面扫 topics + journal + procedures(程序卡);索引面 memoryIndex 仍不含 procedures。
196
+ const scanned = scanCards(root, { dirs: RECALL_SCAN_DIRS });
193
197
  const sidecar = readVerifiedCardAnchors({ memoryRoot: root }).links;
194
198
  const includeAuto = args?.includeAuto === true || args?.archive === true;
195
199
  const results = [];
@@ -202,8 +206,10 @@ export function memoryRecall(args, config = {}) {
202
206
  const { score, hits } = scoreCard(query, card);
203
207
  if (score <= 0 || hits.length === 0) continue;
204
208
  const lifecycle = readLifecycle(card);
205
- // historical 只在非历史查询里降权;canonical/普通卡不变(权重 1)。
206
- const weight = lifecycle === 'historical' && !historyQuery ? HISTORICAL_SCORE_WEIGHT : 1;
209
+ // historical 只在非历史查询里降权;程序卡给固定加成;canonical/普通卡权重 1。
210
+ const lifecycleWeight = lifecycle === 'historical' && !historyQuery ? HISTORICAL_SCORE_WEIGHT : 1;
211
+ const procedureWeight = card.procedure === true ? PROCEDURE_SCORE_WEIGHT : 1;
212
+ const weight = lifecycleWeight * procedureWeight;
207
213
  const weightedScore = weight === 1 ? score : Math.round(score * weight * 100) / 100;
208
214
  const link = sidecar.get(card.rel);
209
215
  results.push({
@@ -181,7 +181,12 @@ export function selectProcedures(memoryRoot, queryText, maxItems = 2) {
181
181
  const total = totalWeight(queryWeights);
182
182
  const score = Math.min(1, matchedWeight(queryWeights, tokenSet(trigger)) / total);
183
183
  if (score <= 0) continue;
184
- scored.push({ name: String(card.name ?? ''), trigger: Array.isArray(card.trigger) ? card.trigger.slice(0, 4) : [String(card.trigger ?? '')], score });
184
+ scored.push({
185
+ name: String(card.name ?? ''),
186
+ trigger: Array.isArray(card.trigger) ? card.trigger.slice(0, 4) : [String(card.trigger ?? '')],
187
+ path: String(card.rel ?? ''),
188
+ score,
189
+ });
185
190
  }
186
191
  scored.sort((left, right) => right.score - left.score || left.name.localeCompare(right.name));
187
192
  return scored.slice(0, Math.max(0, maxItems));
@@ -206,6 +211,22 @@ function textOf(message) {
206
211
  return parts.length > 0 ? parts.join('\n') : '';
207
212
  }
208
213
 
214
+ /**
215
+ * 当前步最后一条真实用户消息的首段文本。与 recall/index.js 里 firstTextOf(lastUserMessage)
216
+ * 同源口径(取首个 content text 块,回退 data.text),供 continuity-volatile 匹配动作动词
217
+ * 选程序卡;注入消息 / 子代理消息不算用户消息(isRealUserMessage 过滤)。
218
+ */
219
+ export function lastUserTextFromMessages(messages) {
220
+ const list = Array.isArray(messages) ? messages : [];
221
+ const lastUserMessage = [...list].reverse().find((message) => isRealUserMessage(message)) ?? null;
222
+ if (!lastUserMessage) return '';
223
+ const content = Array.isArray(lastUserMessage.content) ? lastUserMessage.content : [];
224
+ const block = content.find((item) => item?.type === 'text' && typeof item.text === 'string');
225
+ if (block) return block.text;
226
+ if (typeof lastUserMessage.text === 'string') return lastUserMessage.text;
227
+ return '';
228
+ }
229
+
209
230
  function normalizeTurn(payload) {
210
231
  const value = Number(payload?.turn);
211
232
  return Number.isFinite(value) ? value : null;
@@ -391,13 +412,30 @@ export function renderPendingBlock({ pending, items = [], procedures = [], scann
391
412
  return { hit: true, block };
392
413
  }
393
414
 
394
- function hardgateEvidence({ pending, items = 0, procedures = 0, scanned = 0, extra = [] } = {}) {
415
+ function hardgateEvidence({
416
+ pending,
417
+ items = 0,
418
+ procedures = 0,
419
+ scanned = 0,
420
+ procedureNames = [],
421
+ procedurePaths = [],
422
+ extra = [],
423
+ } = {}) {
424
+ // 2.2.0 lane-B:程序卡回执(供 lane-C 动作门做匹配)。格式稳定:key=value,
425
+ // 最多 2 项、'|' 分隔、相对路径;无程序卡命中时不写这两行(旧行 sha 不变)。
426
+ const names = (Array.isArray(procedureNames) ? procedureNames : [])
427
+ .filter((name) => typeof name === 'string' && name !== '').slice(0, 2);
428
+ const paths = (Array.isArray(procedurePaths) ? procedurePaths : [])
429
+ .filter((item) => typeof item === 'string' && item !== '').slice(0, 2);
395
430
  return [
396
431
  `recallId=${pending?.recallId ?? 'unknown'}`,
397
432
  `items=${items}`,
398
433
  `procedures=${procedures}`,
399
434
  `scanned=${scanned}`,
400
435
  ...(Array.isArray(extra) ? extra : []),
436
+ // 仅追加在既有字段之后,2.1.0 面板按 key=value 读,旧字段位置不变。
437
+ ...(names.length > 0 ? [`procedureNames=${names.join('|')}`] : []),
438
+ ...(paths.length > 0 ? [`procedurePaths=${paths.join('|')}`] : []),
401
439
  ];
402
440
  }
403
441
 
@@ -412,6 +450,8 @@ export function finishPendingInjection({
412
450
  items = 0,
413
451
  procedures = 0,
414
452
  scanned = 0,
453
+ procedureNames = [],
454
+ procedurePaths = [],
415
455
  extra = [],
416
456
  metrics = null,
417
457
  warn,
@@ -453,7 +493,7 @@ export function finishPendingInjection({
453
493
  turn: pending?.turn,
454
494
  decision: resultVerdict.decision,
455
495
  reason: resultVerdict.reason,
456
- evidence: hardgateEvidence({ pending, items, procedures, scanned, extra }),
496
+ evidence: hardgateEvidence({ pending, items, procedures, scanned, procedureNames, procedurePaths, extra }),
457
497
  metrics,
458
498
  warn,
459
499
  });
@@ -480,7 +520,9 @@ export function recordPendingFailure({ pending, reason = RECALL_FAIL_CODE_INJECT
480
520
  }
481
521
 
482
522
  /** 生产链尾命中/归档分支:文本已注入,只补写唯一一行 gate-log。 */
483
- export function recordPendingResult({ pending, hit, items = 0, procedures = 0, scanned = 0, extra = [], metrics = null, warn } = {}) {
523
+ export function recordPendingResult({
524
+ pending, hit, items = 0, procedures = 0, scanned = 0, procedureNames = [], procedurePaths = [], extra = [], metrics = null, warn,
525
+ } = {}) {
484
526
  // B3 P1 接线:ok/zero-hit 判决由统一判决函数给(命中 → ok/hit,零命中 → zero-hit/zero-hit)。
485
527
  const verdict = assertRecallInjectionDecision(resolveRecallInjectionDecision({ zeroHit: hit !== true }));
486
528
  return writeGateRow(pending?.memoryRoot ?? '', {
@@ -488,7 +530,7 @@ export function recordPendingResult({ pending, hit, items = 0, procedures = 0, s
488
530
  turn: pending?.turn,
489
531
  decision: verdict.decision,
490
532
  reason: verdict.reason,
491
- evidence: hardgateEvidence({ pending, items, procedures, scanned, extra }),
533
+ evidence: hardgateEvidence({ pending, items, procedures, scanned, procedureNames, procedurePaths, extra }),
492
534
  metrics,
493
535
  warn,
494
536
  });
@@ -20,6 +20,9 @@
20
20
 
21
21
  import fs from 'node:fs';
22
22
  import path from 'node:path';
23
+ import { createHash } from 'node:crypto';
24
+
25
+ import { lastUserTextFromMessages, selectProcedures } from './brain.mjs';
23
26
 
24
27
  // ── 契约常量(改动即契约变更,需同步 PLAN-v0.4 §0/§2)────────────────────────
25
28
 
@@ -57,6 +60,54 @@ export const DEFAULT_MAX_CARD_CHARS = 600;
57
60
  /** 模块版本,写进 record 便于审计区分实现批次。 */
58
61
  export const CONTINUITY_VOLATILE_VERSION = '2.1.0-lane-core/1';
59
62
 
63
+ // ── 2.2.0 lane-B:动作词 → 程序卡(procedures/)额外注入 ──────────────────────
64
+ // 当前步真实用户文本命中动作动词时,按 trigger 选 1 张程序卡,作为 `[程序]` 行
65
+ // 追加在「已读卡」行之后(≤300 字,吃 990/400 预算)。固定动词表,无概率/阈值。
66
+ export const PROCEDURE_INJECT_MAX_CHARS = 300;
67
+ const PROCEDURE_ACTION_RE = /(发布|安装|回滚|删除|publish|release|install|rollback|remove)/iu;
68
+ const PROCEDURE_CACHE_LIMIT = 32;
69
+ /** key = sha1(memoryRoot + userText) + procedures 目录 mtime;避免每步重扫 32 张卡。 */
70
+ const procedureCache = new Map();
71
+
72
+ function proceduresDirMtime(memoryRoot) {
73
+ try {
74
+ return fs.statSync(path.join(memoryRoot, 'procedures')).mtimeMs;
75
+ } catch {
76
+ return 0;
77
+ }
78
+ }
79
+
80
+ function resolveActionProcedures(memoryRoot, text) {
81
+ const query = collapseLine(text);
82
+ if (query === '' || !PROCEDURE_ACTION_RE.test(query)) return [];
83
+ const digest = createHash('sha1').update(`${memoryRoot}\u0000${query}`).digest('hex');
84
+ const key = `${digest}:${proceduresDirMtime(memoryRoot)}`;
85
+ if (procedureCache.has(key)) return procedureCache.get(key);
86
+ let selected = [];
87
+ try {
88
+ selected = selectProcedures(memoryRoot, query, 1);
89
+ } catch {
90
+ selected = [];
91
+ }
92
+ const result = Array.isArray(selected) ? selected.slice(0, 1) : [];
93
+ if (procedureCache.size >= PROCEDURE_CACHE_LIMIT) procedureCache.clear();
94
+ procedureCache.set(key, result);
95
+ return result;
96
+ }
97
+
98
+ /** `[程序] 名字 · 触发词 / …`,与 recall-core 硬门块的行格式保持一致。 */
99
+ function renderProcedureLine(procedures) {
100
+ const rows = (Array.isArray(procedures) ? procedures : []).map((item) => {
101
+ const name = collapseLine(item && item.name);
102
+ if (name === '') return '';
103
+ const trigger = Array.isArray(item && item.trigger)
104
+ ? item.trigger.map((value) => collapseLine(value)).filter(Boolean).join(' / ')
105
+ : collapseLine(item && item.trigger);
106
+ return trigger === '' ? `[程序] ${name}` : `[程序] ${name} · ${trigger}`;
107
+ }).filter(Boolean);
108
+ return rows.join(' / ');
109
+ }
110
+
60
111
  // ── 基础小工具 ────────────────────────────────────────────────────────────────
61
112
 
62
113
  /** 统一换行、去掉零宽 BOM、压缩连续空白;标题/位置等单行字段用。 */
@@ -209,7 +260,7 @@ function pushSegment(state, raw, perSegmentMax) {
209
260
  * 通用块拼装:第一行固定、人格头/位置/读卡摘要/卡正文按优先级吃预算。
210
261
  * 预算不足时从后往前被裁;始终保证返回 text.length ≤ cap。
211
262
  */
212
- function composeBlock({ firstLine, cap, personaHeader, positionLine, cards, replayLine, mode }) {
263
+ function composeBlock({ firstLine, cap, personaHeader, positionLine, cards, procedures, replayLine, mode }) {
213
264
  const limit = Math.max(1, Math.floor(Number(cap) || 1));
214
265
  const state = { text: hardTrim(firstLine, limit), cap: limit };
215
266
  if (replayLine) pushLine(state, replayLine);
@@ -224,6 +275,8 @@ function composeBlock({ firstLine, cap, personaHeader, positionLine, cards, repl
224
275
  if (titles.length > 0) {
225
276
  pushLine(state, `已读卡:${titles.join(' / ')}`);
226
277
  }
278
+ const procedureLine = renderProcedureLine(procedures);
279
+ if (procedureLine !== '') pushSegment(state, procedureLine, PROCEDURE_INJECT_MAX_CHARS);
227
280
  for (const card of Array.isArray(cards) ? cards : []) {
228
281
  const body = collapse(card && card.text);
229
282
  if (body === '') continue;
@@ -248,6 +301,7 @@ export function composeVolatileBlock({
248
301
  turn = 0,
249
302
  sessionId = 'unknown',
250
303
  mode = 'volatile',
304
+ procedures = [],
251
305
  } = {}) {
252
306
  const effectiveCap = Math.max(1, Math.floor(Number(cap) || STEP1_MAX_CHARS));
253
307
  const block = composeBlock({
@@ -256,6 +310,7 @@ export function composeVolatileBlock({
256
310
  personaHeader,
257
311
  positionLine: positionLine || buildPositionLine({ turn, step, sessionId, mode }),
258
312
  cards,
313
+ procedures,
259
314
  replayLine: replayReason ? buildReplayLine(replayReason, mode) : null,
260
315
  mode,
261
316
  });
@@ -649,6 +704,7 @@ export function createContinuityVolatile(options = {}) {
649
704
  chars: ctx.chars,
650
705
  volatileChars: ctx.volatileChars,
651
706
  cards: ctx.cards,
707
+ procedures: ctx.procedures,
652
708
  drop: ctx.drop,
653
709
  fail: ctx.fail,
654
710
  ms: Math.max(0, Math.round(clock() - startedAt)),
@@ -817,6 +873,7 @@ export function createContinuityVolatile(options = {}) {
817
873
  }
818
874
 
819
875
  let text;
876
+ const procedures = ctx.subagent ? [] : resolveActionProcedures(config.memoryRoot, ctx.userText || '');
820
877
  try {
821
878
  text = ctx.subagent
822
879
  ? composeSubagentBlock({
@@ -829,6 +886,7 @@ export function createContinuityVolatile(options = {}) {
829
886
  personaHeader: resolvePersona(config, payload),
830
887
  positionLine: buildPositionLine({ turn: ctx.turn, step: ctx.step, sessionId: ctx.sessionId, mode: 'volatile' }),
831
888
  cards,
889
+ procedures,
832
890
  replayReason: ctx.replay,
833
891
  step: ctx.step,
834
892
  turn: ctx.turn,
@@ -883,6 +941,7 @@ export function createContinuityVolatile(options = {}) {
883
941
  ctx.chars = text.length;
884
942
  ctx.volatileChars = text.length;
885
943
  ctx.cards = cards.length;
944
+ ctx.procedures = procedures.length;
886
945
  ctx.drop = dropped;
887
946
  ctx.fail = 0;
888
947
  ctx.injected = true;
@@ -917,6 +976,8 @@ export function createContinuityVolatile(options = {}) {
917
976
  chars: 0,
918
977
  volatileChars: 0,
919
978
  cards: 0,
979
+ procedures: 0,
980
+ userText: '',
920
981
  drop: 0,
921
982
  fail: 0,
922
983
  };
@@ -934,6 +995,9 @@ export function createContinuityVolatile(options = {}) {
934
995
  return attach(decision, ctx, startedAt);
935
996
  }
936
997
 
998
+ // 动作词匹配只取当前步最后一条真实用户消息(与 recall/index.js 的 hardgate 同源口径)。
999
+ ctx.userText = subagent ? '' : lastUserTextFromMessages(decision.messages);
1000
+
937
1001
  const tracking = trackSession(sessionId);
938
1002
  const replay = replayReasonFor({
939
1003
  turn,
@@ -1258,6 +1258,7 @@ export function apply(ctx, config = {}) {
1258
1258
  let zeroRendered = null;
1259
1259
  let zeroLane = null;
1260
1260
  let zeroProcedures = 0;
1261
+ let zeroProcedureList = [];
1261
1262
  if (hardgatePending) {
1262
1263
  let procedures = [];
1263
1264
  try {
@@ -1266,6 +1267,7 @@ export function apply(ctx, config = {}) {
1266
1267
  warn('HARDGATE_PROCEDURES_FAILED', error?.code ?? error?.message ?? error);
1267
1268
  }
1268
1269
  zeroProcedures = procedures.length;
1270
+ zeroProcedureList = procedures;
1269
1271
  zeroRendered = renderPendingBlock({
1270
1272
  pending: hardgatePending,
1271
1273
  items: [],
@@ -1332,6 +1334,8 @@ export function apply(ctx, config = {}) {
1332
1334
  factory: zeroFactory,
1333
1335
  items: 0,
1334
1336
  procedures: zeroProcedures,
1337
+ procedureNames: zeroProcedureList.map((item) => String(item?.name ?? '')),
1338
+ procedurePaths: zeroProcedureList.map((item) => String(item?.path ?? '')),
1335
1339
  scanned: result.hits.eligible,
1336
1340
  extra: zeroBudget === null ? [] : [zeroBudget.evidence],
1337
1341
  metrics: zeroMetrics,
@@ -1355,6 +1359,7 @@ export function apply(ctx, config = {}) {
1355
1359
  // 当前线都在块里,capBlock 保证 ≤ budget。
1356
1360
  let hardgateHit = null;
1357
1361
  let hardgateProcedures = 0;
1362
+ let hardgateProcedureList = [];
1358
1363
  if (hardgatePending && !fromArchive) {
1359
1364
  let procedures = [];
1360
1365
  try {
@@ -1366,6 +1371,7 @@ export function apply(ctx, config = {}) {
1366
1371
  finalText = rendered.block;
1367
1372
  hardgateHit = rendered.hit;
1368
1373
  hardgateProcedures = procedures.length;
1374
+ hardgateProcedureList = procedures;
1369
1375
  }
1370
1376
  // B3 C6/C4:最终块(硬门块或 legacy 块)统一过 990 字车道并产出注入度量;
1371
1377
  // 该度量写进 recall-log(injectedChars/injectedTokens)与 gate-log(B1/C1)。
@@ -1480,6 +1486,8 @@ export function apply(ctx, config = {}) {
1480
1486
  hit: fromArchive ? true : hardgateHit === true,
1481
1487
  items: fromArchive ? archiveItems.length : result.items.length,
1482
1488
  procedures: fromArchive ? 0 : hardgateProcedures,
1489
+ procedureNames: fromArchive ? [] : hardgateProcedureList.map((item) => String(item?.name ?? '')),
1490
+ procedurePaths: fromArchive ? [] : hardgateProcedureList.map((item) => String(item?.path ?? '')),
1483
1491
  scanned: result.hits.eligible,
1484
1492
  extra: [turnBudget.evidence],
1485
1493
  metrics: laneMetrics,
package/src/tools.js CHANGED
@@ -58,6 +58,8 @@ import { normalizeTiering, buildTierHint, DEFAULT_TIERING } from './memory/tiers
58
58
  import { liveUpdate, liveList, liveGet, livePrune } from './live.js';
59
59
  import { sessionIdOfLogFile } from './live-target.js';
60
60
  import { privacyScan } from './recall/privacy.mjs';
61
+ import { appendGateLog } from './recall/gate-log.mjs';
62
+ import { ACTION_KEYWORDS } from './gate/action-gate.js';
61
63
  import { searchEventsFts, searchEventsReadOnly } from './memory/event-index.js';
62
64
  import {
63
65
  buildTurnItems,
@@ -2019,6 +2021,49 @@ function memoryTool(name, fn) {
2019
2021
  };
2020
2022
  }
2021
2023
 
2024
+ /**
2025
+ * 2.2.0 动作前回忆门(lane-C):memory_recall 命中动作类查询、且结果里带回 procedure 卡时,
2026
+ * 往 gate-log 写一条 gate='action' / decision='ok' 的显式回执行,作为「执行前回忆过」的凭据。
2027
+ * 只读召回本身不变(不写卡、不建 INDEX);回执写失败一律 fail-open,绝不影响召回结果。
2028
+ */
2029
+ function withActionGateReceipt(name, invoke) {
2030
+ return (args, config) => {
2031
+ const result = invoke(args, config);
2032
+ try {
2033
+ writeActionGateReceipt(name, args, result, config);
2034
+ } catch {
2035
+ /* 回执写失败不影响召回:动作门会按「无回执」处理 */
2036
+ }
2037
+ return result;
2038
+ };
2039
+ }
2040
+
2041
+ function writeActionGateReceipt(name, args, result, config) {
2042
+ if (!result || result.ok !== true || !Array.isArray(result.results)) return;
2043
+ const query = typeof args?.query === 'string' ? args.query : '';
2044
+ if (query.trim() === '') return;
2045
+ const lowerQuery = query.toLowerCase();
2046
+ if (!ACTION_KEYWORDS.some((keyword) => lowerQuery.includes(keyword.toLowerCase()))) return;
2047
+ const procedures = result.results
2048
+ .filter((row) => row && typeof row.path === 'string' && row.path.startsWith('procedures/'))
2049
+ .map((row) => (typeof row.title === 'string' && row.title.trim() !== '' ? row.title.trim() : row.path));
2050
+ if (procedures.length === 0) return;
2051
+ if (!isPlainObject(config)) return;
2052
+ const memoryRoot = memRoot(config, process.env);
2053
+ if (typeof memoryRoot !== 'string' || memoryRoot === '') return;
2054
+ const sessionId = resolveCallerSessionId(config).id;
2055
+ appendGateLog(memoryRoot, {
2056
+ sessionId,
2057
+ gate: 'action',
2058
+ decision: 'ok',
2059
+ reason: `recall-tool:${name}`,
2060
+ evidence: [
2061
+ 'source=memory_recall_tool',
2062
+ `procedureNames=${procedures.slice(0, 2).join('|')}`,
2063
+ ],
2064
+ });
2065
+ }
2066
+
2022
2067
  /**
2023
2068
  * M10 双路由:写类 memory 工具的落盘门委托。
2024
2069
  * 新路径 = memory/land.mjs(批次 B,当前 fail-closed 骨架);land 未实现时如实回退到旧路径,
@@ -2953,7 +2998,7 @@ export const TOOLS = [
2953
2998
  archive: { type: 'boolean', description: 'archive:true 走冷档 fail-closed 检索(2.0.0 W3b):返回 {ok, archived:true, items, manifestSha, stats};冷档离线/坏 state 抛 E_HG_ARCHIVE_OFFLINE,manifest schema/index 不符抛 E_HG_ARCHIVE_MIGRATE_MISMATCH;未配置冷档则静默空。默认 false(本地卡召回)。' },
2954
2999
  },
2955
3000
  output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
2956
- invoke: memoryTool('memory_recall', memoryRecall),
3001
+ invoke: withActionGateReceipt('memory_recall', memoryTool('memory_recall', memoryRecall)),
2957
3002
  },
2958
3003
  {
2959
3004
  name: 'memory_recall_v2',