@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
@@ -1,7 +1,8 @@
1
- // 2.2.0 动作前回忆门(lane-C,默认 enforce)。
1
+ // 2.3.0 动作前回忆门(lane gate-feedback,默认 enforce)。
2
2
  //
3
3
  // 只在宿主 tools 服务的 guard 层工作:同步判定「这一次工具调用是不是高危动作命令」,
4
- // 是则要求 gate-log 里存在同会话的动作类 procedure 卡回执;没有回执就返回拒绝串。
4
+ // 是则要求 gate-log 里存在同会话、同动作类别(actionKind)、且在时间窗内的动作回执;
5
+ // 没有回执就返回拒绝串。
5
6
  // 三条硬约束:
6
7
  // 1. guard 必须是同步的(宿主 ToolGuard 类型不允许 Promise),且绝不能抛异常——
7
8
  // 宿主 checkGuards 没有 try/catch,抛出去会把这一次工具调用变成工具错误。
@@ -10,7 +11,16 @@
10
11
  // 3. 宿主没有 ctx.tools.guard() 时不注册、不阻断、不伪造阻断;只有真实宿主
11
12
  // (ctx.get 存在)才 warn 并往 gate-log 写一条 skip 留痕。
12
13
  //
13
- // 配置走 raw passthrough(settings schema 节点锁不变):{ enabled, mode },
14
+ // 2.3.0 修正(对照 RT-SURFACE-FEATURE P1-1/P1-2/P1-3):
15
+ // - 回执兜底:动作类 query 的 memory_recall 成功调用即写回执(不要求命中 procedure 卡,
16
+ // 见 src/tools.js 的 writeActionGateReceipt)。
17
+ // - 「回滚」按命令起始动词 / cmdlet 组合判定(isRollbackCommand),不再对整条命令文本
18
+ // 做 /回滚/i:echo / Select-String / Set-Content / git log --grep 里的「回滚」文字不拦。
19
+ // - 回执记 actionKind(逗号分隔的多类),匹配要求同 kind;无 kind 信息的 ok 行不再算回执。
20
+ // - 回执时间窗 60–120 秒(常数 RECEIPT_WINDOW_MS=90s,可按配置收窄/放宽,越界夹紧)。
21
+ // - fail / warn 行补 sessionId / sessionSource(resolution 见 resolveExecutionSession)。
22
+ //
23
+ // 配置走 raw passthrough(settings schema 节点锁不变):{ enabled, mode, windowMs },
14
24
  // mode = enforce(默认,拒绝)/ shadow(只记不拦)/ off(不注册)。
15
25
  // 归一化在 normalizeActionGateConfig,接线见 src/features.js。
16
26
 
@@ -18,8 +28,8 @@ import { closeSync, openSync, readSync, statSync } from 'node:fs';
18
28
 
19
29
  import { appendGateLog, gateLogPaths } from '../recall/gate-log.mjs';
20
30
 
21
- /** 默认配置:默认开启、默认强制。 */
22
- export const ACTION_GATE_DEFAULTS = Object.freeze({ enabled: true, mode: 'enforce' });
31
+ /** 默认配置:默认开启、默认强制、回执窗 90 秒(60–120 秒之间)。 */
32
+ export const ACTION_GATE_DEFAULTS = Object.freeze({ enabled: true, mode: 'enforce', windowMs: 90 * 1000 });
23
33
 
24
34
  const ACTION_GATE_MODES = Object.freeze(['enforce', 'shadow']);
25
35
 
@@ -34,9 +44,91 @@ export const SHELL_TOOL_NAMES = Object.freeze(['pwsh', 'bash', 'bash_local']);
34
44
 
35
45
  const PLUGIN_MANAGER_TOOL = 'plugin_manager';
36
46
 
37
- /** 回执尾部读取上限(字节)与无会话回执的时间窗(毫秒)。 */
47
+ /** 回执尾部读取上限(字节)与回执时间窗(毫秒,2.3.0 冻结 60–120 秒)。 */
38
48
  const RECEIPT_TAIL_BYTES = 64 * 1024;
39
- const RECEIPT_WINDOW_MS = 15 * 60 * 1000;
49
+ export const RECEIPT_WINDOW_MS = 90 * 1000;
50
+ export const RECEIPT_WINDOW_MIN_MS = 60 * 1000;
51
+ export const RECEIPT_WINDOW_MAX_MS = 120 * 1000;
52
+
53
+ /* ------------------------------------------------------------------ *
54
+ * 「回滚」判定:只认命令起始动词 / cmdlet 组合。
55
+ *
56
+ * 旧口径(2.2.0)对整条命令文本 /rollback\b|回滚/i,会把
57
+ * Get-Content CHANGELOG.md | Select-String "回滚"
58
+ * Set-Content notes.txt "不要回滚"
59
+ * echo 回滚
60
+ * 这类只是在参数/字符串里出现「回滚」的只读命令全拦掉(RT P1-2)。
61
+ * 新口径按 shell 分段(; && || | 换行)看每段起始 token:
62
+ * - 起始就是 rollback / rollback.ps1 / Rollback-Plugin 之类;
63
+ * - 起始是解释器/包管理器/版本控制工具(node、npm run、python、pwsh -File、git 等),
64
+ * 紧跟的第一个非选项参数是回滚脚本名或 revert/rollback 动词。
65
+ * 字符串里出现「回滚」但起始动词不是回滚命令的一律不算。
66
+ * ------------------------------------------------------------------ */
67
+
68
+ const RUNNER_TOOLS = new Set([
69
+ 'node', 'nodejs', 'npx', 'tsx', 'deno', 'bun',
70
+ 'python', 'python3', 'py',
71
+ 'pwsh', 'powershell', 'bash', 'sh', 'zsh', 'cmd',
72
+ 'npm', 'pnpm', 'yarn',
73
+ 'git',
74
+ ]);
75
+
76
+ const SHELL_SEQUENCE = /\s*(?:\|\||&&|;|\r?\n|\|)\s*/;
77
+
78
+ function unquoteToken(token) {
79
+ return String(token ?? '').replace(/^['"]+/, '').replace(/['"]+$/, '');
80
+ }
81
+
82
+ function basenameOf(token) {
83
+ const cleaned = unquoteToken(token).replace(/^[&.]\s*/, '');
84
+ const parts = cleaned.split(/[\\/]/).filter((part) => part !== '');
85
+ return parts.length > 0 ? parts[parts.length - 1] : '';
86
+ }
87
+
88
+ /** token 本身是不是「回滚」命令/脚本/cmdlet 的名字(不是任意文本里出现回滚)。 */
89
+ function isRollbackName(token) {
90
+ const raw = unquoteToken(token).trim();
91
+ if (raw === '') return false;
92
+ const base = basenameOf(raw);
93
+ const lower = base.toLowerCase();
94
+ if (lower === 'rollback' || lower === 'revert' || lower === 'undo' || lower === '回滚') return true;
95
+ // 脚本名:rollback.ps1 / rollback.mjs / rollback_v2.ps1 / rollback-report.sh 等(必须带脚本扩展名)
96
+ const SCRIPT_EXT = /\.(?:ps1|psm1|cmd|bat|exe|mjs|cjs|js|ts|sh|zsh|py|rb|pl)$/;
97
+ if (SCRIPT_EXT.test(lower) && /^(?:rollback|revert|undo)[-_.][\w.-]*$/.test(lower)) return true;
98
+ if (SCRIPT_EXT.test(lower) && /^(?:rollback|revert|undo)[\w.-]*$/.test(lower)) return true;
99
+ // PowerShell 自定义 cmdlet 组合:Rollback-Plugin / Revert-Migration / Undo-Deploy
100
+ return /^(?:Rollback|Revert|Undo)-[A-Za-z][\w-]*$/.test(raw);
101
+ }
102
+
103
+ function segmentIsRollback(segment) {
104
+ const raw = segment.trim();
105
+ if (raw === '') return false;
106
+ const tokens = raw.split(/\s+/);
107
+ let index = 0;
108
+ // & .\rollback.ps1 / . .\rollback.ps1 —— 跳过调用运算符
109
+ while (index < tokens.length && (tokens[index] === '&' || tokens[index] === '.')) index += 1;
110
+ if (index >= tokens.length) return false;
111
+ const head = tokens[index];
112
+ if (isRollbackName(head)) return true;
113
+ const headTool = basenameOf(head).toLowerCase();
114
+ if (headTool === 'cmd.exe') return segmentIsRollback(['cmd', ...tokens.slice(index + 1)].join(' '));
115
+ if (!RUNNER_TOOLS.has(headTool)) return false;
116
+ // 只看头的下游第一个非选项 token:-File / -Command / -c / -- / run 等跳过后再看。
117
+ for (let cursor = index + 1; cursor < tokens.length; cursor += 1) {
118
+ const token = unquoteToken(tokens[cursor]);
119
+ if (token === '') continue;
120
+ if (token === 'run' || token === '--') continue;
121
+ if (token.startsWith('-') || token.startsWith('/')) continue;
122
+ return isRollbackName(token);
123
+ }
124
+ return false;
125
+ }
126
+
127
+ /** 整条命令是否属于「回滚」类(只认命令起始动词/cmdlet 组合)。 */
128
+ export function isRollbackCommand(text) {
129
+ if (typeof text !== 'string' || text.trim() === '') return false;
130
+ return text.split(SHELL_SEQUENCE).some((segment) => segmentIsRollback(segment));
131
+ }
40
132
 
41
133
  // 窄口径高危规则:只覆盖「发布 / 插件装卸 / 递归删除 / 回滚 / 硬重置」五类,
42
134
  // 常规开发命令(npm install、npm test、git status 等)一律不命中。
@@ -63,14 +155,44 @@ const SHELL_RULES = Object.freeze([
63
155
  },
64
156
  { kind: 'delete', label: '递归删除', keywords: ['删除', 'remove'], re: /\b(?:rd|rmdir)\s+\/s\b/i },
65
157
  { kind: 'delete', label: '递归删除', keywords: ['删除', 'remove'], re: /\b(?:del|erase)\s+\/[a-z]*s[a-z]*\b/i },
66
- { kind: 'rollback', label: '回滚', keywords: ['回滚', 'rollback'], re: /\brollback\b|回滚/i },
158
+ { kind: 'rollback', label: '回滚', keywords: ['回滚', 'rollback'], test: isRollbackCommand },
67
159
  { kind: 'reset', label: '硬重置', keywords: ['回滚', 'reset'], re: /\bgit\s+reset\s+--hard\b/i },
68
160
  ]);
69
161
 
162
+ /** 关键词 → 可接受的动作 kind 集合(回执按 kind 匹配,见 rowIsActionReceipt)。 */
163
+ const KEYWORD_KINDS = (() => {
164
+ const map = new Map();
165
+ for (const rule of SHELL_RULES) {
166
+ for (const keyword of rule.keywords) {
167
+ const key = keyword.toLowerCase();
168
+ if (!map.has(key)) map.set(key, new Set());
169
+ map.get(key).add(rule.kind);
170
+ }
171
+ }
172
+ return map;
173
+ })();
174
+
175
+ /**
176
+ * 文本(query / procedure 名 / 路径)里出现的动作关键词能接受哪些 kind。
177
+ * 供 memory_recall 动作回执写 actionKind,以及 lane-B 程序卡回执的反推。
178
+ * 只做确定性字面匹配,不做分词/相似度。
179
+ */
180
+ export function actionKindsForText(text) {
181
+ const lower = String(text ?? '').toLowerCase();
182
+ const kinds = new Set();
183
+ for (const [keyword, keywordKinds] of KEYWORD_KINDS) {
184
+ if (lower.includes(keyword)) {
185
+ for (const kind of keywordKinds) kinds.add(kind);
186
+ }
187
+ }
188
+ return [...kinds].sort();
189
+ }
190
+
70
191
  /**
71
192
  * 归一化 actionGate 配置。kill switch:DSH_LONGLIVE_DISABLE_ACTION_GATE=1 / true。
72
193
  * - 显式 enabled:false 关闭;mode:'off' 也关闭(不注册)。
73
194
  * - mode 非法值回落 'enforce'(默认强制)。
195
+ * - windowMs 夹在 60–120 秒(2.3.0 冻结),非法值回落 90 秒。
74
196
  */
75
197
  export function normalizeActionGateConfig(raw, env = process.env) {
76
198
  const source = raw && typeof raw === 'object' ? raw : {};
@@ -78,7 +200,11 @@ export function normalizeActionGateConfig(raw, env = process.env) {
78
200
  const requestedOff = source.enabled === false || source.mode === 'off';
79
201
  if (killed || requestedOff) return { enabled: false, mode: 'off' };
80
202
  const mode = ACTION_GATE_MODES.includes(source.mode) ? source.mode : ACTION_GATE_DEFAULTS.mode;
81
- return { enabled: true, mode };
203
+ const requestedWindow = Number(source.windowMs);
204
+ const windowMs = Number.isFinite(requestedWindow)
205
+ ? Math.min(RECEIPT_WINDOW_MAX_MS, Math.max(RECEIPT_WINDOW_MIN_MS, Math.round(requestedWindow)))
206
+ : ACTION_GATE_DEFAULTS.windowMs;
207
+ return { enabled: true, mode, windowMs };
82
208
  }
83
209
 
84
210
  /** 从工具参数里取出命令文本(只认 command / cmd 两个常见键)。 */
@@ -110,27 +236,46 @@ export function classifyActionCall(toolName, args) {
110
236
  const text = commandTextOf(args);
111
237
  if (text === '') return { action: false };
112
238
  for (const rule of SHELL_RULES) {
113
- if (rule.re.test(text)) {
239
+ const hit = typeof rule.test === 'function' ? rule.test(text) : rule.re.test(text);
240
+ if (hit) {
114
241
  return { action: true, kind: rule.kind, label: rule.label, keywords: rule.keywords.slice() };
115
242
  }
116
243
  }
117
244
  return { action: false };
118
245
  }
119
246
 
120
- /** 无回执时的拒绝串:给出下一步(先 memory_recall 取 procedure 卡)。 */
121
- export function buildRefusal(verdict = {}) {
247
+ /**
248
+ * 无回执时的拒绝串:给出显式放行路径(动作类 recall 回执 / 用户二次同意后的 shadow 宽容)。
249
+ * 文案供模型直接执行,不执行任何动作。
250
+ */
251
+ export function buildRefusal(verdict = {}, { windowMs = RECEIPT_WINDOW_MS } = {}) {
122
252
  const label = typeof verdict.label === 'string' && verdict.label !== '' ? verdict.label : '高危';
123
253
  const keyword = Array.isArray(verdict.keywords) && verdict.keywords.length > 0 ? verdict.keywords[0] : '回滚';
124
- return `动作门拦截:该命令属于${label}类高危动作,执行前必须先回忆。下一步:先调用 memory_recall("${keyword}") `
125
- + '取 procedure 卡(含步骤与失败模式),按卡执行后再重试本动作;若确认没有对应 procedure 卡,先向用户说明理由。';
254
+ const windowSec = Math.max(1, Math.round((Number.isFinite(Number(windowMs)) ? Number(windowMs) : RECEIPT_WINDOW_MS) / 1000));
255
+ return `动作门拦截:该命令属于${label}类高危动作,执行前必须先回忆。下一步(显式放行路径,二选一):`
256
+ + `① 主路径:调用 memory_recall("${keyword}") 做一次动作类查询——成功返回即写回执,不要求命中 procedure 卡——`
257
+ + `并在 ${windowSec} 秒内重试本动作;若确认没有对应 procedure 卡,先向用户说明理由。`
258
+ + '② 用户已明确二次同意:在回复里向用户复述该动作与影响并取得明确同意后,把配置 actionGate.mode 设为 shadow'
259
+ + '(或临时设置 DSH_LONGLIVE_DISABLE_ACTION_GATE=1)后重试(需重启宿主生效)。';
126
260
  }
127
261
 
128
- /** 解析 execution 里的会话 id:宿主当前没有 sessionId 字段,用 agent.id(SessionId)。 */
129
- export function resolveExecutionSessionId(execution) {
130
- if (!execution || typeof execution !== 'object') return null;
131
- if (typeof execution.sessionId === 'string' && execution.sessionId !== '') return execution.sessionId;
262
+ /**
263
+ * 解析 execution 里的会话:返回 { sessionId, source }。
264
+ * 宿主当前没有 sessionId 字段,用 agent.id(SessionId);source 用于 fail 行留痕。
265
+ */
266
+ export function resolveExecutionSession(execution) {
267
+ if (!execution || typeof execution !== 'object') return { sessionId: null, source: 'none' };
268
+ if (typeof execution.sessionId === 'string' && execution.sessionId !== '') {
269
+ return { sessionId: execution.sessionId, source: 'execution.sessionId' };
270
+ }
132
271
  const agentId = execution.agent && typeof execution.agent === 'object' ? execution.agent.id : null;
133
- return typeof agentId === 'string' && agentId !== '' ? agentId : null;
272
+ if (typeof agentId === 'string' && agentId !== '') return { sessionId: agentId, source: 'execution.agent.id' };
273
+ return { sessionId: null, source: 'none' };
274
+ }
275
+
276
+ /** 兼容旧导出:只返回会话 id。 */
277
+ export function resolveExecutionSessionId(execution) {
278
+ return resolveExecutionSession(execution).sessionId;
134
279
  }
135
280
 
136
281
  function parseRowTime(value) {
@@ -157,24 +302,41 @@ function evidenceValue(evidence, key) {
157
302
  return found.join(' ');
158
303
  }
159
304
 
160
- /** 单行判定:ok 行的 gate=action(显式回执)或 evidence 里 procedureNames/procedurePaths 命中关键词。 */
161
- function rowIsActionReceipt(row, { sessionId, now, windowMs }) {
305
+ /** 一行 ok 记录能接受的 actionKind 集合:显式 actionKind/actionKinds + 程序卡文本反推。 */
306
+ function receiptKinds(row) {
307
+ const evidence = Array.isArray(row.evidence) ? row.evidence : [];
308
+ const kinds = new Set();
309
+ const explicit = `${evidenceValue(evidence, 'actionKind')} ${evidenceValue(evidence, 'actionKinds')}`.trim();
310
+ for (const item of explicit.split(/[|,\s]+/)) {
311
+ const kind = item.trim().toLowerCase();
312
+ if (kind !== '') kinds.add(kind);
313
+ }
314
+ const procedureText = `${evidenceValue(evidence, 'procedureNames')} ${evidenceValue(evidence, 'procedurePaths')}`;
315
+ for (const kind of actionKindsForText(procedureText)) kinds.add(kind);
316
+ return kinds;
317
+ }
318
+
319
+ /**
320
+ * 单行判定:ok 行 + 同会话 + 时间窗内 + actionKind 匹配。
321
+ * 2.3.0(P1-3):不再把「任意 gate=action 的 ok 行」当回执——必须能给出该动作的 kind;
322
+ * 无会话调用也不接受别会话写的回执。
323
+ */
324
+ function rowIsActionReceipt(row, { sessionId, now, windowMs, actionKind = null }) {
162
325
  if (!row || typeof row !== 'object' || row.decision !== 'ok') return false;
163
326
  const rowSessionId = typeof row.sessionId === 'string' && row.sessionId !== '' ? row.sessionId : null;
164
327
  if (sessionId !== null) {
165
328
  if (rowSessionId !== sessionId) return false;
166
- } else {
167
- const at = parseRowTime(row.at);
168
- if (!Number.isFinite(at)) return false;
169
- const delta = now - at;
170
- if (delta > windowMs || delta < -windowMs) return false;
329
+ } else if (rowSessionId !== null) {
330
+ return false;
171
331
  }
172
- // lane-C 在 memory_recall 工具包装里写的显式动作回执行:本身就是回执。
173
- if (row.gate === 'action') return true;
174
- const evidence = Array.isArray(row.evidence) ? row.evidence : [];
175
- const haystack = `${evidenceValue(evidence, 'procedureNames')} ${evidenceValue(evidence, 'procedurePaths')}`.toLowerCase();
176
- if (haystack.trim() === '') return false;
177
- return ACTION_KEYWORDS.some((keyword) => haystack.includes(keyword.toLowerCase()));
332
+ const at = parseRowTime(row.at);
333
+ if (!Number.isFinite(at)) return false;
334
+ const delta = now - at;
335
+ if (delta > windowMs || delta < -windowMs) return false;
336
+ const kinds = receiptKinds(row);
337
+ if (kinds.size === 0) return false;
338
+ if (actionKind !== null && !kinds.has(String(actionKind).toLowerCase())) return false;
339
+ return true;
178
340
  }
179
341
 
180
342
  // gate-log 尾部行缓存:只按 logFile 的 mtime+size 失效,避免每个 shell 调用都读盘。
@@ -233,11 +395,22 @@ function readTailRows(memoryRoot) {
233
395
  }
234
396
 
235
397
  /**
236
- * 查回执:同会话(sessionId 有效时)或最近 15 分钟(无会话时)的 ok 行。
398
+ * 查回执:同会话(sessionId 有效时)或同为空会话、时间窗内(60–120 秒)、kind 匹配的 ok 行。
237
399
  * 读失败按「无回执」返回 false,并只通过传入的 warn 报告一次(由调用方去重)。
238
400
  */
239
- export function hasActionReceipt({ memoryRoot, sessionId = null, now = Date.now(), windowMs = RECEIPT_WINDOW_MS, warn = null } = {}) {
401
+ export function hasActionReceipt({
402
+ memoryRoot,
403
+ sessionId = null,
404
+ now = Date.now(),
405
+ windowMs = RECEIPT_WINDOW_MS,
406
+ actionKind = null,
407
+ warn = null,
408
+ } = {}) {
240
409
  if (typeof memoryRoot !== 'string' || memoryRoot === '') return false;
410
+ const requested = Number(windowMs);
411
+ const boundedWindow = Number.isFinite(requested)
412
+ ? Math.min(RECEIPT_WINDOW_MAX_MS, Math.max(RECEIPT_WINDOW_MIN_MS, requested))
413
+ : RECEIPT_WINDOW_MS;
241
414
  let rows;
242
415
  try {
243
416
  rows = readTailRows(memoryRoot);
@@ -248,7 +421,7 @@ export function hasActionReceipt({ memoryRoot, sessionId = null, now = Date.now(
248
421
  return false;
249
422
  }
250
423
  for (let index = rows.length - 1; index >= 0; index -= 1) {
251
- if (rowIsActionReceipt(rows[index], { sessionId, now, windowMs })) return true;
424
+ if (rowIsActionReceipt(rows[index], { sessionId, now, windowMs: boundedWindow, actionKind })) return true;
252
425
  }
253
426
  return false;
254
427
  }
@@ -280,12 +453,13 @@ function looksLikeHost(ctx) {
280
453
  /**
281
454
  * 注册动作门(同步)。
282
455
  * options: { config, memoryRoot, ownToolNames, warn|logger, env, now }
283
- * 返回 { enabled, mode, registered, reason?, guard? }。
456
+ * 返回 { enabled, mode, windowMs, registered, reason?, guard? }。
284
457
  */
285
458
  export function registerActionGate(ctx, options = {}) {
286
459
  const normalized = normalizeActionGateConfig(options.config, options.env ?? process.env);
287
460
  if (!normalized.enabled) return { enabled: false, mode: 'off', registered: false, reason: 'off' };
288
461
  const mode = normalized.mode;
462
+ const windowMs = normalized.windowMs ?? RECEIPT_WINDOW_MS;
289
463
  const warn = loggerOf(options);
290
464
  const memoryRoot = typeof options.memoryRoot === 'string' && options.memoryRoot !== '' ? options.memoryRoot : null;
291
465
  const ownToolNames = options.ownToolNames instanceof Set
@@ -305,13 +479,13 @@ export function registerActionGate(ctx, options = {}) {
305
479
  gate: 'action',
306
480
  decision: 'skip',
307
481
  reason: 'host-guard-absent',
308
- evidence: [`mode=${mode}`],
482
+ evidence: [`mode=${mode}`, 'sessionId=none', 'sessionSource=host-guard-absent'],
309
483
  }, null);
310
484
  }
311
485
  }
312
- return { enabled: true, mode, registered: false, reason: 'no-host-guard' };
486
+ return { enabled: true, mode, windowMs, registered: false, reason: 'no-host-guard' };
313
487
  }
314
- if (!memoryRoot) return { enabled: true, mode, registered: false, reason: 'no-memory-root' };
488
+ if (!memoryRoot) return { enabled: true, mode, windowMs, registered: false, reason: 'no-memory-root' };
315
489
 
316
490
  let warned = false;
317
491
  const warnOnce = (message) => {
@@ -328,18 +502,33 @@ export function registerActionGate(ctx, options = {}) {
328
502
  if (ownToolNames && ownToolNames.has(name)) return undefined;
329
503
  const verdict = classifyActionCall(name, execution?.arguments);
330
504
  if (!verdict.action) return undefined;
331
- const sessionId = resolveExecutionSessionId(execution);
332
- if (hasActionReceipt({ memoryRoot, sessionId, now: nowFn(), warn: warnOnce })) return undefined;
333
- const evidence = [`tool=${name}`, `actionKind=${verdict.kind}`, `mode=${mode}`];
505
+ const session = resolveExecutionSession(execution);
506
+ if (hasActionReceipt({
507
+ memoryRoot,
508
+ sessionId: session.sessionId,
509
+ now: nowFn(),
510
+ windowMs,
511
+ actionKind: verdict.kind,
512
+ warn: warnOnce,
513
+ })) return undefined;
514
+ const evidence = [
515
+ `tool=${name}`,
516
+ `actionKind=${verdict.kind}`,
517
+ `sessionId=${session.sessionId ?? 'none'}`,
518
+ `sessionSource=${session.source}`,
519
+ `mode=${mode}`,
520
+ `windowMs=${windowMs}`,
521
+ ];
334
522
  const decision = mode === 'shadow' ? 'warn' : 'fail';
335
523
  writeGateRowSafe(memoryRoot, {
524
+ sessionId: session.sessionId,
336
525
  gate: 'action',
337
526
  decision,
338
527
  reason: mode === 'shadow' ? 'shadow' : 'no-receipt',
339
528
  evidence,
340
529
  }, warnOnce);
341
530
  if (mode === 'shadow') return undefined;
342
- return buildRefusal(verdict);
531
+ return buildRefusal(verdict, { windowMs });
343
532
  } catch (error) {
344
533
  warnOnce(`[longlive] action gate: 判定异常(${error?.code ?? error?.message ?? error})— 已 fail-open 放行`);
345
534
  return undefined;
@@ -350,7 +539,7 @@ export function registerActionGate(ctx, options = {}) {
350
539
  service.guard(guard);
351
540
  } catch (error) {
352
541
  warnOnce(`[longlive] action gate: 注册失败(${error?.code ?? error?.message ?? error})— 降级不阻断`);
353
- return { enabled: true, mode, registered: false, reason: 'register-failed' };
542
+ return { enabled: true, mode, windowMs, registered: false, reason: 'register-failed' };
354
543
  }
355
- return { enabled: true, mode, registered: true, guard };
544
+ return { enabled: true, mode, windowMs, registered: true, guard };
356
545
  }