@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
@@ -0,0 +1,545 @@
1
+ // 2.3.0 动作前回忆门(lane gate-feedback,默认 enforce)。
2
+ //
3
+ // 只在宿主 tools 服务的 guard 层工作:同步判定「这一次工具调用是不是高危动作命令」,
4
+ // 是则要求 gate-log 里存在同会话、同动作类别(actionKind)、且在时间窗内的动作回执;
5
+ // 没有回执就返回拒绝串。
6
+ // 三条硬约束:
7
+ // 1. guard 必须是同步的(宿主 ToolGuard 类型不允许 Promise),且绝不能抛异常——
8
+ // 宿主 checkGuards 没有 try/catch,抛出去会把这一次工具调用变成工具错误。
9
+ // 2. 读 gate-log 只读尾部 64KB(mtime+size 缓存),读失败按「无回执」处理并 warn 一次;
10
+ // 写记录失败只 warn,不影响判定结果。
11
+ // 3. 宿主没有 ctx.tools.guard() 时不注册、不阻断、不伪造阻断;只有真实宿主
12
+ // (ctx.get 存在)才 warn 并往 gate-log 写一条 skip 留痕。
13
+ //
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 },
24
+ // mode = enforce(默认,拒绝)/ shadow(只记不拦)/ off(不注册)。
25
+ // 归一化在 normalizeActionGateConfig,接线见 src/features.js。
26
+
27
+ import { closeSync, openSync, readSync, statSync } from 'node:fs';
28
+
29
+ import { appendGateLog, gateLogPaths } from '../recall/gate-log.mjs';
30
+
31
+ /** 默认配置:默认开启、默认强制、回执窗 90 秒(60–120 秒之间)。 */
32
+ export const ACTION_GATE_DEFAULTS = Object.freeze({ enabled: true, mode: 'enforce', windowMs: 90 * 1000 });
33
+
34
+ const ACTION_GATE_MODES = Object.freeze(['enforce', 'shadow']);
35
+
36
+ /** 回执匹配词:动作类关键词(中文 + 英文,子串匹配、大小写不敏感)。 */
37
+ export const ACTION_KEYWORDS = Object.freeze([
38
+ '发布', '安装', '回滚', '删除',
39
+ 'publish', 'install', 'rollback', 'remove',
40
+ ]);
41
+
42
+ /** 动作类命令只在 shell 工具上判定;plugin_manager 单独按 action 参数判定。 */
43
+ export const SHELL_TOOL_NAMES = Object.freeze(['pwsh', 'bash', 'bash_local']);
44
+
45
+ const PLUGIN_MANAGER_TOOL = 'plugin_manager';
46
+
47
+ /** 回执尾部读取上限(字节)与回执时间窗(毫秒,2.3.0 冻结 60–120 秒)。 */
48
+ const RECEIPT_TAIL_BYTES = 64 * 1024;
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
+ }
132
+
133
+ // 窄口径高危规则:只覆盖「发布 / 插件装卸 / 递归删除 / 回滚 / 硬重置」五类,
134
+ // 常规开发命令(npm install、npm test、git status 等)一律不命中。
135
+ const SHELL_RULES = Object.freeze([
136
+ { kind: 'publish', label: '发布', keywords: ['发布', 'publish'], re: /\b(?:npm|pnpm|yarn)\s+publish\b/i },
137
+ { kind: 'release', label: '发版', keywords: ['发布', 'publish'], re: /\bgh\s+release\b/i },
138
+ {
139
+ kind: 'plugin',
140
+ label: '插件装卸',
141
+ keywords: ['安装', 'install', 'remove'],
142
+ re: /\bplugin_manager\b[\s\S]{0,120}?\b(?:install|remove|add)\b/i,
143
+ },
144
+ {
145
+ kind: 'delete',
146
+ label: '递归删除',
147
+ keywords: ['删除', 'remove'],
148
+ re: /\bRemove-Item\b[\s\S]{0,240}?-Recurse\b/i,
149
+ },
150
+ {
151
+ kind: 'delete',
152
+ label: '递归删除',
153
+ keywords: ['删除', 'remove'],
154
+ re: /\brm\s+(?:-[a-zA-Z]*r[a-zA-Z]*f|-[a-zA-Z]*f[a-zA-Z]*r)\b/,
155
+ },
156
+ { kind: 'delete', label: '递归删除', keywords: ['删除', 'remove'], re: /\b(?:rd|rmdir)\s+\/s\b/i },
157
+ { kind: 'delete', label: '递归删除', keywords: ['删除', 'remove'], re: /\b(?:del|erase)\s+\/[a-z]*s[a-z]*\b/i },
158
+ { kind: 'rollback', label: '回滚', keywords: ['回滚', 'rollback'], test: isRollbackCommand },
159
+ { kind: 'reset', label: '硬重置', keywords: ['回滚', 'reset'], re: /\bgit\s+reset\s+--hard\b/i },
160
+ ]);
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
+
191
+ /**
192
+ * 归一化 actionGate 配置。kill switch:DSH_LONGLIVE_DISABLE_ACTION_GATE=1 / true。
193
+ * - 显式 enabled:false 关闭;mode:'off' 也关闭(不注册)。
194
+ * - mode 非法值回落 'enforce'(默认强制)。
195
+ * - windowMs 夹在 60–120 秒(2.3.0 冻结),非法值回落 90 秒。
196
+ */
197
+ export function normalizeActionGateConfig(raw, env = process.env) {
198
+ const source = raw && typeof raw === 'object' ? raw : {};
199
+ const killed = Boolean(env) && (env.DSH_LONGLIVE_DISABLE_ACTION_GATE === '1' || env.DSH_LONGLIVE_DISABLE_ACTION_GATE === 'true');
200
+ const requestedOff = source.enabled === false || source.mode === 'off';
201
+ if (killed || requestedOff) return { enabled: false, mode: 'off' };
202
+ const mode = ACTION_GATE_MODES.includes(source.mode) ? source.mode : ACTION_GATE_DEFAULTS.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 };
208
+ }
209
+
210
+ /** 从工具参数里取出命令文本(只认 command / cmd 两个常见键)。 */
211
+ function commandTextOf(args) {
212
+ if (typeof args === 'string') return args;
213
+ if (!args || typeof args !== 'object') return '';
214
+ for (const key of ['command', 'cmd']) {
215
+ const value = args[key];
216
+ if (typeof value === 'string' && value.trim() !== '') return value;
217
+ }
218
+ return '';
219
+ }
220
+
221
+ /**
222
+ * 判定一次工具调用是否属于动作类高危命令。
223
+ * 返回 { action:false } 或 { action:true, kind, label, keywords }。
224
+ * 不执行命令、不读盘、无副作用。
225
+ */
226
+ export function classifyActionCall(toolName, args) {
227
+ const name = typeof toolName === 'string' ? toolName : '';
228
+ if (name === PLUGIN_MANAGER_TOOL) {
229
+ const action = args && typeof args === 'object' && typeof args.action === 'string' ? args.action : '';
230
+ if (/(?:install|remove|add)/i.test(action)) {
231
+ return { action: true, kind: 'plugin', label: '插件装卸', keywords: ['安装', 'install', 'remove'] };
232
+ }
233
+ return { action: false };
234
+ }
235
+ if (!SHELL_TOOL_NAMES.includes(name)) return { action: false };
236
+ const text = commandTextOf(args);
237
+ if (text === '') return { action: false };
238
+ for (const rule of SHELL_RULES) {
239
+ const hit = typeof rule.test === 'function' ? rule.test(text) : rule.re.test(text);
240
+ if (hit) {
241
+ return { action: true, kind: rule.kind, label: rule.label, keywords: rule.keywords.slice() };
242
+ }
243
+ }
244
+ return { action: false };
245
+ }
246
+
247
+ /**
248
+ * 无回执时的拒绝串:给出显式放行路径(动作类 recall 回执 / 用户二次同意后的 shadow 宽容)。
249
+ * 文案供模型直接执行,不执行任何动作。
250
+ */
251
+ export function buildRefusal(verdict = {}, { windowMs = RECEIPT_WINDOW_MS } = {}) {
252
+ const label = typeof verdict.label === 'string' && verdict.label !== '' ? verdict.label : '高危';
253
+ const keyword = Array.isArray(verdict.keywords) && verdict.keywords.length > 0 ? verdict.keywords[0] : '回滚';
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)后重试(需重启宿主生效)。';
260
+ }
261
+
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
+ }
271
+ const agentId = execution.agent && typeof execution.agent === 'object' ? execution.agent.id : 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;
279
+ }
280
+
281
+ function parseRowTime(value) {
282
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
283
+ if (typeof value === 'string' && value !== '') {
284
+ const parsed = Date.parse(value);
285
+ return Number.isFinite(parsed) ? parsed : NaN;
286
+ }
287
+ return NaN;
288
+ }
289
+
290
+ function evidenceValue(evidence, key) {
291
+ const prefix = `${key}=`;
292
+ const found = [];
293
+ for (const item of evidence) {
294
+ if (typeof item !== 'string') continue;
295
+ const index = item.indexOf(prefix);
296
+ if (index !== 0 && index < 0) continue;
297
+ const start = index + prefix.length;
298
+ if (start <= 0) continue;
299
+ const value = item.slice(start);
300
+ if (value !== '') found.push(value);
301
+ }
302
+ return found.join(' ');
303
+ }
304
+
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 }) {
325
+ if (!row || typeof row !== 'object' || row.decision !== 'ok') return false;
326
+ const rowSessionId = typeof row.sessionId === 'string' && row.sessionId !== '' ? row.sessionId : null;
327
+ if (sessionId !== null) {
328
+ if (rowSessionId !== sessionId) return false;
329
+ } else if (rowSessionId !== null) {
330
+ return false;
331
+ }
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;
340
+ }
341
+
342
+ // gate-log 尾部行缓存:只按 logFile 的 mtime+size 失效,避免每个 shell 调用都读盘。
343
+ const tailCache = new Map();
344
+
345
+ /** 测试用:清空尾部行缓存(生产不需要调用)。 */
346
+ export function resetActionGateCache() {
347
+ tailCache.clear();
348
+ }
349
+
350
+ function readTailRows(memoryRoot) {
351
+ const { logFile } = gateLogPaths(memoryRoot);
352
+ let stat;
353
+ try {
354
+ stat = statSync(logFile);
355
+ } catch (error) {
356
+ if (error && error.code === 'ENOENT') return [];
357
+ throw error;
358
+ }
359
+ if (!stat.isFile()) {
360
+ const error = new Error('gate-log path is not a regular file');
361
+ error.code = 'E_GATE_LOG_NOT_FILE';
362
+ throw error;
363
+ }
364
+ const cached = tailCache.get(logFile);
365
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached.rows;
366
+ const length = Math.min(stat.size, RECEIPT_TAIL_BYTES);
367
+ const start = Math.max(0, stat.size - length);
368
+ let buffer;
369
+ const fd = openSync(logFile, 'r');
370
+ try {
371
+ buffer = Buffer.alloc(length);
372
+ readSync(fd, buffer, 0, length, start);
373
+ } finally {
374
+ closeSync(fd);
375
+ }
376
+ let text = buffer.toString('utf8');
377
+ if (start > 0) {
378
+ // 尾部截断可能切在行中间:丢掉第一段残行。
379
+ const newline = text.indexOf('\n');
380
+ text = newline >= 0 ? text.slice(newline + 1) : '';
381
+ }
382
+ const rows = [];
383
+ for (const line of text.split('\n')) {
384
+ const trimmed = line.trim();
385
+ if (trimmed === '') continue;
386
+ try {
387
+ const row = JSON.parse(trimmed);
388
+ if (row && typeof row === 'object') rows.push(row);
389
+ } catch {
390
+ /* 坏行忽略:一条损坏记录不应让门失效 */
391
+ }
392
+ }
393
+ tailCache.set(logFile, { mtimeMs: stat.mtimeMs, size: stat.size, rows });
394
+ return rows;
395
+ }
396
+
397
+ /**
398
+ * 查回执:同会话(sessionId 有效时)或同为空会话、时间窗内(60–120 秒)、kind 匹配的 ok 行。
399
+ * 读失败按「无回执」返回 false,并只通过传入的 warn 报告一次(由调用方去重)。
400
+ */
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
+ } = {}) {
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;
414
+ let rows;
415
+ try {
416
+ rows = readTailRows(memoryRoot);
417
+ } catch (error) {
418
+ if (typeof warn === 'function') {
419
+ warn(`[longlive] action gate: gate-log 读取失败(${error?.code ?? error?.message ?? error})— 按无回执处理`);
420
+ }
421
+ return false;
422
+ }
423
+ for (let index = rows.length - 1; index >= 0; index -= 1) {
424
+ if (rowIsActionReceipt(rows[index], { sessionId, now, windowMs: boundedWindow, actionKind })) return true;
425
+ }
426
+ return false;
427
+ }
428
+
429
+ function writeGateRowSafe(memoryRoot, entry, warn) {
430
+ try {
431
+ appendGateLog(memoryRoot, entry);
432
+ return true;
433
+ } catch (error) {
434
+ if (typeof warn === 'function') {
435
+ warn(`[longlive] action gate: gate-log 写入失败(${error?.code ?? error?.message ?? error})— 判定不受影响`);
436
+ }
437
+ return false;
438
+ }
439
+ }
440
+
441
+ function loggerOf(options) {
442
+ if (typeof options.warn === 'function') return options.warn;
443
+ const logger = options.logger;
444
+ if (logger && typeof logger.warn === 'function') return (message) => logger.warn(message);
445
+ return null;
446
+ }
447
+
448
+ /** 宿主是否像真实宿主:真实 Cordis ctx 有 ctx.get();单元测试的 fake ctx 一般没有。 */
449
+ function looksLikeHost(ctx) {
450
+ return Boolean(ctx) && (typeof ctx.get === 'function' || typeof ctx.tools?.execute === 'function');
451
+ }
452
+
453
+ /**
454
+ * 注册动作门(同步)。
455
+ * options: { config, memoryRoot, ownToolNames, warn|logger, env, now }
456
+ * 返回 { enabled, mode, windowMs, registered, reason?, guard? }。
457
+ */
458
+ export function registerActionGate(ctx, options = {}) {
459
+ const normalized = normalizeActionGateConfig(options.config, options.env ?? process.env);
460
+ if (!normalized.enabled) return { enabled: false, mode: 'off', registered: false, reason: 'off' };
461
+ const mode = normalized.mode;
462
+ const windowMs = normalized.windowMs ?? RECEIPT_WINDOW_MS;
463
+ const warn = loggerOf(options);
464
+ const memoryRoot = typeof options.memoryRoot === 'string' && options.memoryRoot !== '' ? options.memoryRoot : null;
465
+ const ownToolNames = options.ownToolNames instanceof Set
466
+ ? options.ownToolNames
467
+ : (Array.isArray(options.ownToolNames) ? new Set(options.ownToolNames) : null);
468
+ const nowFn = typeof options.now === 'function' ? options.now : Date.now;
469
+ const service = ctx && ctx.tools;
470
+
471
+ if (!service || typeof service.guard !== 'function') {
472
+ // 降级:不阻断、不伪造。真实宿主缺 API 才 warn + gate-log 留痕。
473
+ if (looksLikeHost(ctx)) {
474
+ const message = '[longlive] action gate: 宿主未提供 ctx.tools.guard(),动作门无法注册(降级:不阻断,仅留痕)';
475
+ if (warn) warn(message);
476
+ else console.warn?.(message);
477
+ if (memoryRoot) {
478
+ writeGateRowSafe(memoryRoot, {
479
+ gate: 'action',
480
+ decision: 'skip',
481
+ reason: 'host-guard-absent',
482
+ evidence: [`mode=${mode}`, 'sessionId=none', 'sessionSource=host-guard-absent'],
483
+ }, null);
484
+ }
485
+ }
486
+ return { enabled: true, mode, windowMs, registered: false, reason: 'no-host-guard' };
487
+ }
488
+ if (!memoryRoot) return { enabled: true, mode, windowMs, registered: false, reason: 'no-memory-root' };
489
+
490
+ let warned = false;
491
+ const warnOnce = (message) => {
492
+ if (warned) return;
493
+ warned = true;
494
+ if (warn) warn(message);
495
+ else console.warn?.(message);
496
+ };
497
+
498
+ const guard = (execution) => {
499
+ try {
500
+ const name = typeof execution?.name === 'string' ? execution.name : '';
501
+ if (name === '') return undefined;
502
+ if (ownToolNames && ownToolNames.has(name)) return undefined;
503
+ const verdict = classifyActionCall(name, execution?.arguments);
504
+ if (!verdict.action) return undefined;
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
+ ];
522
+ const decision = mode === 'shadow' ? 'warn' : 'fail';
523
+ writeGateRowSafe(memoryRoot, {
524
+ sessionId: session.sessionId,
525
+ gate: 'action',
526
+ decision,
527
+ reason: mode === 'shadow' ? 'shadow' : 'no-receipt',
528
+ evidence,
529
+ }, warnOnce);
530
+ if (mode === 'shadow') return undefined;
531
+ return buildRefusal(verdict, { windowMs });
532
+ } catch (error) {
533
+ warnOnce(`[longlive] action gate: 判定异常(${error?.code ?? error?.message ?? error})— 已 fail-open 放行`);
534
+ return undefined;
535
+ }
536
+ };
537
+
538
+ try {
539
+ service.guard(guard);
540
+ } catch (error) {
541
+ warnOnce(`[longlive] action gate: 注册失败(${error?.code ?? error?.message ?? error})— 降级不阻断`);
542
+ return { enabled: true, mode, windowMs, registered: false, reason: 'register-failed' };
543
+ }
544
+ return { enabled: true, mode, windowMs, registered: true, guard };
545
+ }