@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
@@ -12,6 +12,7 @@
12
12
 
13
13
  import { scanCards } from '../memory/index.js';
14
14
  import { scanProcedures } from '../memory/procedure.js';
15
+ import { applyFeedbackRanking } from '../memory/recall-feedback.mjs';
15
16
 
16
17
  import { loadCards } from './cards.mjs';
17
18
  import { renderCurrentLine } from './current-line.mjs';
@@ -150,12 +151,18 @@ export function selectCards(memoryRoot, queryText, cfg = {}) {
150
151
  } catch {
151
152
  result = { items: [], hits: {} };
152
153
  }
153
- const items = (Array.isArray(result.items) ? result.items : []).slice(0, maxItems).map((item) => ({
154
+ let items = (Array.isArray(result.items) ? result.items : []).map((item) => ({
154
155
  path: item.path,
155
156
  title: item.title,
156
157
  score: item.score,
157
158
  excerpt: item.excerpt,
158
159
  }));
160
+ // D20 融合点:上一轮 memory_feedback 的 up/down 反映到注入排序(零反馈 identity,失败 fail-open)。
161
+ try {
162
+ items = applyFeedbackRanking(memoryRoot, items).slice(0, maxItems);
163
+ } catch {
164
+ items = items.slice(0, maxItems);
165
+ }
159
166
  const droppedBy = {};
160
167
  for (const [key, value] of Object.entries(result.hits ?? {})) {
161
168
  if (typeof value === 'number' && value > 0 && key.startsWith('dropped')) droppedBy[key] = value;
@@ -181,7 +188,12 @@ export function selectProcedures(memoryRoot, queryText, maxItems = 2) {
181
188
  const total = totalWeight(queryWeights);
182
189
  const score = Math.min(1, matchedWeight(queryWeights, tokenSet(trigger)) / total);
183
190
  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 });
191
+ scored.push({
192
+ name: String(card.name ?? ''),
193
+ trigger: Array.isArray(card.trigger) ? card.trigger.slice(0, 4) : [String(card.trigger ?? '')],
194
+ path: String(card.rel ?? ''),
195
+ score,
196
+ });
185
197
  }
186
198
  scored.sort((left, right) => right.score - left.score || left.name.localeCompare(right.name));
187
199
  return scored.slice(0, Math.max(0, maxItems));
@@ -206,6 +218,22 @@ function textOf(message) {
206
218
  return parts.length > 0 ? parts.join('\n') : '';
207
219
  }
208
220
 
221
+ /**
222
+ * 当前步最后一条真实用户消息的首段文本。与 recall/index.js 里 firstTextOf(lastUserMessage)
223
+ * 同源口径(取首个 content text 块,回退 data.text),供 continuity-volatile 匹配动作动词
224
+ * 选程序卡;注入消息 / 子代理消息不算用户消息(isRealUserMessage 过滤)。
225
+ */
226
+ export function lastUserTextFromMessages(messages) {
227
+ const list = Array.isArray(messages) ? messages : [];
228
+ const lastUserMessage = [...list].reverse().find((message) => isRealUserMessage(message)) ?? null;
229
+ if (!lastUserMessage) return '';
230
+ const content = Array.isArray(lastUserMessage.content) ? lastUserMessage.content : [];
231
+ const block = content.find((item) => item?.type === 'text' && typeof item.text === 'string');
232
+ if (block) return block.text;
233
+ if (typeof lastUserMessage.text === 'string') return lastUserMessage.text;
234
+ return '';
235
+ }
236
+
209
237
  function normalizeTurn(payload) {
210
238
  const value = Number(payload?.turn);
211
239
  return Number.isFinite(value) ? value : null;
@@ -391,13 +419,30 @@ export function renderPendingBlock({ pending, items = [], procedures = [], scann
391
419
  return { hit: true, block };
392
420
  }
393
421
 
394
- function hardgateEvidence({ pending, items = 0, procedures = 0, scanned = 0, extra = [] } = {}) {
422
+ function hardgateEvidence({
423
+ pending,
424
+ items = 0,
425
+ procedures = 0,
426
+ scanned = 0,
427
+ procedureNames = [],
428
+ procedurePaths = [],
429
+ extra = [],
430
+ } = {}) {
431
+ // 2.2.0 lane-B:程序卡回执(供 lane-C 动作门做匹配)。格式稳定:key=value,
432
+ // 最多 2 项、'|' 分隔、相对路径;无程序卡命中时不写这两行(旧行 sha 不变)。
433
+ const names = (Array.isArray(procedureNames) ? procedureNames : [])
434
+ .filter((name) => typeof name === 'string' && name !== '').slice(0, 2);
435
+ const paths = (Array.isArray(procedurePaths) ? procedurePaths : [])
436
+ .filter((item) => typeof item === 'string' && item !== '').slice(0, 2);
395
437
  return [
396
438
  `recallId=${pending?.recallId ?? 'unknown'}`,
397
439
  `items=${items}`,
398
440
  `procedures=${procedures}`,
399
441
  `scanned=${scanned}`,
400
442
  ...(Array.isArray(extra) ? extra : []),
443
+ // 仅追加在既有字段之后,2.1.0 面板按 key=value 读,旧字段位置不变。
444
+ ...(names.length > 0 ? [`procedureNames=${names.join('|')}`] : []),
445
+ ...(paths.length > 0 ? [`procedurePaths=${paths.join('|')}`] : []),
401
446
  ];
402
447
  }
403
448
 
@@ -412,6 +457,8 @@ export function finishPendingInjection({
412
457
  items = 0,
413
458
  procedures = 0,
414
459
  scanned = 0,
460
+ procedureNames = [],
461
+ procedurePaths = [],
415
462
  extra = [],
416
463
  metrics = null,
417
464
  warn,
@@ -453,7 +500,7 @@ export function finishPendingInjection({
453
500
  turn: pending?.turn,
454
501
  decision: resultVerdict.decision,
455
502
  reason: resultVerdict.reason,
456
- evidence: hardgateEvidence({ pending, items, procedures, scanned, extra }),
503
+ evidence: hardgateEvidence({ pending, items, procedures, scanned, procedureNames, procedurePaths, extra }),
457
504
  metrics,
458
505
  warn,
459
506
  });
@@ -480,7 +527,9 @@ export function recordPendingFailure({ pending, reason = RECALL_FAIL_CODE_INJECT
480
527
  }
481
528
 
482
529
  /** 生产链尾命中/归档分支:文本已注入,只补写唯一一行 gate-log。 */
483
- export function recordPendingResult({ pending, hit, items = 0, procedures = 0, scanned = 0, extra = [], metrics = null, warn } = {}) {
530
+ export function recordPendingResult({
531
+ pending, hit, items = 0, procedures = 0, scanned = 0, procedureNames = [], procedurePaths = [], extra = [], metrics = null, warn,
532
+ } = {}) {
484
533
  // B3 P1 接线:ok/zero-hit 判决由统一判决函数给(命中 → ok/hit,零命中 → zero-hit/zero-hit)。
485
534
  const verdict = assertRecallInjectionDecision(resolveRecallInjectionDecision({ zeroHit: hit !== true }));
486
535
  return writeGateRow(pending?.memoryRoot ?? '', {
@@ -488,7 +537,7 @@ export function recordPendingResult({ pending, hit, items = 0, procedures = 0, s
488
537
  turn: pending?.turn,
489
538
  decision: verdict.decision,
490
539
  reason: verdict.reason,
491
- evidence: hardgateEvidence({ pending, items, procedures, scanned, extra }),
540
+ evidence: hardgateEvidence({ pending, items, procedures, scanned, procedureNames, procedurePaths, extra }),
492
541
  metrics,
493
542
  warn,
494
543
  });
@@ -20,6 +20,14 @@
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';
26
+ import {
27
+ createTaskStateStore,
28
+ isTaskStateRelated,
29
+ TASK_STATE_INJECT_MAX_CHARS,
30
+ } from '../memory/task-state.mjs';
23
31
 
24
32
  // ── 契约常量(改动即契约变更,需同步 PLAN-v0.4 §0/§2)────────────────────────
25
33
 
@@ -57,6 +65,54 @@ export const DEFAULT_MAX_CARD_CHARS = 600;
57
65
  /** 模块版本,写进 record 便于审计区分实现批次。 */
58
66
  export const CONTINUITY_VOLATILE_VERSION = '2.1.0-lane-core/1';
59
67
 
68
+ // ── 2.2.0 lane-B:动作词 → 程序卡(procedures/)额外注入 ──────────────────────
69
+ // 当前步真实用户文本命中动作动词时,按 trigger 选 1 张程序卡,作为 `[程序]` 行
70
+ // 追加在「已读卡」行之后(≤300 字,吃 990/400 预算)。固定动词表,无概率/阈值。
71
+ export const PROCEDURE_INJECT_MAX_CHARS = 300;
72
+ const PROCEDURE_ACTION_RE = /(发布|安装|回滚|删除|publish|release|install|rollback|remove)/iu;
73
+ const PROCEDURE_CACHE_LIMIT = 32;
74
+ /** key = sha1(memoryRoot + userText) + procedures 目录 mtime;避免每步重扫 32 张卡。 */
75
+ const procedureCache = new Map();
76
+
77
+ function proceduresDirMtime(memoryRoot) {
78
+ try {
79
+ return fs.statSync(path.join(memoryRoot, 'procedures')).mtimeMs;
80
+ } catch {
81
+ return 0;
82
+ }
83
+ }
84
+
85
+ function resolveActionProcedures(memoryRoot, text) {
86
+ const query = collapseLine(text);
87
+ if (query === '' || !PROCEDURE_ACTION_RE.test(query)) return [];
88
+ const digest = createHash('sha1').update(`${memoryRoot}\u0000${query}`).digest('hex');
89
+ const key = `${digest}:${proceduresDirMtime(memoryRoot)}`;
90
+ if (procedureCache.has(key)) return procedureCache.get(key);
91
+ let selected = [];
92
+ try {
93
+ selected = selectProcedures(memoryRoot, query, 1);
94
+ } catch {
95
+ selected = [];
96
+ }
97
+ const result = Array.isArray(selected) ? selected.slice(0, 1) : [];
98
+ if (procedureCache.size >= PROCEDURE_CACHE_LIMIT) procedureCache.clear();
99
+ procedureCache.set(key, result);
100
+ return result;
101
+ }
102
+
103
+ /** `[程序] 名字 · 触发词 / …`,与 recall-core 硬门块的行格式保持一致。 */
104
+ function renderProcedureLine(procedures) {
105
+ const rows = (Array.isArray(procedures) ? procedures : []).map((item) => {
106
+ const name = collapseLine(item && item.name);
107
+ if (name === '') return '';
108
+ const trigger = Array.isArray(item && item.trigger)
109
+ ? item.trigger.map((value) => collapseLine(value)).filter(Boolean).join(' / ')
110
+ : collapseLine(item && item.trigger);
111
+ return trigger === '' ? `[程序] ${name}` : `[程序] ${name} · ${trigger}`;
112
+ }).filter(Boolean);
113
+ return rows.join(' / ');
114
+ }
115
+
60
116
  // ── 基础小工具 ────────────────────────────────────────────────────────────────
61
117
 
62
118
  /** 统一换行、去掉零宽 BOM、压缩连续空白;标题/位置等单行字段用。 */
@@ -209,7 +265,7 @@ function pushSegment(state, raw, perSegmentMax) {
209
265
  * 通用块拼装:第一行固定、人格头/位置/读卡摘要/卡正文按优先级吃预算。
210
266
  * 预算不足时从后往前被裁;始终保证返回 text.length ≤ cap。
211
267
  */
212
- function composeBlock({ firstLine, cap, personaHeader, positionLine, cards, replayLine, mode }) {
268
+ function composeBlock({ firstLine, cap, personaHeader, positionLine, taskStateLine, cards, procedures, replayLine, mode }) {
213
269
  const limit = Math.max(1, Math.floor(Number(cap) || 1));
214
270
  const state = { text: hardTrim(firstLine, limit), cap: limit };
215
271
  if (replayLine) pushLine(state, replayLine);
@@ -217,6 +273,8 @@ function composeBlock({ firstLine, cap, personaHeader, positionLine, cards, repl
217
273
  pushLine(state, `你是谁:${collapseLine(personaHeader)}`);
218
274
  }
219
275
  if (positionLine) pushLine(state, positionLine);
276
+ // W2.4:跨会话/压缩后的任务状态接续行,紧跟位置行(不抢首行安全声明,不挤掉读卡正文)。
277
+ if (taskStateLine) pushSegment(state, taskStateLine, TASK_STATE_INJECT_MAX_CHARS);
220
278
  const titles = (Array.isArray(cards) ? cards : [])
221
279
  .map((card) => collapseLine(card && card.title))
222
280
  .filter(Boolean)
@@ -224,6 +282,8 @@ function composeBlock({ firstLine, cap, personaHeader, positionLine, cards, repl
224
282
  if (titles.length > 0) {
225
283
  pushLine(state, `已读卡:${titles.join(' / ')}`);
226
284
  }
285
+ const procedureLine = renderProcedureLine(procedures);
286
+ if (procedureLine !== '') pushSegment(state, procedureLine, PROCEDURE_INJECT_MAX_CHARS);
227
287
  for (const card of Array.isArray(cards) ? cards : []) {
228
288
  const body = collapse(card && card.text);
229
289
  if (body === '') continue;
@@ -242,12 +302,14 @@ export function composeVolatileBlock({
242
302
  cap = STEP1_MAX_CHARS,
243
303
  personaHeader = '',
244
304
  positionLine = '',
305
+ taskStateLine = null,
245
306
  cards = [],
246
307
  replayReason = null,
247
308
  step = 1,
248
309
  turn = 0,
249
310
  sessionId = 'unknown',
250
311
  mode = 'volatile',
312
+ procedures = [],
251
313
  } = {}) {
252
314
  const effectiveCap = Math.max(1, Math.floor(Number(cap) || STEP1_MAX_CHARS));
253
315
  const block = composeBlock({
@@ -255,7 +317,9 @@ export function composeVolatileBlock({
255
317
  cap: effectiveCap,
256
318
  personaHeader,
257
319
  positionLine: positionLine || buildPositionLine({ turn, step, sessionId, mode }),
320
+ taskStateLine,
258
321
  cards,
322
+ procedures,
259
323
  replayLine: replayReason ? buildReplayLine(replayReason, mode) : null,
260
324
  mode,
261
325
  });
@@ -275,6 +339,7 @@ export function composeFallbackBlock({
275
339
  mode = 'degraded',
276
340
  personaHeader = '',
277
341
  positionLine = '',
342
+ taskStateLine = null,
278
343
  cards = [],
279
344
  replayReason = null,
280
345
  step = 1,
@@ -287,6 +352,7 @@ export function composeFallbackBlock({
287
352
  cap: effectiveCap,
288
353
  personaHeader,
289
354
  positionLine: positionLine || buildPositionLine({ turn, step, sessionId, mode }),
355
+ taskStateLine,
290
356
  cards,
291
357
  replayLine: replayReason ? buildReplayLine(replayReason, mode) : null,
292
358
  mode,
@@ -649,8 +715,20 @@ export function createContinuityVolatile(options = {}) {
649
715
  chars: ctx.chars,
650
716
  volatileChars: ctx.volatileChars,
651
717
  cards: ctx.cards,
718
+ procedures: ctx.procedures,
652
719
  drop: ctx.drop,
653
720
  fail: ctx.fail,
721
+ // W2.4 任务状态:captured/noop/fail + 是否 rehydrate + 捕获摘要(不含用户原文,隐私边界 F8)。
722
+ taskState: ctx.taskState
723
+ ? {
724
+ mode: ctx.taskState.mode,
725
+ reason: ctx.taskState.reason,
726
+ rehydrate: ctx.taskState.rehydrate === true,
727
+ injected: ctx.taskState.injected === true,
728
+ chars: toInt(ctx.taskState.chars, 0),
729
+ capture: ctx.taskState.capture,
730
+ }
731
+ : null,
654
732
  ms: Math.max(0, Math.round(clock() - startedAt)),
655
733
  };
656
734
  emit(record);
@@ -686,6 +764,99 @@ export function createContinuityVolatile(options = {}) {
686
764
  return result;
687
765
  }
688
766
 
767
+ /**
768
+ * W2.4 任务状态(task-state):先读上一次落盘的机器可读任务状态(跨会话/压缩后的接续来源),
769
+ * 再捕获本步状态落盘(幂等)。只在新会话首步 / 进程重启后的首步 rehydrate,避免与
770
+ * 2.0 工作帧(同会话每轮 ≤300 字)重复注入。任何异常都不外抛,只记 fail。
771
+ */
772
+ function taskStateForStep({ decision, sessionId, turn, step, subagent, tracking, userText }) {
773
+ try {
774
+ if (subagent) {
775
+ return { mode: 'off', reason: 'E_TASK_STATE_SUBAGENT_SKIP', rehydrate: false, injected: false, chars: 0, text: '', capture: null };
776
+ }
777
+ if (typeof config.memoryRoot !== 'string' || config.memoryRoot.trim() === '') {
778
+ return { mode: 'off', reason: 'E_NO_MEMORY_ROOT', rehydrate: false, injected: false, chars: 0, text: '', capture: null };
779
+ }
780
+ // 任务状态时间戳必须用真实时间:continuity 的 clock()(nowMillis(config.now)) 在未注入时钟时
781
+ // 会返回 0(Number(null) 语义),若直接透传,状态 updatedAt 会写成 1970 且「过期」永远判新鲜。
782
+ const taskClock = () => {
783
+ try {
784
+ const value = clock();
785
+ if (Number.isFinite(value) && value > 0) return value;
786
+ } catch {
787
+ /* fall through */
788
+ }
789
+ return Date.now();
790
+ };
791
+ const store = createTaskStateStore({ memoryRoot: config.memoryRoot, now: taskClock });
792
+ const messages = Array.isArray(decision.messages) ? decision.messages : [];
793
+ const previous = store.read();
794
+ let rehydrate = { inject: false, reason: null };
795
+ if (step === 1) {
796
+ if (!previous.ok || !previous.exists) {
797
+ rehydrate = { inject: false, reason: previous.code || 'E_TASK_STATE_ABSENT' };
798
+ } else if (!previous.fresh) {
799
+ rehydrate = { inject: false, reason: 'E_TASK_STATE_STALE' };
800
+ } else {
801
+ const related = isTaskStateRelated(previous.state, userText);
802
+ // 新会话(sessionId 变了)或本进程首次观测到该会话(宿重启 / truncate 后重开)才接续。
803
+ const restarted = previous.state.sessionId !== sessionId || tracking.firstObservation === true;
804
+ if (!related.related) rehydrate = { inject: false, reason: 'E_TASK_STATE_UNRELATED', related };
805
+ else if (!restarted) rehydrate = { inject: false, reason: 'E_TASK_STATE_SAME_SESSION', related };
806
+ else rehydrate = { inject: true, reason: related.reason, related };
807
+ }
808
+ } else {
809
+ rehydrate = { inject: false, reason: 'E_TASK_STATE_STEP_GT_1' };
810
+ }
811
+
812
+ const captured = store.capture({
813
+ sessionId,
814
+ turn,
815
+ step,
816
+ messages,
817
+ previous: previous.ok ? previous.state : null,
818
+ // 同一会话继续 or 新会话仍在同一话题 → 继承触达文件;跨到新话题 → 只留本轮文件。
819
+ keepAnchors:
820
+ (previous.ok && previous.exists && previous.state.sessionId === sessionId) ||
821
+ (rehydrate.related ? rehydrate.related.related === true : false),
822
+ });
823
+ let text = '';
824
+ if (rehydrate.inject) {
825
+ // 用捕获后的最新状态渲染(doing/nextStep/anchor 已合并本轮信息)。
826
+ const rendered = store.renderLine({ allowStale: true });
827
+ text = rendered.ok ? rendered.text : '';
828
+ if (text === '') rehydrate = { ...rehydrate, inject: false, reason: rendered.code || 'E_TASK_STATE_EMPTY' };
829
+ }
830
+ const fields = captured.ok ? captured.fields : null;
831
+ return {
832
+ mode: captured.ok ? (captured.written ? 'captured' : 'noop') : 'fail',
833
+ reason: rehydrate.inject ? rehydrate.reason : (captured.ok ? rehydrate.reason : captured.code),
834
+ rehydrate: rehydrate.inject === true,
835
+ injected: rehydrate.inject === true && text !== '',
836
+ chars: text.length,
837
+ text,
838
+ capture: fields
839
+ ? {
840
+ doing: fields.doing ?? '',
841
+ waitingFor: fields.waitingFor ?? null,
842
+ nextStep: fields.nextStep ?? '',
843
+ anchorFiles: Array.isArray(fields.anchorFiles) ? fields.anchorFiles.slice(0, 5) : [],
844
+ }
845
+ : null,
846
+ };
847
+ } catch (error) {
848
+ return {
849
+ mode: 'fail',
850
+ reason: errorCode(error, 'E_TASK_STATE_INTERNAL'),
851
+ rehydrate: false,
852
+ injected: false,
853
+ chars: 0,
854
+ text: '',
855
+ capture: null,
856
+ };
857
+ }
858
+ }
859
+
689
860
  async function fallbackPath(payload, decision, ctx, opts) {
690
861
  const step1Only = opts.step1Only !== false;
691
862
  const baseMode = opts.mode || 'degraded';
@@ -738,6 +909,7 @@ export function createContinuityVolatile(options = {}) {
738
909
  mode: baseMode,
739
910
  personaHeader: resolvePersona(config, payload),
740
911
  positionLine: buildPositionLine({ turn: ctx.turn, step: ctx.step, sessionId: ctx.sessionId, mode: baseMode }),
912
+ taskStateLine: ctx.taskState && ctx.taskState.injected ? ctx.taskState.text : null,
741
913
  cards,
742
914
  replayReason: ctx.replay,
743
915
  step: ctx.step,
@@ -817,6 +989,7 @@ export function createContinuityVolatile(options = {}) {
817
989
  }
818
990
 
819
991
  let text;
992
+ const procedures = ctx.subagent ? [] : resolveActionProcedures(config.memoryRoot, ctx.userText || '');
820
993
  try {
821
994
  text = ctx.subagent
822
995
  ? composeSubagentBlock({
@@ -828,7 +1001,9 @@ export function createContinuityVolatile(options = {}) {
828
1001
  cap,
829
1002
  personaHeader: resolvePersona(config, payload),
830
1003
  positionLine: buildPositionLine({ turn: ctx.turn, step: ctx.step, sessionId: ctx.sessionId, mode: 'volatile' }),
1004
+ taskStateLine: ctx.taskState && ctx.taskState.injected ? ctx.taskState.text : null,
831
1005
  cards,
1006
+ procedures,
832
1007
  replayReason: ctx.replay,
833
1008
  step: ctx.step,
834
1009
  turn: ctx.turn,
@@ -883,6 +1058,7 @@ export function createContinuityVolatile(options = {}) {
883
1058
  ctx.chars = text.length;
884
1059
  ctx.volatileChars = text.length;
885
1060
  ctx.cards = cards.length;
1061
+ ctx.procedures = procedures.length;
886
1062
  ctx.drop = dropped;
887
1063
  ctx.fail = 0;
888
1064
  ctx.injected = true;
@@ -917,8 +1093,11 @@ export function createContinuityVolatile(options = {}) {
917
1093
  chars: 0,
918
1094
  volatileChars: 0,
919
1095
  cards: 0,
1096
+ procedures: 0,
1097
+ userText: '',
920
1098
  drop: 0,
921
1099
  fail: 0,
1100
+ taskState: null,
922
1101
  };
923
1102
  try {
924
1103
  if (!decision || typeof decision !== 'object') {
@@ -934,6 +1113,9 @@ export function createContinuityVolatile(options = {}) {
934
1113
  return attach(decision, ctx, startedAt);
935
1114
  }
936
1115
 
1116
+ // 动作词匹配只取当前步最后一条真实用户消息(与 recall/index.js 的 hardgate 同源口径)。
1117
+ ctx.userText = subagent ? '' : lastUserTextFromMessages(decision.messages);
1118
+
937
1119
  const tracking = trackSession(sessionId);
938
1120
  const replay = replayReasonFor({
939
1121
  turn,
@@ -945,6 +1127,18 @@ export function createContinuityVolatile(options = {}) {
945
1127
  });
946
1128
  ctx.replay = replay;
947
1129
 
1130
+ // W2.4:任务状态机——捕获本步「在做什么/等什么/下一步」,并在新会话首步按需 rehydrate。
1131
+ // 与 volatile/fallback 选择无关:即使宿主无哨兵走回落块,任务状态也照样捕获与接续。
1132
+ ctx.taskState = taskStateForStep({
1133
+ decision,
1134
+ sessionId,
1135
+ turn,
1136
+ step,
1137
+ subagent,
1138
+ tracking,
1139
+ userText: ctx.userText,
1140
+ });
1141
+
948
1142
  const hostVolatile = probeHost(typeof globalThis !== 'undefined' ? globalThis : undefined);
949
1143
  if (hostVolatile) {
950
1144
  return await volatilePath(payload, decision, ctx);
@@ -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,