@jjh32456/longlive 1.8.12 → 2.1.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.
- package/CHANGELOG.md +258 -202
- package/QUICKSTART.md +10 -11
- package/README.en.md +13 -4
- package/README.md +61 -18
- package/SPEC.md +3 -3
- package/build-info.json +259 -129
- package/cordis.patch.yml +32 -1
- package/docs/ANSWER-GUARD.md +1 -1
- package/docs/ARCHITECTURE.md +3 -3
- package/docs/AUTO-RECALL-WIRING.md +5 -3
- package/docs/AUTO-RECALL.md +10 -4
- package/docs/CONFIG.md +46 -11
- package/docs/ERRORS.md +1 -1
- package/docs/FAQ.md +9 -9
- package/docs/FEATURES.md +19 -16
- package/docs/OPERATIONS.md +3 -3
- package/docs/PANEL-INTEGRATION.md +1 -1
- package/docs/PRIVACY.md +6 -6
- package/docs/QUICKSTART.md +5 -5
- package/docs/README.en.md +5 -3
- package/docs/TOOLS.md +1 -1
- package/docs/TROUBLESHOOTING.md +4 -4
- package/package.json +6 -3
- package/runbook.md +3 -3
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-lifecycle.mjs +2 -2
- package/src/answer/claim-guard.mjs +234 -0
- package/src/backup.js +165 -1
- package/src/config.js +18 -7
- package/src/features.js +132 -5
- package/src/handoff/index.js +133 -0
- package/src/handoff/model.js +48 -0
- package/src/identity/handover.js +203 -15
- package/src/identity/inject-position.js +3 -1
- package/src/index.js +2 -2
- package/src/memory/a1-migration.js +72 -6
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/capture-host.js +71 -2
- package/src/memory/capture.js +45 -6
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +51 -2
- package/src/memory/conclusion-drafts.js +7 -3
- package/src/memory/conflicts.js +915 -2
- package/src/memory/consolidate.js +20 -1
- package/src/memory/forget-v2.js +272 -2
- package/src/memory/forget.js +20 -1
- package/src/memory/frames-activation.js +3 -1
- package/src/memory/fts-query.js +2 -2
- package/src/memory/index.js +80 -7
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +128 -0
- package/src/memory/maintenance.js +386 -22
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/memory-reader.mjs +1003 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +3 -3
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +20 -1
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +13 -1
- package/src/memory/recall.js +102 -1
- package/src/memory/reinforce.js +138 -2
- package/src/memory/retention.js +34 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/working-frame.js +271 -8
- package/src/metrics/classify.mjs +3 -1
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +174 -19
- package/src/recall/archive-search.mjs +3 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/continuity-log.mjs +435 -0
- package/src/recall/continuity-volatile.mjs +1001 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +21 -2
- package/src/recall/explain.mjs +10 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +663 -29
- package/src/recall/inject-order.mjs +3 -1
- package/src/recall/link-fastpath.mjs +662 -0
- package/src/recall/recall-core.mjs +74 -2
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +58 -1
- package/src/retention/index.js +193 -35
- package/src/router/design-headings.json +10 -10
- package/src/tools.js +122 -6
|
@@ -0,0 +1,2999 @@
|
|
|
1
|
+
// 2.0.0 批 H · N15 hardgate.wake 唤醒桥(单模块:能力探测 + 数据面 + 状态机 + 自动授权)
|
|
2
|
+
//
|
|
3
|
+
// 规格:H-IMPL-SPEC-v2 §2–§6(DRAFT-PENDING-RT)。本文件同时承载 auto-authz 符号
|
|
4
|
+
// (authorize / applyProposal / authorizeAndApply / auditRow / DEFAULT_RULES / sha256Text / isInside),
|
|
5
|
+
// 不再有 src/hardgate/ 双模块布局(附录 C 被否行为 1)。
|
|
6
|
+
//
|
|
7
|
+
// 口径(红队可审):
|
|
8
|
+
// * 默认关闭:`hardgate.wake.enabled !== true` 时零钩子、零定时器、零会话、零写盘。
|
|
9
|
+
// * 能力探测 fail-closed(P0-01):permissionPresets.resolve('auto') 不抛 + API 形状
|
|
10
|
+
// + auto-review 版本精确 '0.2.3-alpha.2';缺失/不符 → E_HG_WAKE_CAPABILITY_MISSING,
|
|
11
|
+
// 0 会话 0 重试,可见(gate-log hg.wake.fail + panel.capability 段)。
|
|
12
|
+
// * 数据面只写 <memoryRoot>/.longlive/wake/ 六类文件;写时 prune + daily reconcile 双保险;
|
|
13
|
+
// 原子写 tmp → fsync → rename;上界见 WAKE_BOUNDS。
|
|
14
|
+
// * 后台会话:permissionPresets.set(session,'auto') → approval.setPolicy(agent,'never') →
|
|
15
|
+
// installToolPolicy(白名单 + denyNames 拒绝表优先,run_code/PTC 一律排除;创建后断言)。
|
|
16
|
+
// 注:本模块**不** import src/router/**(R1-ID4 拓扑:产品代码里只有 src/index.js 能
|
|
17
|
+
// import router),安装策略用下面的本地 installWakeToolPolicy;需要时也可由
|
|
18
|
+
// options.installToolPolicy 注入(测试/d23 夹具走注入)。
|
|
19
|
+
// 写动作只能走 memory_wake action=propose → 本文件 auto-authz 规则表判定,插件核自己写盘。
|
|
20
|
+
// * 重试(P1-04):pickTicket = queued ∪ failed(retries < retryMax);达到 retryMax 才 expired。
|
|
21
|
+
// * 限额(P1-05):timeoutSeconds/maxPerDay/cooldownSeconds/queueMax/maxFilesPerRun 是硬拦;
|
|
22
|
+
// maxRounds/maxOutputTokens/maxOutputChars 只写进任务书与 run 审计字段(rounds/tokens/
|
|
23
|
+
// outputChars/toolCalls),不假称硬拦。
|
|
24
|
+
// * 被拒(AUTO_REVIEW_DENIED / AUTO_REVIEW_FAILED):绝不静默、绝不重试,升级 pending 给人工。
|
|
25
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
26
|
+
import fs from 'node:fs';
|
|
27
|
+
import fsp from 'node:fs/promises';
|
|
28
|
+
import path from 'node:path';
|
|
29
|
+
|
|
30
|
+
import { appendGateLog, canonicalJson } from '../recall/gate-log.mjs';
|
|
31
|
+
import { nextLocalMidnight, MIDNIGHT_PAD_MS } from './maintenance.js';
|
|
32
|
+
|
|
33
|
+
/** 模块路径(红队/计数脚本用;唯一生产路径 = src/memory/wake-bridge.mjs)。 */
|
|
34
|
+
export const WAKE_MODULE = 'memory/wake-bridge.mjs';
|
|
35
|
+
/** 工具名(tools.js 已注册,不新增工具)。 */
|
|
36
|
+
export const WAKE_TOOL_NAME = 'memory_wake';
|
|
37
|
+
/** auto-review 版本精确匹配值(§4 / §10 Q4)。 */
|
|
38
|
+
export const WAKE_CAPABILITY_VERSION = '0.2.3-alpha.2';
|
|
39
|
+
export const AUTO_REVIEW_BUNDLE = '@deepseek-ai/dsh-experimental-auto-review';
|
|
40
|
+
/** 能力缺失码(可见:gate-log + panel.capability 段)。 */
|
|
41
|
+
export const CAPABILITY_MISSING_CODE = 'E_HG_WAKE_CAPABILITY_MISSING';
|
|
42
|
+
/** 门事件命名空间(hardgate/ 只是数据面与门事件命名空间,不是模块目录)。 */
|
|
43
|
+
export const GATE_EVENTS = Object.freeze({
|
|
44
|
+
FAIL: 'hg.d23.fail',
|
|
45
|
+
SKIP: 'hg.d23.skip',
|
|
46
|
+
WAKE_FAIL: 'hg.wake.fail',
|
|
47
|
+
WAKE_RECONCILE: 'hg.wake.reconcile',
|
|
48
|
+
WAKE_ROTATE: 'hg.wake.rotate',
|
|
49
|
+
WAKE_CAPABILITY: 'hg.wake.capability',
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
/** 数据面:<memoryRoot>/.longlive/wake/ 六类文件(§3)。 */
|
|
53
|
+
export const WAKE_DATA_REL = '.longlive/wake';
|
|
54
|
+
export const WAKE_QUEUE_REL = '.longlive/wake/wake-queue.jsonl';
|
|
55
|
+
export const WAKE_PENDING_REL = '.longlive/wake/wake-pending.jsonl';
|
|
56
|
+
export const WAKE_AUTHZ_REL = '.longlive/wake/auto-authz.jsonl';
|
|
57
|
+
export const WAKE_PANEL_REL = '.longlive/wake/panel.json';
|
|
58
|
+
export const WAKE_STATE_REL = '.longlive/wake/wake-state.json';
|
|
59
|
+
export const WAKE_RUNS_REL = '.longlive/wake/runs';
|
|
60
|
+
export const WAKE_SCHEMAS = Object.freeze({
|
|
61
|
+
queue: 'wake-queue/v1',
|
|
62
|
+
pending: 'wake-pending/v1',
|
|
63
|
+
authz: 'wake-authz/v1',
|
|
64
|
+
run: 'wake-run/v1',
|
|
65
|
+
panel: 'wake-panel/v1',
|
|
66
|
+
state: 'wake-state/v1',
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
/** 上界(§3.2):条数 ∧ 天数 + 单文件字节 + panel/state 字节。 */
|
|
70
|
+
export const WAKE_BOUNDS = Object.freeze({
|
|
71
|
+
queueMax: 200,
|
|
72
|
+
pendingMax: 200,
|
|
73
|
+
retryMax: 2,
|
|
74
|
+
ticketTtlDays: 90,
|
|
75
|
+
runsMax: 200,
|
|
76
|
+
runsDays: 90,
|
|
77
|
+
authzMaxLines: 50000,
|
|
78
|
+
authzDays: 180,
|
|
79
|
+
panelMaxBytes: 64 * 1024,
|
|
80
|
+
stateMaxBytes: 4 * 1024,
|
|
81
|
+
fileMaxBytes: 256 * 1024,
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
/** 唤醒桥错误码(全部 fail-closed,不静默)。 */
|
|
85
|
+
export const WAKE_CODES = Object.freeze({
|
|
86
|
+
DISABLED: 'E_WAKE_DISABLED',
|
|
87
|
+
ROOT_UNRESOLVED: 'E_WAKE_ROOT_UNRESOLVED',
|
|
88
|
+
DEPS_MISSING: 'E_WAKE_DEPS_MISSING',
|
|
89
|
+
CAPABILITY_MISSING: CAPABILITY_MISSING_CODE,
|
|
90
|
+
CREATE_FAILED: 'E_WAKE_CREATE_FAILED',
|
|
91
|
+
SHAPE_INVALID: 'E_WAKE_AGENT_SHAPE',
|
|
92
|
+
FOLLOWUP_FAILED: 'E_WAKE_FOLLOWUP_FAILED',
|
|
93
|
+
TIMEOUT: 'E_WAKE_TIMEOUT',
|
|
94
|
+
DENIED: 'E_WAKE_AUTO_REVIEW_DENIED',
|
|
95
|
+
REVIEW_UNAVAILABLE: 'E_WAKE_AUTO_REVIEW_FAILED',
|
|
96
|
+
ESCALATE: 'E_WAKE_ESCALATE',
|
|
97
|
+
QUOTA: 'E_WAKE_QUOTA',
|
|
98
|
+
COOLDOWN: 'E_WAKE_COOLDOWN',
|
|
99
|
+
EMPTY: 'E_WAKE_QUEUE_EMPTY',
|
|
100
|
+
TICKET_INVALID: 'E_WAKE_TICKET_INVALID',
|
|
101
|
+
TICKET_EXPIRED: 'E_WAKE_TICKET_EXPIRED',
|
|
102
|
+
TICKET_NOT_FOUND: 'E_WAKE_TICKET_NOT_FOUND',
|
|
103
|
+
QUEUE_FULL: 'E_WAKE_QUEUE_FULL',
|
|
104
|
+
TRIGGER_DISABLED: 'E_WAKE_TRIGGER_DISABLED',
|
|
105
|
+
RUN_CODE_NOT_RESTRICTABLE: 'E_WAKE_RUN_CODE_NOT_RESTRICTABLE',
|
|
106
|
+
TOOLSET_VIOLATION: 'E_WAKE_TOOLSET_VIOLATION',
|
|
107
|
+
NOT_WAKE_SESSION: 'E_WAKE_NOT_WAKE_SESSION',
|
|
108
|
+
ACTION_INVALID: 'E_WAKE_ACTION_INVALID',
|
|
109
|
+
PROPOSAL_FAILED: 'E_WAKE_PROPOSAL_FAILED',
|
|
110
|
+
AUTHZ_DENY: 'E_WAKE_AUTHZ_DENY',
|
|
111
|
+
STORE_WRITE_FAILED: 'E_WAKE_STORE_WRITE_FAILED',
|
|
112
|
+
CONFIG_INVALID: 'E_WAKE_CONFIG_INVALID',
|
|
113
|
+
BUSY: 'E_WAKE_BUSY',
|
|
114
|
+
UNEXPECTED: 'E_WAKE_UNEXPECTED',
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
/** 五类触发源(§5 / §6.4:配置只可删)。 */
|
|
118
|
+
export const WAKE_KINDS = Object.freeze([
|
|
119
|
+
'forget_historical',
|
|
120
|
+
'conflict_resolved',
|
|
121
|
+
'procedure_candidate',
|
|
122
|
+
'promise_done',
|
|
123
|
+
'migration_confirm',
|
|
124
|
+
]);
|
|
125
|
+
|
|
126
|
+
/** 后台会话默认工具白名单(只读 + 提议工具)。 */
|
|
127
|
+
export const WAKE_ALLOW_TOOLS_DEFAULT = Object.freeze(['read', 'glob', 'grep', 'read_image', 'memory_wake']);
|
|
128
|
+
|
|
129
|
+
/** 拒绝表(优先于白名单;run_code / PTC / 委派 / 终端 / 写工具一律排除)。 */
|
|
130
|
+
export const WAKE_TOOL_DENY = Object.freeze([
|
|
131
|
+
'run_code',
|
|
132
|
+
'rpc',
|
|
133
|
+
'ptc',
|
|
134
|
+
'task',
|
|
135
|
+
'subagent',
|
|
136
|
+
'subagent_fork',
|
|
137
|
+
'bash',
|
|
138
|
+
'pwsh',
|
|
139
|
+
'terminal_open',
|
|
140
|
+
'terminal_send',
|
|
141
|
+
'write',
|
|
142
|
+
'edit',
|
|
143
|
+
'apply_patch',
|
|
144
|
+
'install',
|
|
145
|
+
'pack',
|
|
146
|
+
'publish',
|
|
147
|
+
]);
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* 默认值(I2 契约钉住;规格 §6.4 的数字不随环境变)。
|
|
151
|
+
* maxRounds / maxOutputTokens / maxOutputChars 只进任务书 + 审计,不是硬拦。
|
|
152
|
+
*/
|
|
153
|
+
export const WAKE_DEFAULTS = Object.freeze({
|
|
154
|
+
enabled: false,
|
|
155
|
+
triggers: Object.freeze([...WAKE_KINDS]),
|
|
156
|
+
maxPerDay: 20,
|
|
157
|
+
cooldownSeconds: 600,
|
|
158
|
+
timeoutSeconds: 180,
|
|
159
|
+
ticketTtlHours: 24,
|
|
160
|
+
queueMax: 200,
|
|
161
|
+
maxFilesPerRun: 3,
|
|
162
|
+
maxRounds: 3,
|
|
163
|
+
maxOutputTokens: 2000,
|
|
164
|
+
maxOutputChars: 8000,
|
|
165
|
+
retryMax: 2,
|
|
166
|
+
preset: 'auto',
|
|
167
|
+
approvalPolicy: 'never',
|
|
168
|
+
allowTools: WAKE_ALLOW_TOOLS_DEFAULT,
|
|
169
|
+
denyTools: Object.freeze([...WAKE_TOOL_DENY]),
|
|
170
|
+
toolExclude: Object.freeze([...WAKE_TOOL_DENY]),
|
|
171
|
+
runOnStart: true,
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
/** 对外配置键(config.js passthrough 注释里逐字说明;不声明 schemastery 节点)。 */
|
|
175
|
+
export const WAKE_CONFIG_KEYS = Object.freeze([
|
|
176
|
+
'enabled',
|
|
177
|
+
'triggers',
|
|
178
|
+
'maxPerDay',
|
|
179
|
+
'cooldownSeconds',
|
|
180
|
+
'timeoutSeconds',
|
|
181
|
+
'ticketTtlHours',
|
|
182
|
+
'queueMax',
|
|
183
|
+
'maxFilesPerRun',
|
|
184
|
+
'maxRounds',
|
|
185
|
+
'maxOutputTokens',
|
|
186
|
+
'maxOutputChars',
|
|
187
|
+
'retryMax',
|
|
188
|
+
'allowTools',
|
|
189
|
+
'toolExclude',
|
|
190
|
+
'runOnStart',
|
|
191
|
+
]);
|
|
192
|
+
|
|
193
|
+
/** 预算说明(写进任务书;不是硬拦,超了只审计)。 */
|
|
194
|
+
export const WAKE_BUDGET_NOTE = Object.freeze({
|
|
195
|
+
timeoutSeconds: '硬拦:whenIdle 超时后 cancel + dispose',
|
|
196
|
+
maxPerDay: '硬拦:当天会话数上限',
|
|
197
|
+
cooldownSeconds: '硬拦:两次会话最小间隔',
|
|
198
|
+
queueMax: '硬拦:队列容量',
|
|
199
|
+
maxFilesPerRun: '硬拦:单次提议可写文件数',
|
|
200
|
+
maxRounds: '非硬拦:任务书预算 + run.rounds 审计',
|
|
201
|
+
maxOutputTokens: '非硬拦:任务书预算(宿主 token 计量不可得时记 null)',
|
|
202
|
+
maxOutputChars: '非硬拦:任务书预算 + run.outputChars 审计',
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
// ---------------------------------------------------------------------------
|
|
206
|
+
// 基础工具(纯函数 / 最小 I/O)
|
|
207
|
+
// ---------------------------------------------------------------------------
|
|
208
|
+
|
|
209
|
+
/** 构造带 code 的错误(fail-closed 的可见载体)。 */
|
|
210
|
+
function wakeError(code, message, detail) {
|
|
211
|
+
const error = new Error(message ?? code);
|
|
212
|
+
error.code = code;
|
|
213
|
+
if (detail !== undefined) error.detail = detail;
|
|
214
|
+
return error;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** 运行时时间源:注入 now() 便于夹具做确定性复现。 */
|
|
218
|
+
function nowDateOf(value) {
|
|
219
|
+
const date = value instanceof Date ? value : new Date(value ?? Date.now());
|
|
220
|
+
return Number.isNaN(date.getTime()) ? new Date() : date;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function nowOf(runtime) {
|
|
224
|
+
const source = typeof runtime?.now === 'function' ? runtime.now() : runtime?.now;
|
|
225
|
+
return nowDateOf(source);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** 本地时区 YYYY-MM-DD(与 maintenance 的 dayString 同口径)。 */
|
|
229
|
+
function dateKeyOf(date) {
|
|
230
|
+
const value = nowDateOf(date);
|
|
231
|
+
const y = value.getFullYear();
|
|
232
|
+
const m = String(value.getMonth() + 1).padStart(2, '0');
|
|
233
|
+
const d = String(value.getDate()).padStart(2, '0');
|
|
234
|
+
return `${y}-${m}-${d}`;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function isoOf(date) {
|
|
238
|
+
return nowDateOf(date).toISOString();
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Promise 超时(whenIdle / dispose 用);超时抛带 code 的错误。 */
|
|
242
|
+
function withTimeout(promise, ms, code, message) {
|
|
243
|
+
let timer = null;
|
|
244
|
+
const timeout = new Promise((_, reject) => {
|
|
245
|
+
timer = setTimeout(() => reject(wakeError(code, message ?? `${code} after ${ms}ms`)), Math.max(1, Number(ms) || 1));
|
|
246
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
247
|
+
});
|
|
248
|
+
return Promise.race([Promise.resolve(promise), timeout]).finally(() => {
|
|
249
|
+
if (timer) clearTimeout(timer);
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function readJson(file, fallback = null) {
|
|
254
|
+
try {
|
|
255
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
256
|
+
} catch {
|
|
257
|
+
return fallback;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function readJsonl(file, { maxRows = 0, tail = 0 } = {}) {
|
|
262
|
+
let text;
|
|
263
|
+
try {
|
|
264
|
+
text = fs.readFileSync(file, 'utf8');
|
|
265
|
+
} catch {
|
|
266
|
+
return [];
|
|
267
|
+
}
|
|
268
|
+
const rows = [];
|
|
269
|
+
for (const line of text.split(/\r?\n/)) {
|
|
270
|
+
const trimmed = line.trim();
|
|
271
|
+
if (trimmed === '') continue;
|
|
272
|
+
try {
|
|
273
|
+
const parsed = JSON.parse(trimmed);
|
|
274
|
+
if (parsed && typeof parsed === 'object') rows.push(parsed);
|
|
275
|
+
} catch {
|
|
276
|
+
// 半行(进程被杀)跳过:审计面宁缺一行,也不打死整个唤醒。
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (tail > 0) return rows.slice(-tail);
|
|
280
|
+
if (maxRows > 0) return rows.slice(0, maxRows);
|
|
281
|
+
return rows;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** 原子写:tmp → fsync → rename;父目录自动建。 */
|
|
285
|
+
function writeFileAtomic(file, text) {
|
|
286
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
287
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
|
|
288
|
+
const fd = fs.openSync(tmp, 'w');
|
|
289
|
+
try {
|
|
290
|
+
fs.writeSync(fd, text, null, 'utf8');
|
|
291
|
+
fs.fsyncSync(fd);
|
|
292
|
+
} finally {
|
|
293
|
+
fs.closeSync(fd);
|
|
294
|
+
}
|
|
295
|
+
fs.renameSync(tmp, file);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function appendJsonl(file, row) {
|
|
299
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
300
|
+
const fd = fs.openSync(file, 'a');
|
|
301
|
+
try {
|
|
302
|
+
fs.writeSync(fd, `${JSON.stringify(row)}\n`, null, 'utf8');
|
|
303
|
+
fs.fsyncSync(fd);
|
|
304
|
+
} finally {
|
|
305
|
+
fs.closeSync(fd);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function statSize(file) {
|
|
310
|
+
try {
|
|
311
|
+
return fs.statSync(file).size;
|
|
312
|
+
} catch {
|
|
313
|
+
return 0;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function clampText(text, maxChars) {
|
|
318
|
+
const value = String(text ?? '');
|
|
319
|
+
const max = Math.max(1, Number(maxChars) || 1);
|
|
320
|
+
return value.length <= max ? value : `${value.slice(0, max)}\n…[truncated ${value.length - max} chars]`;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function bumpCount(map, key, amount = 1) {
|
|
324
|
+
map[key] = Number(map[key] ?? 0) + amount;
|
|
325
|
+
return map[key];
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function sha256Hex(text) {
|
|
329
|
+
return createHash('sha256').update(Buffer.from(String(text ?? ''), 'utf8')).digest('hex');
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function isPlainObject(value) {
|
|
333
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// ---------------------------------------------------------------------------
|
|
337
|
+
// 能力探测(P0-01 / §4):运行期唯一口径
|
|
338
|
+
// ---------------------------------------------------------------------------
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* 探测 auto-review 运行期能力(同步、可注入、可被夹具桩造缺失)。
|
|
342
|
+
*
|
|
343
|
+
* 判定:
|
|
344
|
+
* 1) API 形状:permissionPresets.resolve/set/current/registerAuto +
|
|
345
|
+
* approval.overrideOf/setPolicy + agents.create 全部是 function;
|
|
346
|
+
* 2) permissionPresets.resolve('auto') 不抛(auto 集成活着);
|
|
347
|
+
* 3) auto-review bundle 版本精确 === '0.2.3-alpha.2';取不到版本 → 'unknown' fail-closed。
|
|
348
|
+
*
|
|
349
|
+
* @returns {{ok:boolean, mode:'present'|'missing', capability:object, code?:string, detail?:object}}
|
|
350
|
+
*/
|
|
351
|
+
export function probeWakeCapabilities(runtime = {}, options = {}) {
|
|
352
|
+
const ctx = runtime?.ctx ?? runtime;
|
|
353
|
+
const get = (name) => {
|
|
354
|
+
try {
|
|
355
|
+
return typeof ctx?.get === 'function' ? ctx.get(name) : ctx?.[name];
|
|
356
|
+
} catch {
|
|
357
|
+
return undefined;
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
const permissionPresets = options.permissionPresets ?? get('permissionPresets');
|
|
361
|
+
const approval = options.approval ?? get('approval');
|
|
362
|
+
const agents = options.agents ?? get('agents');
|
|
363
|
+
|
|
364
|
+
const missing = [];
|
|
365
|
+
for (const key of ['resolve', 'set', 'current', 'registerAuto']) {
|
|
366
|
+
if (typeof permissionPresets?.[key] !== 'function') missing.push(`permissionPresets.${key}`);
|
|
367
|
+
}
|
|
368
|
+
for (const key of ['overrideOf', 'setPolicy']) {
|
|
369
|
+
if (typeof approval?.[key] !== 'function') missing.push(`approval.${key}`);
|
|
370
|
+
}
|
|
371
|
+
if (typeof agents?.create !== 'function') missing.push('agents.create');
|
|
372
|
+
|
|
373
|
+
const versionOverride = typeof options.version === 'string' && options.version.trim() !== ''
|
|
374
|
+
? options.version.trim()
|
|
375
|
+
: (typeof runtime?.capabilityVersion === 'string' && runtime.capabilityVersion.trim() !== ''
|
|
376
|
+
? runtime.capabilityVersion.trim()
|
|
377
|
+
: null);
|
|
378
|
+
|
|
379
|
+
const fail = (reason, extra = {}) => ({
|
|
380
|
+
ok: false,
|
|
381
|
+
mode: 'missing',
|
|
382
|
+
capability: {
|
|
383
|
+
present: false,
|
|
384
|
+
version: extra.version ?? 'unknown',
|
|
385
|
+
code: CAPABILITY_MISSING_CODE,
|
|
386
|
+
},
|
|
387
|
+
code: CAPABILITY_MISSING_CODE,
|
|
388
|
+
detail: { reason, missing: [...missing], ...extra },
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
if (missing.length > 0) return fail('shape-missing', { version: versionOverride ?? 'unknown' });
|
|
392
|
+
|
|
393
|
+
let resolved = null;
|
|
394
|
+
try {
|
|
395
|
+
resolved = permissionPresets.resolve('auto');
|
|
396
|
+
} catch (error) {
|
|
397
|
+
return fail('resolve-threw', {
|
|
398
|
+
version: versionOverride ?? 'unknown',
|
|
399
|
+
message: error?.message ?? String(error),
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
if (!isPlainObject(resolved)) return fail('resolve-empty', { version: versionOverride ?? 'unknown' });
|
|
403
|
+
|
|
404
|
+
let version = versionOverride ?? 'unknown';
|
|
405
|
+
let versionSource = versionOverride ? 'injected' : null;
|
|
406
|
+
if (version === 'unknown') {
|
|
407
|
+
let list = null;
|
|
408
|
+
const bundleList = options.bundleList ?? runtime?.bundleList;
|
|
409
|
+
try {
|
|
410
|
+
if (typeof bundleList === 'function') list = bundleList();
|
|
411
|
+
else if (Array.isArray(bundleList)) list = bundleList;
|
|
412
|
+
else if (ctx && typeof ctx.get === 'function') {
|
|
413
|
+
const bundles = ctx.get('bundles');
|
|
414
|
+
if (bundles && typeof bundles.list === 'function') list = bundles.list();
|
|
415
|
+
else if (Array.isArray(bundles)) list = bundles;
|
|
416
|
+
}
|
|
417
|
+
} catch {
|
|
418
|
+
list = null;
|
|
419
|
+
}
|
|
420
|
+
if (Array.isArray(list)) {
|
|
421
|
+
const hit = list.find((item) => item && (item.name === AUTO_REVIEW_BUNDLE || item.packageName === AUTO_REVIEW_BUNDLE));
|
|
422
|
+
if (hit && typeof hit.version === 'string' && hit.version.trim() !== '') {
|
|
423
|
+
version = hit.version.trim();
|
|
424
|
+
versionSource = 'bundleList';
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (version === 'unknown') {
|
|
429
|
+
// 本机同步来源(§4.2 证据:asar 内 auto-review package.json 3,498 B / version 0.2.3-alpha.2)。
|
|
430
|
+
const fromFs = readAutoReviewVersionSync(options);
|
|
431
|
+
if (fromFs) {
|
|
432
|
+
version = fromFs.version;
|
|
433
|
+
versionSource = fromFs.source;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
if (version === 'unknown') return fail('version-unknown', { version: 'unknown' });
|
|
437
|
+
if (version !== WAKE_CAPABILITY_VERSION) {
|
|
438
|
+
return fail('version-mismatch', { version, expected: WAKE_CAPABILITY_VERSION });
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
return {
|
|
442
|
+
ok: true,
|
|
443
|
+
mode: 'present',
|
|
444
|
+
capability: { present: true, version },
|
|
445
|
+
detail: { reason: 'ok', missing: [], versionSource: versionSource ?? 'unknown-source' },
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// ---------------------------------------------------------------------------
|
|
450
|
+
// auto-review bundle 版本:同步来源(本机实测可用的唯一确定路径)
|
|
451
|
+
// ---------------------------------------------------------------------------
|
|
452
|
+
|
|
453
|
+
const AUTO_REVIEW_PKG_REL = path.join('node_modules', '@deepseek-ai', 'dsh-experimental-auto-review', 'package.json');
|
|
454
|
+
// 缓存按「候选路径串」分键:不同 env(测试注入的假根)不会互相污染。
|
|
455
|
+
let AUTO_REVIEW_SYNC_CACHE = null;
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* 同步解析 auto-review bundle 版本(fail-closed:任何一步取不到 → null,不猜)。
|
|
459
|
+
*
|
|
460
|
+
* 来源顺序:
|
|
461
|
+
* 1) DSH_INSTALL_DIR(= <resources>/app.asar/dsh/node_modules/@deepseek-ai/dsh)的 sibling package.json
|
|
462
|
+
* —— Electron 主进程的 fs 可直接读 asar 内路径;
|
|
463
|
+
* 2) process.resourcesPath / <exe>/resources 下的 app.asar|app 运行时。
|
|
464
|
+
* 读到的 package.json 必须 name === '@deepseek-ai/dsh-experimental-auto-review' 才认。
|
|
465
|
+
*
|
|
466
|
+
* @returns {{version:string, source:string, packagePath:string}|null}
|
|
467
|
+
*/
|
|
468
|
+
export function readAutoReviewVersionSync(options = {}) {
|
|
469
|
+
const env = options.env ?? process.env ?? {};
|
|
470
|
+
const candidates = [];
|
|
471
|
+
const install = typeof env.DSH_INSTALL_DIR === 'string' ? env.DSH_INSTALL_DIR.trim() : '';
|
|
472
|
+
if (install) {
|
|
473
|
+
// install = .../app.asar/dsh/node_modules/@deepseek-ai/dsh;bundle 是其 sibling。
|
|
474
|
+
candidates.push(path.join(install, '..', 'dsh-experimental-auto-review', 'package.json'));
|
|
475
|
+
candidates.push(path.join(install, 'node_modules', '@deepseek-ai', 'dsh-experimental-auto-review', 'package.json'));
|
|
476
|
+
}
|
|
477
|
+
let resources = typeof process.resourcesPath === 'string' && process.resourcesPath !== '' ? process.resourcesPath : null;
|
|
478
|
+
if (!resources && typeof process.execPath === 'string' && process.execPath !== '') {
|
|
479
|
+
resources = path.join(path.dirname(process.execPath), 'resources');
|
|
480
|
+
}
|
|
481
|
+
if (resources) {
|
|
482
|
+
for (const sub of ['app.asar', 'app']) candidates.push(path.join(resources, sub, 'dsh', AUTO_REVIEW_PKG_REL));
|
|
483
|
+
}
|
|
484
|
+
const cacheKey = candidates.join('|');
|
|
485
|
+
if (AUTO_REVIEW_SYNC_CACHE && AUTO_REVIEW_SYNC_CACHE.key === cacheKey) return AUTO_REVIEW_SYNC_CACHE.result;
|
|
486
|
+
for (const file of candidates) {
|
|
487
|
+
try {
|
|
488
|
+
if (!fs.existsSync(file)) continue;
|
|
489
|
+
const pkg = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
490
|
+
if (pkg && pkg.name === AUTO_REVIEW_BUNDLE && typeof pkg.version === 'string' && pkg.version.trim() !== '') {
|
|
491
|
+
const result = { version: pkg.version.trim(), source: 'package.json', packagePath: file };
|
|
492
|
+
AUTO_REVIEW_SYNC_CACHE = { key: cacheKey, result };
|
|
493
|
+
return result;
|
|
494
|
+
}
|
|
495
|
+
} catch {
|
|
496
|
+
// 读不到(普通 node 无法读 asar 内部路径)→ 继续下一个候选。
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
return null;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** 清空版本缓存(测试用)。 */
|
|
503
|
+
export function resetAutoReviewVersionCache() {
|
|
504
|
+
AUTO_REVIEW_SYNC_CACHE = null;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* 异步补齐 auto-review 版本(同步来源失败时的升级通道)。
|
|
509
|
+
* 只用真实宿主契约:pluginManager.listBundles()(Remote async)。
|
|
510
|
+
*
|
|
511
|
+
* @returns {Promise<{version:string, source:string}|null>}
|
|
512
|
+
*/
|
|
513
|
+
export async function resolveAutoReviewVersionAsync(ctx, options = {}) {
|
|
514
|
+
const sync = options.version ? null : readAutoReviewVersionSync(options);
|
|
515
|
+
if (sync) return sync;
|
|
516
|
+
const injected = typeof options.version === 'string' && options.version.trim() !== '' ? options.version.trim() : null;
|
|
517
|
+
if (injected) return { version: injected, source: 'injected' };
|
|
518
|
+
const pm = options.pluginManager ?? (typeof ctx?.get === 'function' ? ctx.get('pluginManager') : null);
|
|
519
|
+
if (pm && typeof pm.listBundles === 'function') {
|
|
520
|
+
try {
|
|
521
|
+
const list = await pm.listBundles();
|
|
522
|
+
const hit = Array.isArray(list)
|
|
523
|
+
? list.find((item) => item && (item.name === AUTO_REVIEW_BUNDLE || item.packageName === AUTO_REVIEW_BUNDLE))
|
|
524
|
+
: null;
|
|
525
|
+
if (hit && typeof hit.version === 'string' && hit.version.trim() !== '') {
|
|
526
|
+
return { version: hit.version.trim(), source: 'pluginManager.listBundles' };
|
|
527
|
+
}
|
|
528
|
+
} catch {
|
|
529
|
+
// 异步通道失败 → 仍按 unknown fail-closed。
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
return null;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// ---------------------------------------------------------------------------
|
|
536
|
+
// 配置归一化(§6.4:越界只可收紧;clamp + warn + 审计 configClamps)
|
|
537
|
+
// ---------------------------------------------------------------------------
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* 归一化 `hardgate.wake.*`(raw passthrough,与 proactive/handoff 同法;153 节点锁不变)。
|
|
541
|
+
* 越界一律 clamp 到「更保守」的边界并收集 warnings / clamps(下次 run 写审计)。
|
|
542
|
+
*/
|
|
543
|
+
export function normalizeWakeConfig(raw = {}, options = {}) {
|
|
544
|
+
const warn = typeof options.warn === 'function' ? options.warn : () => {};
|
|
545
|
+
const src = isPlainObject(raw) ? raw : {};
|
|
546
|
+
const warnings = [];
|
|
547
|
+
const clamps = [];
|
|
548
|
+
const note = (message, extra = {}) => {
|
|
549
|
+
const entry = { message, ...extra };
|
|
550
|
+
warnings.push(entry);
|
|
551
|
+
warn(`[longlive] hardgate.wake: ${message}`);
|
|
552
|
+
};
|
|
553
|
+
const clampInt = (key, fallback, min, max) => {
|
|
554
|
+
if (src[key] === undefined) return fallback;
|
|
555
|
+
const value = Number(src[key]);
|
|
556
|
+
if (!Number.isFinite(value)) {
|
|
557
|
+
note(`${key} 不是数字,使用默认 ${fallback}`, { key, from: src[key], to: fallback });
|
|
558
|
+
return fallback;
|
|
559
|
+
}
|
|
560
|
+
const floored = Math.floor(value);
|
|
561
|
+
const clamped = Math.min(max, Math.max(min, floored));
|
|
562
|
+
if (clamped !== floored) {
|
|
563
|
+
note(`${key}=${floored} 超出 ${min}..${max},已钳制为 ${clamped}`, { key, from: floored, to: clamped });
|
|
564
|
+
clamps.push({ key, from: floored, to: clamped, rule: `${min}..${max}` });
|
|
565
|
+
}
|
|
566
|
+
return clamped;
|
|
567
|
+
};
|
|
568
|
+
|
|
569
|
+
// triggers:五类只可删,不可加未知种类。
|
|
570
|
+
let triggers = [...WAKE_DEFAULTS.triggers];
|
|
571
|
+
if (src.triggers !== undefined) {
|
|
572
|
+
if (!Array.isArray(src.triggers)) {
|
|
573
|
+
note('triggers 不是数组,使用默认五类', { key: 'triggers' });
|
|
574
|
+
} else {
|
|
575
|
+
const unknown = src.triggers.filter((item) => !WAKE_KINDS.includes(item));
|
|
576
|
+
if (unknown.length > 0) note(`triggers 含未知触发源 ${unknown.join(',')},已忽略`, { key: 'triggers' });
|
|
577
|
+
triggers = src.triggers.filter((item) => WAKE_KINDS.includes(item));
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// allowTools:只能在默认白名单上追加;拒绝表优先,run_code/PTC 永不许进。
|
|
582
|
+
const allowTools = [...WAKE_DEFAULTS.allowTools];
|
|
583
|
+
if (src.allowTools !== undefined) {
|
|
584
|
+
if (!Array.isArray(src.allowTools)) {
|
|
585
|
+
note('allowTools 不是数组,使用默认白名单', { key: 'allowTools' });
|
|
586
|
+
} else {
|
|
587
|
+
for (const name of src.allowTools) {
|
|
588
|
+
if (typeof name !== 'string' || name.trim() === '') continue;
|
|
589
|
+
const tool = name.trim();
|
|
590
|
+
if (WAKE_TOOL_DENY.includes(tool)) {
|
|
591
|
+
note(`allowTools 里的 ${tool} 在被拒表内(拒绝表优先),已忽略`, { key: 'allowTools', tool });
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
if (!allowTools.includes(tool)) allowTools.push(tool);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
if (!allowTools.includes(WAKE_TOOL_NAME)) allowTools.push(WAKE_TOOL_NAME);
|
|
599
|
+
if (allowTools.includes('run_code')) {
|
|
600
|
+
const index = allowTools.indexOf('run_code');
|
|
601
|
+
allowTools.splice(index, 1);
|
|
602
|
+
note('run_code 不能进入后台会话工具集(auto-review 不审 run_code 外层调用),已剔除', { key: 'allowTools' });
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// toolExclude:只能追加(拒绝表默认项不可移除)。
|
|
606
|
+
const denyTools = [...WAKE_DEFAULTS.denyTools];
|
|
607
|
+
if (src.toolExclude !== undefined) {
|
|
608
|
+
if (!Array.isArray(src.toolExclude)) {
|
|
609
|
+
note('toolExclude 不是数组,已忽略', { key: 'toolExclude' });
|
|
610
|
+
} else {
|
|
611
|
+
for (const name of src.toolExclude) {
|
|
612
|
+
if (typeof name !== 'string' || name.trim() === '') continue;
|
|
613
|
+
const tool = name.trim();
|
|
614
|
+
if (!denyTools.includes(tool)) denyTools.push(tool);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
const preset = typeof src.preset === 'string' && src.preset.trim() !== '' ? src.preset.trim() : WAKE_DEFAULTS.preset;
|
|
620
|
+
const approvalPolicy = typeof src.approvalPolicy === 'string' && src.approvalPolicy.trim() !== ''
|
|
621
|
+
? src.approvalPolicy.trim()
|
|
622
|
+
: WAKE_DEFAULTS.approvalPolicy;
|
|
623
|
+
if (preset !== 'auto') {
|
|
624
|
+
note(`preset=${preset} 不是 auto:后台会话不会被 auto-review 审查,已钳制为 auto`, { key: 'preset', from: preset, to: 'auto' });
|
|
625
|
+
clamps.push({ key: 'preset', from: preset, to: 'auto', rule: 'auto' });
|
|
626
|
+
}
|
|
627
|
+
if (approvalPolicy !== 'never') {
|
|
628
|
+
note(`approvalPolicy=${approvalPolicy} 不是 never:无人应答会挂死,已钳制为 never`, { key: 'approvalPolicy', from: approvalPolicy, to: 'never' });
|
|
629
|
+
clamps.push({ key: 'approvalPolicy', from: approvalPolicy, to: 'never', rule: 'never' });
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
const cfg = {
|
|
633
|
+
enabled: src.enabled === true,
|
|
634
|
+
triggers,
|
|
635
|
+
maxPerDay: clampInt('maxPerDay', WAKE_DEFAULTS.maxPerDay, 1, WAKE_BOUNDS.queueMax > 0 ? 20 : 20),
|
|
636
|
+
cooldownSeconds: clampInt('cooldownSeconds', WAKE_DEFAULTS.cooldownSeconds, 600, 86400),
|
|
637
|
+
timeoutSeconds: clampInt('timeoutSeconds', WAKE_DEFAULTS.timeoutSeconds, 10, 180),
|
|
638
|
+
ticketTtlHours: clampInt('ticketTtlHours', WAKE_DEFAULTS.ticketTtlHours, 1, 24),
|
|
639
|
+
queueMax: clampInt('queueMax', WAKE_DEFAULTS.queueMax, 1, 200),
|
|
640
|
+
maxFilesPerRun: clampInt('maxFilesPerRun', WAKE_DEFAULTS.maxFilesPerRun, 0, 3),
|
|
641
|
+
maxRounds: clampInt('maxRounds', WAKE_DEFAULTS.maxRounds, 1, 3),
|
|
642
|
+
maxOutputTokens: clampInt('maxOutputTokens', WAKE_DEFAULTS.maxOutputTokens, 500, 2000),
|
|
643
|
+
maxOutputChars: clampInt('maxOutputChars', WAKE_DEFAULTS.maxOutputChars, 1000, 8000),
|
|
644
|
+
retryMax: clampInt('retryMax', WAKE_DEFAULTS.retryMax, 0, 2),
|
|
645
|
+
preset: 'auto',
|
|
646
|
+
approvalPolicy: 'never',
|
|
647
|
+
allowTools: Object.freeze(allowTools),
|
|
648
|
+
denyTools: Object.freeze(denyTools),
|
|
649
|
+
toolExclude: Object.freeze(denyTools),
|
|
650
|
+
runOnStart: src.runOnStart !== false,
|
|
651
|
+
warnings,
|
|
652
|
+
clamps,
|
|
653
|
+
};
|
|
654
|
+
return cfg;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// ---------------------------------------------------------------------------
|
|
658
|
+
// 路径与门事件
|
|
659
|
+
// ---------------------------------------------------------------------------
|
|
660
|
+
|
|
661
|
+
/** 六类文件的绝对路径(input 可以是 memoryRoot 或已解析的 paths,幂等)。 */
|
|
662
|
+
export function wakePaths(memoryRoot) {
|
|
663
|
+
// 数据面路径解析:传 root 字符串或 {root} 均可;已解析的 paths(root+queue+state 三键齐全)原样返回。
|
|
664
|
+
if (isPlainObject(memoryRoot) && typeof memoryRoot.root === 'string' && typeof memoryRoot.queue === 'string' && typeof memoryRoot.state === 'string') return memoryRoot;
|
|
665
|
+
const rootInput = isPlainObject(memoryRoot) && typeof memoryRoot.root === 'string' ? memoryRoot.root : memoryRoot;
|
|
666
|
+
const root = path.resolve(String(rootInput));
|
|
667
|
+
const dir = path.join(root, WAKE_DATA_REL);
|
|
668
|
+
return {
|
|
669
|
+
root,
|
|
670
|
+
dir,
|
|
671
|
+
queue: path.join(root, WAKE_QUEUE_REL),
|
|
672
|
+
pending: path.join(root, WAKE_PENDING_REL),
|
|
673
|
+
autoAuthz: path.join(root, WAKE_AUTHZ_REL),
|
|
674
|
+
runsDir: path.join(root, WAKE_RUNS_REL),
|
|
675
|
+
panel: path.join(root, WAKE_PANEL_REL),
|
|
676
|
+
state: path.join(root, WAKE_STATE_REL),
|
|
677
|
+
gateDir: path.join(root, '.longlive', 'hardgate'),
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
function asPaths(input) {
|
|
682
|
+
return wakePaths(input);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
function rootOf(input) {
|
|
686
|
+
return asPaths(input).root;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/** 写 gate-log(链式日志;写不了不打断主流程)。 */
|
|
690
|
+
function writeGate(input, event, fields = {}) {
|
|
691
|
+
const root = rootOf(input);
|
|
692
|
+
try {
|
|
693
|
+
return appendGateLog(root, {
|
|
694
|
+
gate: event,
|
|
695
|
+
decision: fields.decision ?? 'ok',
|
|
696
|
+
reason: typeof fields.reason === 'string' ? fields.reason : '',
|
|
697
|
+
...(typeof fields.code === 'string' && fields.code !== '' ? { code: fields.code } : {}),
|
|
698
|
+
evidence: Array.isArray(fields.evidence) ? fields.evidence.map(String) : [],
|
|
699
|
+
});
|
|
700
|
+
} catch {
|
|
701
|
+
return null;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
function safeGate(input, event, fields = {}) {
|
|
706
|
+
try {
|
|
707
|
+
writeGate(input, event, fields);
|
|
708
|
+
} catch {
|
|
709
|
+
// 门日志不可写不影响唤醒本身(fail-closed 的可见性由 panel 兜底)。
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// ---------------------------------------------------------------------------
|
|
714
|
+
// 状态 / 面板(≤4 KiB / ≤64 KiB;原子写 + 超限收缩)
|
|
715
|
+
// ---------------------------------------------------------------------------
|
|
716
|
+
|
|
717
|
+
function defaultWakeState() {
|
|
718
|
+
return {
|
|
719
|
+
schema: WAKE_SCHEMAS.state,
|
|
720
|
+
enabled: false,
|
|
721
|
+
capability: null,
|
|
722
|
+
cooldownUntil: null,
|
|
723
|
+
dayKey: null,
|
|
724
|
+
dayCount: 0,
|
|
725
|
+
running: null,
|
|
726
|
+
lastPruneAt: null,
|
|
727
|
+
lastDailyAt: null,
|
|
728
|
+
seq: 0,
|
|
729
|
+
lastTicketId: null,
|
|
730
|
+
totals: { runs: 0, escalated: 0, failed: 0 },
|
|
731
|
+
lastRun: null,
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
/** 读 wake-state.json(坏文件 → 默认状态,不抛)。 */
|
|
736
|
+
export function readWakeState(input) {
|
|
737
|
+
const paths = asPaths(input);
|
|
738
|
+
const raw = readJson(paths.state, null);
|
|
739
|
+
const base = defaultWakeState();
|
|
740
|
+
if (!isPlainObject(raw)) return base;
|
|
741
|
+
return {
|
|
742
|
+
...base,
|
|
743
|
+
...raw,
|
|
744
|
+
schema: WAKE_SCHEMAS.state,
|
|
745
|
+
totals: { ...base.totals, ...(isPlainObject(raw.totals) ? raw.totals : {}) },
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/** 写 wake-state.json(≤4 KiB;超限先丢可选字段,再失败则 gate-log fail)。 */
|
|
750
|
+
export function writeWakeState(input, state) {
|
|
751
|
+
const paths = asPaths(input);
|
|
752
|
+
const value = { ...defaultWakeState(), ...(isPlainObject(state) ? state : {}), schema: WAKE_SCHEMAS.state };
|
|
753
|
+
let text = `${JSON.stringify(value, null, 2)}\n`;
|
|
754
|
+
if (Buffer.byteLength(text, 'utf8') > WAKE_BOUNDS.stateMaxBytes) {
|
|
755
|
+
// 超限:先丢可选字段(lastRun / capability.detail / totals 之外的扩展),仍超则只留骨架。
|
|
756
|
+
const slim = {
|
|
757
|
+
schema: value.schema,
|
|
758
|
+
enabled: value.enabled === true,
|
|
759
|
+
capability: value.capability ? { present: value.capability.present === true, version: value.capability.version ?? 'unknown', code: value.capability.code ?? null } : null,
|
|
760
|
+
cooldownUntil: value.cooldownUntil ?? null,
|
|
761
|
+
dayKey: value.dayKey ?? null,
|
|
762
|
+
dayCount: Number(value.dayCount ?? 0),
|
|
763
|
+
running: value.running ?? null,
|
|
764
|
+
lastDailyAt: value.lastDailyAt ?? null,
|
|
765
|
+
seq: Number(value.seq ?? 0),
|
|
766
|
+
lastTicketId: value.lastTicketId ?? null,
|
|
767
|
+
};
|
|
768
|
+
text = `${JSON.stringify(slim, null, 2)}\n`;
|
|
769
|
+
if (Buffer.byteLength(text, 'utf8') > WAKE_BOUNDS.stateMaxBytes) {
|
|
770
|
+
safeGate(paths, GATE_EVENTS.WAKE_FAIL, { decision: 'fail', code: WAKE_CODES.STORE_WRITE_FAILED, reason: `wake-state 超过 ${WAKE_BOUNDS.stateMaxBytes} 字节` });
|
|
771
|
+
throw wakeError(WAKE_CODES.STORE_WRITE_FAILED, `wake-state 超过 ${WAKE_BOUNDS.stateMaxBytes} 字节(已拒绝写)`);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
writeFileAtomic(paths.state, text);
|
|
775
|
+
return value;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
function defaultWakePanel() {
|
|
779
|
+
return {
|
|
780
|
+
schema: WAKE_SCHEMAS.panel,
|
|
781
|
+
updatedAt: null,
|
|
782
|
+
enabled: false,
|
|
783
|
+
capability: { present: false, version: 'unknown', code: null },
|
|
784
|
+
queue: { total: 0, due: 0, byKind: {} },
|
|
785
|
+
pendingCount: 0,
|
|
786
|
+
lastRun: null,
|
|
787
|
+
runsTotal: 0,
|
|
788
|
+
bounds: {
|
|
789
|
+
queueMax: WAKE_BOUNDS.queueMax,
|
|
790
|
+
pendingMax: WAKE_BOUNDS.pendingMax,
|
|
791
|
+
runsMax: WAKE_BOUNDS.runsMax,
|
|
792
|
+
authzMaxLines: WAKE_BOUNDS.authzMaxLines,
|
|
793
|
+
panelMaxBytes: WAKE_BOUNDS.panelMaxBytes,
|
|
794
|
+
stateMaxBytes: WAKE_BOUNDS.stateMaxBytes,
|
|
795
|
+
},
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/** 读 panel.json(不存在 → null,不抛)。 */
|
|
800
|
+
export function readWakePanel(input) {
|
|
801
|
+
const raw = readJson(asPaths(input).panel, null);
|
|
802
|
+
return isPlainObject(raw) ? raw : null;
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/** 写 panel.json(≤64 KiB:超限依次收缩 queue/lastRun,再失败则 gate-log warn)。 */
|
|
806
|
+
export function writeWakePanel(input, panel) {
|
|
807
|
+
const paths = asPaths(input);
|
|
808
|
+
const value = { ...defaultWakePanel(), ...(isPlainObject(panel) ? panel : {}), schema: WAKE_SCHEMAS.panel };
|
|
809
|
+
let text = `${JSON.stringify(value, null, 2)}\n`;
|
|
810
|
+
if (Buffer.byteLength(text, 'utf8') > WAKE_BOUNDS.panelMaxBytes) {
|
|
811
|
+
const slim = {
|
|
812
|
+
...value,
|
|
813
|
+
lastRun: value.lastRun ? { runId: value.lastRun.runId ?? null, status: value.lastRun.status ?? null, code: value.lastRun.code ?? null, at: value.lastRun.at ?? null } : null,
|
|
814
|
+
queue: { total: value.queue?.total ?? 0, due: value.queue?.due ?? 0, byKind: {} },
|
|
815
|
+
};
|
|
816
|
+
text = `${JSON.stringify(slim, null, 2)}\n`;
|
|
817
|
+
if (Buffer.byteLength(text, 'utf8') > WAKE_BOUNDS.panelMaxBytes) {
|
|
818
|
+
const minimal = { schema: value.schema, updatedAt: value.updatedAt, enabled: value.enabled === true, capability: value.capability, queue: { total: value.queue?.total ?? 0, due: value.queue?.due ?? 0, byKind: {} }, pendingCount: value.pendingCount ?? 0, lastRun: null, runsTotal: value.runsTotal ?? 0 };
|
|
819
|
+
text = `${JSON.stringify(minimal, null, 2)}\n`;
|
|
820
|
+
safeGate(paths, GATE_EVENTS.WAKE_FAIL, { decision: 'warn', code: 'E_WAKE_PANEL_OVERSIZE', reason: `panel 超过 ${WAKE_BOUNDS.panelMaxBytes} 字节,已收缩为 counts` });
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
writeFileAtomic(paths.panel, text);
|
|
824
|
+
return value;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/** 由队列/待批/runs 重建 panel(写盘;daily reconcile 与每次 run 结束时调用)。 */
|
|
828
|
+
export function buildWakePanel(input, options = {}) {
|
|
829
|
+
const paths = asPaths(input);
|
|
830
|
+
const now = nowDateOf(options.now ?? options);
|
|
831
|
+
const queue = readQueue(paths);
|
|
832
|
+
const pending = readPending(paths);
|
|
833
|
+
const runs = readRunRecords(paths, { limit: 1 });
|
|
834
|
+
const state = readWakeState(paths);
|
|
835
|
+
const byKind = {};
|
|
836
|
+
let due = 0;
|
|
837
|
+
for (const row of queue) {
|
|
838
|
+
if (!['queued', 'failed'].includes(row.status)) continue;
|
|
839
|
+
if (row.status === 'failed' && Number(row.retries ?? 0) >= Number(options.retryMax ?? WAKE_DEFAULTS.retryMax)) continue;
|
|
840
|
+
bumpCount(byKind, String(row.kind ?? 'unknown'));
|
|
841
|
+
if (Date.parse(row.expiresAt) > now.getTime()) due += 1;
|
|
842
|
+
}
|
|
843
|
+
const total = queue.filter((row) => ['queued', 'failed', 'running'].includes(row.status)).length;
|
|
844
|
+
const lastRun = state.lastRun ?? (runs[0] ? { runId: runs[0].runId, status: runs[0].status, code: runs[0].code ?? null, at: runs[0].finishedAt ?? null } : null);
|
|
845
|
+
return {
|
|
846
|
+
...defaultWakePanel(),
|
|
847
|
+
updatedAt: isoOf(now),
|
|
848
|
+
enabled: options.enabled === true,
|
|
849
|
+
capability: options.capability ?? state.capability ?? defaultWakePanel().capability,
|
|
850
|
+
queue: { total, due, byKind },
|
|
851
|
+
pendingCount: pending.length,
|
|
852
|
+
lastRun,
|
|
853
|
+
runsTotal: runs.length > 0 ? (state.totals?.runs ?? runs.length) : 0,
|
|
854
|
+
bounds: defaultWakePanel().bounds,
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
/** 落 panel(build + write + 返回面板)。 */
|
|
859
|
+
export function refreshWakePanel(input, options = {}) {
|
|
860
|
+
const panel = buildWakePanel(input, options);
|
|
861
|
+
try {
|
|
862
|
+
writeWakePanel(input, panel);
|
|
863
|
+
} catch (error) {
|
|
864
|
+
safeGate(input, GATE_EVENTS.WAKE_FAIL, { decision: 'fail', code: error?.code ?? WAKE_CODES.STORE_WRITE_FAILED, reason: error?.message ?? String(error) });
|
|
865
|
+
}
|
|
866
|
+
return panel;
|
|
867
|
+
}
|
|
868
|
+
/** 本草案认识的提议种类(新增种类必须同时加规则,否则 fail-closed 拒绝)。 */
|
|
869
|
+
export const AUTHZ_KINDS = Object.freeze([
|
|
870
|
+
'jsonl_append',
|
|
871
|
+
'card_mark',
|
|
872
|
+
'card_create',
|
|
873
|
+
'card_delete',
|
|
874
|
+
'tombstone',
|
|
875
|
+
'rules_write',
|
|
876
|
+
]);
|
|
877
|
+
|
|
878
|
+
export const AUTHZ_CODES = Object.freeze({
|
|
879
|
+
RULES_UNAVAILABLE: 'E_WAKE_AUTHZ_RULES_UNAVAILABLE',
|
|
880
|
+
PROPOSAL_INVALID: 'E_WAKE_AUTHZ_PROPOSAL_INVALID',
|
|
881
|
+
EVIDENCE_MISSING: 'E_WAKE_AUTHZ_EVIDENCE_MISSING',
|
|
882
|
+
EVIDENCE_SHA_MISMATCH: 'E_WAKE_AUTHZ_EVIDENCE_SHA_MISMATCH',
|
|
883
|
+
BEFORE_SHA_MISMATCH: 'E_WAKE_AUTHZ_BEFORE_SHA_MISMATCH',
|
|
884
|
+
TARGET_OUTSIDE_ROOT: 'E_WAKE_AUTHZ_TARGET_OUTSIDE_ROOT',
|
|
885
|
+
TARGET_NOT_ALLOWED: 'E_WAKE_AUTHZ_TARGET_NOT_ALLOWED',
|
|
886
|
+
EFFECTOR_UNSUPPORTED: 'E_WAKE_AUTHZ_EFFECTOR_UNSUPPORTED',
|
|
887
|
+
BLAST_RADIUS: 'E_WAKE_AUTHZ_BLAST_RADIUS',
|
|
888
|
+
QUOTA_EXCEEDED: 'E_WAKE_AUTHZ_QUOTA_EXCEEDED',
|
|
889
|
+
RULE_DENY: 'E_WAKE_AUTHZ_RULE_DENY',
|
|
890
|
+
NO_RULE: 'E_WAKE_AUTHZ_NO_RULE',
|
|
891
|
+
NOT_REVERSIBLE: 'E_WAKE_AUTHZ_NOT_REVERSIBLE',
|
|
892
|
+
WRITE_FAILED: 'E_WAKE_AUTHZ_WRITE_FAILED',
|
|
893
|
+
});
|
|
894
|
+
|
|
895
|
+
export const AUTHZ_RULES_VERSION = 'wake-authz-rules-v1.0-draft';
|
|
896
|
+
|
|
897
|
+
/**
|
|
898
|
+
* 冻结规则表草案(AUTO / ESCALATE / DENY 三态)。
|
|
899
|
+
* quota 的 perRun / perDay 是规则级上限,调用方另有一层全局上限。
|
|
900
|
+
*/
|
|
901
|
+
export const DEFAULT_RULES = Object.freeze([
|
|
902
|
+
{
|
|
903
|
+
ruleId: 'AUTO-1-forget-historical',
|
|
904
|
+
kind: 'card_mark',
|
|
905
|
+
match: { targetPrefix: 'topics/', ticketKinds: ['forget_historical'], maxCards: 1, maxFiles: 1 },
|
|
906
|
+
reversibleRequired: true,
|
|
907
|
+
evidenceRequired: ['path', 'sha'],
|
|
908
|
+
verdict: 'AUTO',
|
|
909
|
+
quota: { perRun: 2, perDay: 10 },
|
|
910
|
+
},
|
|
911
|
+
{
|
|
912
|
+
ruleId: 'AUTO-2-conflict-resolved',
|
|
913
|
+
kind: 'card_mark',
|
|
914
|
+
match: { targetPrefix: 'topics/', ticketKinds: ['conflict_resolved'], maxCards: 1, maxFiles: 1 },
|
|
915
|
+
reversibleRequired: true,
|
|
916
|
+
evidenceRequired: ['path', 'sha'],
|
|
917
|
+
verdict: 'AUTO',
|
|
918
|
+
quota: { perRun: 2, perDay: 10 },
|
|
919
|
+
},
|
|
920
|
+
{
|
|
921
|
+
ruleId: 'AUTO-3-recall-feedback',
|
|
922
|
+
kind: 'jsonl_append',
|
|
923
|
+
match: { targetPrefix: '.longlive/', ticketKinds: ['recall_feedback'], maxCards: 0, maxFiles: 1 },
|
|
924
|
+
reversibleRequired: true,
|
|
925
|
+
evidenceRequired: ['path'],
|
|
926
|
+
verdict: 'AUTO',
|
|
927
|
+
quota: { perRun: 2, perDay: 20 },
|
|
928
|
+
},
|
|
929
|
+
{
|
|
930
|
+
ruleId: 'ESCALATE-1-procedure-card',
|
|
931
|
+
kind: 'card_create',
|
|
932
|
+
match: { targetPrefix: 'procedures/', maxCards: 1, maxFiles: 1 },
|
|
933
|
+
reversibleRequired: true,
|
|
934
|
+
evidenceRequired: ['path', 'sha'],
|
|
935
|
+
verdict: 'ESCALATE',
|
|
936
|
+
quota: { perRun: 1, perDay: 3 },
|
|
937
|
+
},
|
|
938
|
+
{
|
|
939
|
+
ruleId: 'ESCALATE-2-promise-done',
|
|
940
|
+
kind: 'card_mark',
|
|
941
|
+
match: { targetPrefix: 'topics/', ticketKinds: ['promise_done'], maxCards: 1, maxFiles: 1 },
|
|
942
|
+
reversibleRequired: true,
|
|
943
|
+
evidenceRequired: ['path', 'sha'],
|
|
944
|
+
verdict: 'ESCALATE',
|
|
945
|
+
quota: { perRun: 1, perDay: 5 },
|
|
946
|
+
},
|
|
947
|
+
{
|
|
948
|
+
ruleId: 'DENY-1-card-delete',
|
|
949
|
+
kind: 'card_delete',
|
|
950
|
+
match: {},
|
|
951
|
+
reversibleRequired: false,
|
|
952
|
+
evidenceRequired: [],
|
|
953
|
+
verdict: 'DENY',
|
|
954
|
+
quota: { perRun: 0, perDay: 0 },
|
|
955
|
+
},
|
|
956
|
+
{
|
|
957
|
+
ruleId: 'DENY-2-tombstone',
|
|
958
|
+
kind: 'tombstone',
|
|
959
|
+
match: {},
|
|
960
|
+
reversibleRequired: false,
|
|
961
|
+
evidenceRequired: [],
|
|
962
|
+
verdict: 'DENY',
|
|
963
|
+
quota: { perRun: 0, perDay: 0 },
|
|
964
|
+
},
|
|
965
|
+
{
|
|
966
|
+
ruleId: 'DENY-3-rules-write',
|
|
967
|
+
kind: 'rules_write',
|
|
968
|
+
match: {},
|
|
969
|
+
reversibleRequired: false,
|
|
970
|
+
evidenceRequired: [],
|
|
971
|
+
verdict: 'DENY',
|
|
972
|
+
quota: { perRun: 0, perDay: 0 },
|
|
973
|
+
},
|
|
974
|
+
]);
|
|
975
|
+
|
|
976
|
+
/** 本草案允许 jsonl_append 落盘的相对前缀(其余前缀一律 ESCALATE)。 */
|
|
977
|
+
const ALLOWED_WRITE_PREFIXES = Object.freeze(['.longlive/', 'journal/']);
|
|
978
|
+
|
|
979
|
+
function sha256(buf) {
|
|
980
|
+
return createHash('sha256').update(buf).digest('hex');
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
export function sha256Text(text) {
|
|
984
|
+
return sha256(Buffer.from(String(text), 'utf8'));
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
function sha256FileSync(file) {
|
|
988
|
+
return sha256(bufSafeRead(file));
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
function bufSafeRead(file) {
|
|
992
|
+
try {
|
|
993
|
+
return fs.readFileSync(file);
|
|
994
|
+
} catch {
|
|
995
|
+
return null;
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
function err(code, message, detail) {
|
|
1000
|
+
const e = new Error(message);
|
|
1001
|
+
e.code = code;
|
|
1002
|
+
if (detail !== undefined) e.detail = detail;
|
|
1003
|
+
return e;
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
/** 解析并校验 target.file 是否落在 root 内;越界一律拒绝(不跟 symlink 猜测)。 */
|
|
1007
|
+
function resolveTarget(root, rel) {
|
|
1008
|
+
if (typeof rel !== 'string' || rel.length === 0) {
|
|
1009
|
+
throw err(AUTHZ_CODES.PROPOSAL_INVALID, 'proposal.target.file 必须是非空相对路径');
|
|
1010
|
+
}
|
|
1011
|
+
if (path.isAbsolute(rel)) {
|
|
1012
|
+
const abs = path.resolve(rel);
|
|
1013
|
+
if (!isInside(root, abs)) throw err(AUTHZ_CODES.TARGET_OUTSIDE_ROOT, `absolute target 越出记忆根: ${rel}`);
|
|
1014
|
+
return { abs, rel: path.relative(root, abs).split(path.sep).join('/') };
|
|
1015
|
+
}
|
|
1016
|
+
const abs = path.resolve(root, rel);
|
|
1017
|
+
if (!isInside(root, abs)) throw err(AUTHZ_CODES.TARGET_OUTSIDE_ROOT, `target 越出记忆根: ${rel}`);
|
|
1018
|
+
return { abs, rel: rel.split(path.sep).join('/') };
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
export function isInside(root, abs) {
|
|
1022
|
+
const rel = path.relative(path.resolve(root), path.resolve(abs));
|
|
1023
|
+
return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
function normalizeProposal(proposal) {
|
|
1027
|
+
if (!proposal || typeof proposal !== 'object' || Array.isArray(proposal)) {
|
|
1028
|
+
throw err(AUTHZ_CODES.PROPOSAL_INVALID, 'proposal 必须是普通对象');
|
|
1029
|
+
}
|
|
1030
|
+
const kind = String(proposal.kind ?? '');
|
|
1031
|
+
if (!AUTHZ_KINDS.includes(kind)) {
|
|
1032
|
+
throw err(AUTHZ_CODES.PROPOSAL_INVALID, `未知提议种类: ${kind || '(空)'}`);
|
|
1033
|
+
}
|
|
1034
|
+
const id = typeof proposal.id === 'string' && proposal.id ? proposal.id : `prop-${randomUUID()}`;
|
|
1035
|
+
const targetFile = proposal?.target?.file;
|
|
1036
|
+
if (typeof targetFile !== 'string' || targetFile.length === 0) {
|
|
1037
|
+
throw err(AUTHZ_CODES.PROPOSAL_INVALID, 'proposal.target.file 缺失');
|
|
1038
|
+
}
|
|
1039
|
+
const evidence = Array.isArray(proposal.evidence) ? proposal.evidence : [];
|
|
1040
|
+
return {
|
|
1041
|
+
...proposal,
|
|
1042
|
+
id,
|
|
1043
|
+
kind,
|
|
1044
|
+
target: { ...(proposal.target ?? {}), file: targetFile },
|
|
1045
|
+
evidence,
|
|
1046
|
+
params: proposal.params ?? {},
|
|
1047
|
+
reversible: proposal.reversible === true,
|
|
1048
|
+
blast_radius: {
|
|
1049
|
+
cards: Number.isFinite(proposal?.blast_radius?.cards) ? proposal.blast_radius.cards : 0,
|
|
1050
|
+
files: Number.isFinite(proposal?.blast_radius?.files) ? proposal.blast_radius.files : 1,
|
|
1051
|
+
},
|
|
1052
|
+
};
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
/** 命中第一条 kind/targetPrefix/ticketKinds 都匹配的规则;无规则 → null。 */
|
|
1056
|
+
function matchRule(proposal, rules) {
|
|
1057
|
+
for (const rule of rules) {
|
|
1058
|
+
if (!rule || typeof rule !== 'object') continue;
|
|
1059
|
+
if (rule.kind !== proposal.kind) continue;
|
|
1060
|
+
const m = rule.match ?? {};
|
|
1061
|
+
if (typeof m.targetPrefix === 'string' && m.targetPrefix.length > 0
|
|
1062
|
+
&& !proposal.target.rel.startsWith(m.targetPrefix)) continue;
|
|
1063
|
+
if (Array.isArray(m.ticketKinds) && m.ticketKinds.length > 0
|
|
1064
|
+
&& !m.ticketKinds.includes(String(proposal.ticketKind ?? ''))) continue;
|
|
1065
|
+
return rule;
|
|
1066
|
+
}
|
|
1067
|
+
return null;
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
function evidenceIssues(proposal, root, requirement) {
|
|
1071
|
+
const issues = [];
|
|
1072
|
+
const needPath = requirement.includes('path');
|
|
1073
|
+
const needSha = requirement.includes('sha');
|
|
1074
|
+
for (const item of proposal.evidence) {
|
|
1075
|
+
if (!item || typeof item !== 'object' || typeof item.path !== 'string' || item.path.length === 0) {
|
|
1076
|
+
issues.push({ code: AUTHZ_CODES.EVIDENCE_MISSING, reason: 'evidence[].path 缺失' });
|
|
1077
|
+
continue;
|
|
1078
|
+
}
|
|
1079
|
+
const abs = path.isAbsolute(item.path) ? path.resolve(item.path) : path.resolve(root, item.path);
|
|
1080
|
+
if (!isInside(root, abs)) {
|
|
1081
|
+
issues.push({ code: AUTHZ_CODES.TARGET_OUTSIDE_ROOT, reason: `evidence 越出记忆根: ${item.path}` });
|
|
1082
|
+
continue;
|
|
1083
|
+
}
|
|
1084
|
+
const buf = bufSafeRead(abs);
|
|
1085
|
+
if (buf === null) {
|
|
1086
|
+
if (needPath || needSha) issues.push({ code: AUTHZ_CODES.EVIDENCE_MISSING, reason: `evidence 文件不存在: ${item.path}` });
|
|
1087
|
+
continue;
|
|
1088
|
+
}
|
|
1089
|
+
if (needSha) {
|
|
1090
|
+
if (typeof item.sha !== 'string' || !/^[0-9a-f]{64}$/i.test(item.sha)) {
|
|
1091
|
+
issues.push({ code: AUTHZ_CODES.EVIDENCE_MISSING, reason: `evidence 缺 sha: ${item.path}` });
|
|
1092
|
+
} else if (sha256(buf) !== item.sha.toLowerCase()) {
|
|
1093
|
+
issues.push({ code: AUTHZ_CODES.EVIDENCE_SHA_MISMATCH, reason: `evidence sha 不符: ${item.path}` });
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
if (proposal.evidence.length === 0 && (needPath || needSha)) {
|
|
1098
|
+
issues.push({ code: AUTHZ_CODES.EVIDENCE_MISSING, reason: '规则要求证据,但 proposal.evidence 为空' });
|
|
1099
|
+
}
|
|
1100
|
+
return issues;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
/**
|
|
1104
|
+
* 纯判定:不写盘。返回 {ok, verdict, ruleId, ruleHits, reason, code, target, evidence}。
|
|
1105
|
+
* usage = { perRun: {ruleId: n}, perDay: {ruleId: n} }。
|
|
1106
|
+
*/
|
|
1107
|
+
export function authorize(proposal, options = {}) {
|
|
1108
|
+
const rules = options.rules ?? DEFAULT_RULES;
|
|
1109
|
+
if (!Array.isArray(rules) || rules.length === 0) {
|
|
1110
|
+
return {
|
|
1111
|
+
ok: false,
|
|
1112
|
+
verdict: 'DENY',
|
|
1113
|
+
ruleId: null,
|
|
1114
|
+
ruleHits: [],
|
|
1115
|
+
code: AUTHZ_CODES.RULES_UNAVAILABLE,
|
|
1116
|
+
reason: '冻结规则表不可用(fail-closed:不执行)',
|
|
1117
|
+
};
|
|
1118
|
+
}
|
|
1119
|
+
let p;
|
|
1120
|
+
try {
|
|
1121
|
+
p = normalizeProposal(proposal);
|
|
1122
|
+
} catch (e) {
|
|
1123
|
+
return { ok: false, verdict: 'DENY', ruleId: null, ruleHits: [], code: e.code ?? AUTHZ_CODES.PROPOSAL_INVALID, reason: e.message };
|
|
1124
|
+
}
|
|
1125
|
+
// target.rel 用于规则匹配与写入范围判断;先解析,越界即 DENY。
|
|
1126
|
+
let target;
|
|
1127
|
+
try {
|
|
1128
|
+
target = resolveTarget(options.root ?? '', p.target.file);
|
|
1129
|
+
} catch (e) {
|
|
1130
|
+
return { ok: false, verdict: 'DENY', ruleId: null, ruleHits: [], code: e.code ?? AUTHZ_CODES.TARGET_OUTSIDE_ROOT, reason: e.message, proposal: p };
|
|
1131
|
+
}
|
|
1132
|
+
const rel = { ...p, target: { ...p.target, rel: target.rel, abs: target.abs } };
|
|
1133
|
+
const rule = matchRule(rel, rules);
|
|
1134
|
+
if (!rule) {
|
|
1135
|
+
return { ok: false, verdict: 'DENY', ruleId: null, ruleHits: [], code: AUTHZ_CODES.NO_RULE, reason: `没有匹配 ${p.kind} 的冻结规则(fail-closed)`, proposal: rel };
|
|
1136
|
+
}
|
|
1137
|
+
const ruleHits = [{ ruleId: rule.ruleId, verdict: rule.verdict }];
|
|
1138
|
+
if (rule.verdict === 'DENY') {
|
|
1139
|
+
return { ok: true, verdict: 'DENY', ruleId: rule.ruleId, ruleHits, code: AUTHZ_CODES.RULE_DENY, reason: `规则 ${rule.ruleId} 明确拒绝`, proposal: rel };
|
|
1140
|
+
}
|
|
1141
|
+
if (rule.verdict === 'ESCALATE') {
|
|
1142
|
+
return { ok: true, verdict: 'ESCALATE', ruleId: rule.ruleId, ruleHits, code: null, reason: `规则 ${rule.ruleId} 要求人工确认`, proposal: rel };
|
|
1143
|
+
}
|
|
1144
|
+
// AUTO:可逆 + 证据 + 爆炸半径 + 额度 四关,任一不过就 ESCALATE(不静默)。
|
|
1145
|
+
if (rule.reversibleRequired && rel.reversible !== true) {
|
|
1146
|
+
return { ok: true, verdict: 'ESCALATE', ruleId: rule.ruleId, ruleHits, code: AUTHZ_CODES.NOT_REVERSIBLE, reason: `规则 ${rule.ruleId} 要求可逆写,proposal.reversible 不是 true`, proposal: rel };
|
|
1147
|
+
}
|
|
1148
|
+
const evidence = evidenceIssues(rel, options.root ?? '', rule.evidenceRequired ?? []);
|
|
1149
|
+
if (evidence.length > 0) {
|
|
1150
|
+
const first = evidence[0];
|
|
1151
|
+
return { ok: true, verdict: 'ESCALATE', ruleId: rule.ruleId, ruleHits, code: first.code, reason: `${first.reason}(升级人工)`, evidence, proposal: rel };
|
|
1152
|
+
}
|
|
1153
|
+
const maxCards = Number.isFinite(rule?.match?.maxCards) ? rule.match.maxCards : 0;
|
|
1154
|
+
const maxFiles = Number.isFinite(rule?.match?.maxFiles) ? rule.match.maxFiles : 1;
|
|
1155
|
+
if (rel.blast_radius.cards > maxCards || rel.blast_radius.files > Math.max(maxFiles, options.maxFilesPerProposal ?? 0)) {
|
|
1156
|
+
return { ok: true, verdict: 'ESCALATE', ruleId: rule.ruleId, ruleHits, code: AUTHZ_CODES.BLAST_RADIUS, reason: `爆炸半径超限(cards ${rel.blast_radius.cards}/${maxCards},files ${rel.blast_radius.files})`, proposal: rel };
|
|
1157
|
+
}
|
|
1158
|
+
const perRun = Number(options?.usage?.perRun?.[rule.ruleId] ?? 0);
|
|
1159
|
+
const perDay = Number(options?.usage?.perDay?.[rule.ruleId] ?? 0);
|
|
1160
|
+
if (perRun >= rule.quota.perRun || perDay >= rule.quota.perDay) {
|
|
1161
|
+
return { ok: true, verdict: 'ESCALATE', ruleId: rule.ruleId, ruleHits, code: AUTHZ_CODES.QUOTA_EXCEEDED, reason: `规则 ${rule.ruleId} 额度用尽(本轮 ${perRun}/${rule.quota.perRun},今日 ${perDay}/${rule.quota.perDay})`, proposal: rel };
|
|
1162
|
+
}
|
|
1163
|
+
return { ok: true, verdict: 'AUTO', ruleId: rule.ruleId, ruleHits, code: null, reason: `规则 ${rule.ruleId} 放行(可逆 + 证据齐 + 未超额度)`, proposal: rel };
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
function backupName(file, now) {
|
|
1167
|
+
const stampDate = now instanceof Date ? now : new Date(now ?? Date.now());
|
|
1168
|
+
const iso = stampDate.toISOString().replace(/[:.]/g, '-');
|
|
1169
|
+
return `${file}.bak-${iso}`;
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
/**
|
|
1173
|
+
* 执行已判 AUTO 的提议。写前 .bak、写后回读 sha;不把写权交回会话。
|
|
1174
|
+
* 只支持 jsonl_append;其余种类返回 unsupported(调用方必须升级人工)。
|
|
1175
|
+
*/
|
|
1176
|
+
export async function applyProposal(root, proposal, verdict, options = {}) {
|
|
1177
|
+
const now = options.now ?? new Date();
|
|
1178
|
+
const p = verdict?.proposal ?? normalizeProposal(proposal);
|
|
1179
|
+
const abs = p.target.abs ?? path.resolve(root, p.target.file);
|
|
1180
|
+
const rel = p.target.rel ?? path.relative(root, abs).split(path.sep).join('/');
|
|
1181
|
+
if (!ALLOWED_WRITE_PREFIXES.some((prefix) => rel.startsWith(prefix))) {
|
|
1182
|
+
return { applied: false, unsupported: true, code: AUTHZ_CODES.TARGET_NOT_ALLOWED, reason: `target 前缀不在允许写范围(${ALLOWED_WRITE_PREFIXES.join(', ')}): ${rel}` };
|
|
1183
|
+
}
|
|
1184
|
+
if (p.kind !== 'jsonl_append') {
|
|
1185
|
+
return { applied: false, unsupported: true, code: AUTHZ_CODES.EFFECTOR_UNSUPPORTED, reason: `效果器未实现: ${p.kind}(草案只实现 jsonl_append)` };
|
|
1186
|
+
}
|
|
1187
|
+
const lineValue = p?.params?.line ?? p?.params?.value;
|
|
1188
|
+
if (lineValue === undefined) {
|
|
1189
|
+
return { applied: false, code: AUTHZ_CODES.PROPOSAL_INVALID, reason: 'jsonl_append 需要 params.line 或 params.value' };
|
|
1190
|
+
}
|
|
1191
|
+
try {
|
|
1192
|
+
await fsp.mkdir(path.dirname(abs), { recursive: true });
|
|
1193
|
+
let beforeSha = null;
|
|
1194
|
+
let backup = null;
|
|
1195
|
+
if (fs.existsSync(abs)) {
|
|
1196
|
+
beforeSha = sha256FileSync(abs);
|
|
1197
|
+
if (p?.target?.beforeSha && String(p.target.beforeSha).toLowerCase() !== beforeSha) {
|
|
1198
|
+
return { applied: false, code: AUTHZ_CODES.BEFORE_SHA_MISMATCH, reason: `target.beforeSha 不符(期望 ${p.target.beforeSha},实际 ${beforeSha})` };
|
|
1199
|
+
}
|
|
1200
|
+
backup = backupName(abs, now);
|
|
1201
|
+
await fsp.copyFile(abs, backup);
|
|
1202
|
+
}
|
|
1203
|
+
const line = typeof lineValue === 'string' ? lineValue : JSON.stringify(lineValue);
|
|
1204
|
+
const fd = fs.openSync(abs, 'a');
|
|
1205
|
+
try {
|
|
1206
|
+
fs.writeSync(fd, `${line}\n`);
|
|
1207
|
+
fs.fsyncSync(fd);
|
|
1208
|
+
} finally {
|
|
1209
|
+
fs.closeSync(fd);
|
|
1210
|
+
}
|
|
1211
|
+
const afterSha = sha256FileSync(abs);
|
|
1212
|
+
const bytes = fs.statSync(abs).size;
|
|
1213
|
+
return { applied: true, code: null, target: rel, beforeSha, afterSha, bytes, backup };
|
|
1214
|
+
} catch (e) {
|
|
1215
|
+
return { applied: false, code: AUTHZ_CODES.WRITE_FAILED, reason: e?.message ?? String(e) };
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
/** 判定 + 执行一体(供 wake-bridge 的 submitProposal 调用)。 */
|
|
1220
|
+
export async function authorizeAndApply(options = {}) {
|
|
1221
|
+
const started = Date.now();
|
|
1222
|
+
const now = options.now ?? new Date();
|
|
1223
|
+
const root = options.root;
|
|
1224
|
+
const authz = authorize(options.proposal, {
|
|
1225
|
+
root,
|
|
1226
|
+
rules: options.rules,
|
|
1227
|
+
usage: options.usage,
|
|
1228
|
+
maxFilesPerProposal: options.maxFilesPerProposal,
|
|
1229
|
+
});
|
|
1230
|
+
let applied = false;
|
|
1231
|
+
let unsupported = false;
|
|
1232
|
+
let write = null;
|
|
1233
|
+
let verdict = authz.verdict;
|
|
1234
|
+
let code = authz.code;
|
|
1235
|
+
let reason = authz.reason;
|
|
1236
|
+
if (verdict === 'AUTO') {
|
|
1237
|
+
write = await applyProposal(root, options.proposal, authz, { now });
|
|
1238
|
+
if (write.applied) {
|
|
1239
|
+
applied = true;
|
|
1240
|
+
} else {
|
|
1241
|
+
// 判定 AUTO 但效果器拒绝/未实现:降级 ESCALATE,绝不假报已执行。
|
|
1242
|
+
unsupported = write.unsupported === true;
|
|
1243
|
+
verdict = 'ESCALATE';
|
|
1244
|
+
code = write.code ?? AUTHZ_CODES.EFFECTOR_UNSUPPORTED;
|
|
1245
|
+
reason = write.reason ?? '效果器拒绝执行,升级人工';
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
const params = options.proposal?.params ?? {};
|
|
1249
|
+
return {
|
|
1250
|
+
ok: true,
|
|
1251
|
+
verdict,
|
|
1252
|
+
ruleId: authz.ruleId,
|
|
1253
|
+
ruleHits: authz.ruleHits,
|
|
1254
|
+
reason,
|
|
1255
|
+
code,
|
|
1256
|
+
applied,
|
|
1257
|
+
unsupported,
|
|
1258
|
+
target: write?.target ?? authz.proposal?.target?.rel ?? String(options.proposal?.target?.file ?? ''),
|
|
1259
|
+
beforeSha: write?.beforeSha ?? null,
|
|
1260
|
+
afterSha: write?.afterSha ?? null,
|
|
1261
|
+
bytes: write?.bytes ?? null,
|
|
1262
|
+
backup: write?.backup ?? null,
|
|
1263
|
+
paramsSha: sha256Text(JSON.stringify(params)),
|
|
1264
|
+
durationMs: Date.now() - started,
|
|
1265
|
+
};
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
/** 审计行(jsonl);字段顺序固定,便于面板按行重放。 */
|
|
1269
|
+
export function auditRow(entry) {
|
|
1270
|
+
const row = {
|
|
1271
|
+
ts: entry.ts ?? new Date().toISOString(),
|
|
1272
|
+
runId: entry.runId ?? null,
|
|
1273
|
+
sessionId: entry.sessionId ?? null,
|
|
1274
|
+
proposalId: entry.proposalId ?? null,
|
|
1275
|
+
kind: entry.kind ?? null,
|
|
1276
|
+
target: entry.target ?? null,
|
|
1277
|
+
paramsSha: entry.paramsSha ?? null,
|
|
1278
|
+
verdict: entry.verdict ?? null,
|
|
1279
|
+
ruleHits: Array.isArray(entry.ruleHits) ? entry.ruleHits.map((h) => (typeof h === 'object' ? h : { ruleId: String(h) })) : [],
|
|
1280
|
+
reason: entry.reason ?? null,
|
|
1281
|
+
code: entry.code ?? null,
|
|
1282
|
+
beforeSha: entry.beforeSha ?? null,
|
|
1283
|
+
afterSha: entry.afterSha ?? null,
|
|
1284
|
+
result: entry.result ?? (entry.applied === true ? 'applied' : 'not-applied'),
|
|
1285
|
+
durationMs: entry.durationMs ?? 0,
|
|
1286
|
+
tokens: entry.tokens ?? null,
|
|
1287
|
+
};
|
|
1288
|
+
return row;
|
|
1289
|
+
}
|
|
1290
|
+
// ---------------------------------------------------------------------------
|
|
1291
|
+
// 数据面原语:队列 / 待批 / 授权审计 / runs(§3)
|
|
1292
|
+
//
|
|
1293
|
+
// 设计口径:
|
|
1294
|
+
// * 每次 append 前 prune(写时有界),daily reconcile 再做一次全量(双保险)。
|
|
1295
|
+
// * 队列行 schema 固定 wake-queue/v1;状态 queued → running → done/failed → expired。
|
|
1296
|
+
// * failed 行保留在队列里(retries < retryMax 可再拾取),达到 retryMax 才 expired。
|
|
1297
|
+
// * 所有写都是原子写(tmp → fsync → rename),半行读入直接跳过。
|
|
1298
|
+
// ---------------------------------------------------------------------------
|
|
1299
|
+
|
|
1300
|
+
/** 读队列(容忍坏行/半行)。 */
|
|
1301
|
+
export function readQueue(input) {
|
|
1302
|
+
return readJsonl(asPaths(input).queue);
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
/** 待批行(升级给人工的可见账)。 */
|
|
1306
|
+
export function readPending(input) {
|
|
1307
|
+
return readJsonl(asPaths(input).pending);
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
function rewriteJsonl(file, rows) {
|
|
1311
|
+
writeFileAtomic(file, rows.map((row) => `${JSON.stringify(row)}\n`).join(''));
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
function activeRows(rows) {
|
|
1315
|
+
return rows.filter((row) => ['queued', 'failed', 'running'].includes(String(row?.status ?? 'queued')));
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
/**
|
|
1319
|
+
* 队列剪枝:过期(TTL/90d)→ expired 丢弃;条数超 queueMax → 丢最旧的 queued。
|
|
1320
|
+
* 幂等、有界;写时调用(append 前)与 daily 都调。
|
|
1321
|
+
*/
|
|
1322
|
+
export function pruneQueue(input, options = {}) {
|
|
1323
|
+
const paths = asPaths(input);
|
|
1324
|
+
const now = nowDateOf(options.now ?? options);
|
|
1325
|
+
const retryMax = Number.isFinite(Number(options.retryMax)) ? Number(options.retryMax) : WAKE_DEFAULTS.retryMax;
|
|
1326
|
+
const queueMax = Math.min(WAKE_BOUNDS.queueMax, Math.max(1, Number(options.queueMax ?? WAKE_DEFAULTS.queueMax) || WAKE_DEFAULTS.queueMax));
|
|
1327
|
+
const rows = readQueue(paths);
|
|
1328
|
+
const kept = [];
|
|
1329
|
+
const expired = [];
|
|
1330
|
+
for (const row of rows) {
|
|
1331
|
+
const status = String(row.status ?? 'queued');
|
|
1332
|
+
if (!['queued', 'failed', 'running'].includes(status)) continue;
|
|
1333
|
+
if (status === 'running') {
|
|
1334
|
+
kept.push(row);
|
|
1335
|
+
continue;
|
|
1336
|
+
}
|
|
1337
|
+
const createdAt = Date.parse(row.createdAt);
|
|
1338
|
+
const expiresAt = Date.parse(row.expiresAt);
|
|
1339
|
+
const tooOld = Number.isFinite(createdAt) && now.getTime() - createdAt > WAKE_BOUNDS.ticketTtlDays * 86400000;
|
|
1340
|
+
const ttlOut = Number.isFinite(expiresAt) && expiresAt <= now.getTime();
|
|
1341
|
+
if (tooOld || ttlOut) {
|
|
1342
|
+
expired.push({ id: row.id ?? null, ticketId: row.ticket ?? row.id ?? null, status, retries: Number(row.retries ?? 0) });
|
|
1343
|
+
continue;
|
|
1344
|
+
}
|
|
1345
|
+
if (status === 'failed' && Number(row.retries ?? 0) >= retryMax) {
|
|
1346
|
+
// 达到重试上限:保留给 pickTicket 走 expired 可见路径(这里不静默删)。
|
|
1347
|
+
kept.push(row);
|
|
1348
|
+
continue;
|
|
1349
|
+
}
|
|
1350
|
+
kept.push(row);
|
|
1351
|
+
}
|
|
1352
|
+
let overflow = [];
|
|
1353
|
+
const clipped = kept.filter((row) => String(row.status) !== 'running');
|
|
1354
|
+
if (clipped.length > queueMax) {
|
|
1355
|
+
const sortable = clipped
|
|
1356
|
+
.map((row, index) => ({ row, index, at: Date.parse(row.createdAt) || 0 }))
|
|
1357
|
+
.sort((a, b) => (a.at - b.at) || (a.index - b.index));
|
|
1358
|
+
const drop = new Set(sortable.slice(0, clipped.length - queueMax).map((item) => item.row));
|
|
1359
|
+
overflow = [...drop].map((row) => ({ id: row.id ?? null, ticketId: row.ticket ?? row.id ?? null, reason: 'capacity' }));
|
|
1360
|
+
for (const row of drop) {
|
|
1361
|
+
const index = kept.indexOf(row);
|
|
1362
|
+
if (index >= 0) kept.splice(index, 1);
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
if (expired.length > 0 || overflow.length > 0 || kept.length !== rows.length) {
|
|
1366
|
+
rewriteJsonl(paths.queue, kept);
|
|
1367
|
+
}
|
|
1368
|
+
const summary = { total: rows.length, kept: kept.length, expired, overflow };
|
|
1369
|
+
if (overflow.length > 0) {
|
|
1370
|
+
safeGate(paths, GATE_EVENTS.WAKE_FAIL, {
|
|
1371
|
+
decision: 'warn',
|
|
1372
|
+
code: WAKE_CODES.QUEUE_FULL,
|
|
1373
|
+
reason: `queue 超过 ${queueMax} 条,丢弃最旧 ${overflow.length} 行`,
|
|
1374
|
+
evidence: [stringifyCounts({ kept: kept.length, dropped: overflow.length })],
|
|
1375
|
+
});
|
|
1376
|
+
}
|
|
1377
|
+
return summary;
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
function stringifyCounts(counts) {
|
|
1381
|
+
try {
|
|
1382
|
+
return canonicalJson(counts);
|
|
1383
|
+
} catch {
|
|
1384
|
+
return JSON.stringify(counts);
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
/** 追加一行(写前 prune;超 queueMax fail-closed 拒绝)。 */
|
|
1389
|
+
export function appendQueueRow(input, row) {
|
|
1390
|
+
const paths = asPaths(input);
|
|
1391
|
+
const cfg = input?.cfg ?? {};
|
|
1392
|
+
pruneQueue(paths, { now: input?.now, retryMax: cfg.retryMax, queueMax: cfg.queueMax });
|
|
1393
|
+
const rows = readQueue(paths);
|
|
1394
|
+
const queueMax = Math.min(WAKE_BOUNDS.queueMax, Math.max(1, Number(cfg.queueMax ?? WAKE_DEFAULTS.queueMax)));
|
|
1395
|
+
if (activeRows(rows).length >= queueMax) {
|
|
1396
|
+
throw wakeError(WAKE_CODES.QUEUE_FULL, `唤醒队列已满(${queueMax})`, { queueMax });
|
|
1397
|
+
}
|
|
1398
|
+
const value = { schema: WAKE_SCHEMAS.queue, ...row };
|
|
1399
|
+
appendJsonl(paths.queue, value);
|
|
1400
|
+
if (statSize(paths.queue) > WAKE_BOUNDS.fileMaxBytes) {
|
|
1401
|
+
const tail = readQueue(paths).slice(-queueMax);
|
|
1402
|
+
rewriteJsonl(paths.queue, tail);
|
|
1403
|
+
}
|
|
1404
|
+
return value;
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
/** 待批剪枝:≤200 条 ∧ 90d。 */
|
|
1408
|
+
export function prunePending(input, options = {}) {
|
|
1409
|
+
const paths = asPaths(input);
|
|
1410
|
+
const now = nowDateOf(options.now ?? options);
|
|
1411
|
+
const rows = readPending(paths);
|
|
1412
|
+
const max = WAKE_BOUNDS.pendingMax;
|
|
1413
|
+
const kept = rows.filter((row) => {
|
|
1414
|
+
const ts = Date.parse(row.ts);
|
|
1415
|
+
return !Number.isFinite(ts) || now.getTime() - ts <= WAKE_BOUNDS.ticketTtlDays * 86400000;
|
|
1416
|
+
});
|
|
1417
|
+
const clipped = kept.length > max ? kept.slice(-max) : kept;
|
|
1418
|
+
if (clipped.length !== rows.length) rewriteJsonl(paths.pending, clipped);
|
|
1419
|
+
return { total: rows.length, kept: clipped.length };
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
/** 升级行(wake-pending/v1);写前 prune。 */
|
|
1423
|
+
export function appendPending(input, entry) {
|
|
1424
|
+
const paths = asPaths(input);
|
|
1425
|
+
prunePending(paths, { now: input?.now });
|
|
1426
|
+
const row = { schema: WAKE_SCHEMAS.pending, ...entry };
|
|
1427
|
+
appendJsonl(paths.pending, row);
|
|
1428
|
+
return row;
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
/**
|
|
1432
|
+
* 授权审计日志 rotate:≤50,000 行 ∧ 180d ∧ ≤256 KiB。
|
|
1433
|
+
* 只留一代:旧内容覆盖式写到 auto-authz.jsonl.1,当前文件只保留未超龄行。
|
|
1434
|
+
*/
|
|
1435
|
+
export function rotateAuthzLog(input, options = {}) {
|
|
1436
|
+
const paths = asPaths(input);
|
|
1437
|
+
const now = nowDateOf(options.now ?? options);
|
|
1438
|
+
let text;
|
|
1439
|
+
try {
|
|
1440
|
+
text = fs.readFileSync(paths.autoAuthz, 'utf8');
|
|
1441
|
+
} catch {
|
|
1442
|
+
return { rotated: false, lines: 0, kept: 0 };
|
|
1443
|
+
}
|
|
1444
|
+
const lineCount = text === '' ? 0 : text.split(/\r?\n/).filter((line) => line.trim() !== '').length;
|
|
1445
|
+
const size = Buffer.byteLength(text, 'utf8');
|
|
1446
|
+
const rows = readJsonl(paths.autoAuthz);
|
|
1447
|
+
const cutoff = now.getTime() - WAKE_BOUNDS.authzDays * 86400000;
|
|
1448
|
+
const aged = rows.filter((row) => {
|
|
1449
|
+
const ts = Date.parse(row.ts);
|
|
1450
|
+
return !Number.isFinite(ts) || ts >= cutoff;
|
|
1451
|
+
});
|
|
1452
|
+
const needsRotate = lineCount > WAKE_BOUNDS.authzMaxLines || size > WAKE_BOUNDS.fileMaxBytes || aged.length !== rows.length;
|
|
1453
|
+
if (!needsRotate && options.force !== true) return { rotated: false, lines: lineCount, kept: rows.length };
|
|
1454
|
+
try {
|
|
1455
|
+
writeFileAtomic(`${paths.autoAuthz}.1`, text);
|
|
1456
|
+
} catch {
|
|
1457
|
+
// 旧代写不了也要把当前文件压回去(否则无限长)。
|
|
1458
|
+
}
|
|
1459
|
+
const kept = aged.slice(-WAKE_BOUNDS.authzMaxLines);
|
|
1460
|
+
rewriteJsonl(paths.autoAuthz, kept);
|
|
1461
|
+
safeGate(paths, GATE_EVENTS.WAKE_ROTATE, {
|
|
1462
|
+
decision: 'ok',
|
|
1463
|
+
reason: 'auto-authz rotate',
|
|
1464
|
+
evidence: [stringifyCounts({ linesBefore: lineCount, linesAfter: kept.length, bytesBefore: size })],
|
|
1465
|
+
});
|
|
1466
|
+
return { rotated: true, lines: lineCount, kept: kept.length };
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
/** 读 runs 记录(按 finishedAt/文件名倒序;limit 默认 1)。 */
|
|
1470
|
+
export function readRunRecords(input, options = {}) {
|
|
1471
|
+
const paths = asPaths(input);
|
|
1472
|
+
const limit = Math.max(1, Number(options.limit ?? 1) || 1);
|
|
1473
|
+
let files = [];
|
|
1474
|
+
try {
|
|
1475
|
+
files = fs.readdirSync(paths.runsDir).filter((name) => name.endsWith('.json'));
|
|
1476
|
+
} catch {
|
|
1477
|
+
return [];
|
|
1478
|
+
}
|
|
1479
|
+
files.sort().reverse();
|
|
1480
|
+
const rows = [];
|
|
1481
|
+
for (const name of files) {
|
|
1482
|
+
if (rows.length >= limit) break;
|
|
1483
|
+
const row = readJson(path.join(paths.runsDir, name), null);
|
|
1484
|
+
if (row && typeof row === 'object') rows.push(row);
|
|
1485
|
+
}
|
|
1486
|
+
return rows;
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
/** runs 剪枝:≤200 个 ∧ 90d。 */
|
|
1490
|
+
export function pruneRuns(input, options = {}) {
|
|
1491
|
+
const paths = asPaths(input);
|
|
1492
|
+
const now = nowDateOf(options.now ?? options);
|
|
1493
|
+
let files = [];
|
|
1494
|
+
try {
|
|
1495
|
+
files = fs.readdirSync(paths.runsDir).filter((name) => name.endsWith('.json'));
|
|
1496
|
+
} catch {
|
|
1497
|
+
return { total: 0, removed: 0 };
|
|
1498
|
+
}
|
|
1499
|
+
const entries = files.map((name) => {
|
|
1500
|
+
const file = path.join(paths.runsDir, name);
|
|
1501
|
+
let at = 0;
|
|
1502
|
+
try {
|
|
1503
|
+
at = fs.statSync(file).mtimeMs;
|
|
1504
|
+
} catch {
|
|
1505
|
+
at = 0;
|
|
1506
|
+
}
|
|
1507
|
+
return { name, file, at };
|
|
1508
|
+
});
|
|
1509
|
+
entries.sort((a, b) => a.at - b.at);
|
|
1510
|
+
const removed = [];
|
|
1511
|
+
const cutoff = now.getTime() - WAKE_BOUNDS.runsDays * 86400000;
|
|
1512
|
+
const overflow = Math.max(0, entries.length - WAKE_BOUNDS.runsMax);
|
|
1513
|
+
const toRemove = new Set(entries.slice(0, overflow).map((entry) => entry.name));
|
|
1514
|
+
for (const entry of entries) {
|
|
1515
|
+
if (toRemove.has(entry.name) || (entry.at > 0 && entry.at < cutoff)) {
|
|
1516
|
+
try {
|
|
1517
|
+
fs.unlinkSync(entry.file);
|
|
1518
|
+
removed.push(entry.name);
|
|
1519
|
+
} catch {
|
|
1520
|
+
// 删不掉就留着:宁可多一个 run 记录,也不打死 daily。
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
return { total: files.length, removed: removed.length };
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
/** 写 run 记录(wake-run/v1;≤200 个 ∧ 90d;原子写)。 */
|
|
1528
|
+
export function writeRunRecord(input, run) {
|
|
1529
|
+
const paths = asPaths(input);
|
|
1530
|
+
pruneRuns(paths, { now: input?.now });
|
|
1531
|
+
const runId = String(run?.runId ?? '');
|
|
1532
|
+
if (runId === '') throw wakeError(WAKE_CODES.RUN_CODE_NOT_RESTRICTABLE, 'runId 缺失');
|
|
1533
|
+
// 先算收据哈希(覆盖除 receiptSha256 外的全部字段)。
|
|
1534
|
+
const payload = { ...run, receiptSha256: null };
|
|
1535
|
+
payload.receiptSha256 = sha256Text(stringifyCounts(payload));
|
|
1536
|
+
fs.mkdirSync(paths.runsDir, { recursive: true });
|
|
1537
|
+
writeFileAtomic(path.join(paths.runsDir, `${runId}.json`), `${JSON.stringify(payload, null, 2)}\n`);
|
|
1538
|
+
return payload;
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
/** 写时 prune(有界;不重建 panel)。 */
|
|
1542
|
+
export function pruneWakeStore(input, options = {}) {
|
|
1543
|
+
const paths = asPaths(input);
|
|
1544
|
+
const now = nowDateOf(options.now ?? options);
|
|
1545
|
+
const summary = {
|
|
1546
|
+
at: isoOf(now),
|
|
1547
|
+
queue: pruneQueue(paths, { now, retryMax: options.retryMax, queueMax: options.queueMax }),
|
|
1548
|
+
pending: prunePending(paths, { now }),
|
|
1549
|
+
runs: pruneRuns(paths, { now }),
|
|
1550
|
+
authz: rotateAuthzLog(paths, { now }),
|
|
1551
|
+
};
|
|
1552
|
+
return summary;
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
/**
|
|
1556
|
+
* daily 全量对账(§3.3):prune + rotate + 重建 panel + 写 reconcile 门。
|
|
1557
|
+
* 失败只降级 gate-log fail + panel.capability.code,不阻塞主会话。
|
|
1558
|
+
*/
|
|
1559
|
+
export function reconcileWakeStore(input, options = {}) {
|
|
1560
|
+
const paths = asPaths(input);
|
|
1561
|
+
const now = nowDateOf(options.now ?? options);
|
|
1562
|
+
let summary;
|
|
1563
|
+
try {
|
|
1564
|
+
summary = {
|
|
1565
|
+
at: isoOf(now),
|
|
1566
|
+
queue: pruneQueue(paths, { now, retryMax: options.retryMax, queueMax: options.queueMax }),
|
|
1567
|
+
pending: prunePending(paths, { now }),
|
|
1568
|
+
runs: pruneRuns(paths, { now }),
|
|
1569
|
+
authz: rotateAuthzLog(paths, { now }),
|
|
1570
|
+
};
|
|
1571
|
+
} catch (error) {
|
|
1572
|
+
safeGate(paths, GATE_EVENTS.WAKE_FAIL, { decision: 'fail', code: error?.code ?? WAKE_CODES.STORE_WRITE_FAILED, reason: error?.message ?? String(error) });
|
|
1573
|
+
return { ok: false, code: error?.code ?? WAKE_CODES.STORE_WRITE_FAILED };
|
|
1574
|
+
}
|
|
1575
|
+
const state = readWakeState(paths);
|
|
1576
|
+
state.lastDailyAt = isoOf(now);
|
|
1577
|
+
state.lastPruneAt = isoOf(now);
|
|
1578
|
+
const dayKey = dateKeyOf(now);
|
|
1579
|
+
if (state.dayKey !== dayKey) {
|
|
1580
|
+
state.dayKey = dayKey;
|
|
1581
|
+
state.dayCount = 0;
|
|
1582
|
+
}
|
|
1583
|
+
try {
|
|
1584
|
+
writeWakeState(paths, state);
|
|
1585
|
+
} catch (error) {
|
|
1586
|
+
safeGate(paths, GATE_EVENTS.WAKE_FAIL, { decision: 'fail', code: error?.code ?? WAKE_CODES.STORE_WRITE_FAILED, reason: error?.message ?? String(error) });
|
|
1587
|
+
}
|
|
1588
|
+
const panel = refreshWakePanel(paths, { now, enabled: options.enabled !== false, capability: state.capability ?? null });
|
|
1589
|
+
safeGate(paths, GATE_EVENTS.WAKE_RECONCILE, {
|
|
1590
|
+
decision: 'ok',
|
|
1591
|
+
reason: 'daily reconcile',
|
|
1592
|
+
evidence: [stringifyCounts({ queue: summary.queue.kept, pending: summary.pending.kept, runs: summary.runs.total, rotated: summary.authz.rotated })],
|
|
1593
|
+
});
|
|
1594
|
+
return { ok: true, ...summary, panel };
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
// ---------------------------------------------------------------------------
|
|
1598
|
+
// 票据:入队 / 取消 / 拾取 / 状态迁移(§6.1–6.2)
|
|
1599
|
+
// ---------------------------------------------------------------------------
|
|
1600
|
+
|
|
1601
|
+
function dedupeKeyOf({ kind, target, params, now }) {
|
|
1602
|
+
return sha256Text(`${stringifyCounts({ kind, target, params })}|${dateKeyOf(now)}`);
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
function newTicketId() {
|
|
1606
|
+
return `tkt-${randomUUID()}`;
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
/**
|
|
1610
|
+
* 入队(去重口径:同 dedupeKey 且活跃状态 → dup:true 不新增)。
|
|
1611
|
+
* @returns {{ok:boolean, dup?:boolean, ticketId?:string, ticket?:object, code?:string, message?:string}}
|
|
1612
|
+
*/
|
|
1613
|
+
export function enqueueWakeTicket(input = {}, args = {}) {
|
|
1614
|
+
const paths = asPaths(input.root ?? input.memoryRoot ?? input);
|
|
1615
|
+
const cfg = isPlainObject(input.cfg) ? input.cfg : WAKE_DEFAULTS;
|
|
1616
|
+
const now = nowDateOf(input.now);
|
|
1617
|
+
const raw = isPlainObject(args?.ticket) ? args.ticket : (isPlainObject(args) ? args : {});
|
|
1618
|
+
const kind = typeof raw.kind === 'string' ? raw.kind.trim() : '';
|
|
1619
|
+
if (!WAKE_KINDS.includes(kind)) {
|
|
1620
|
+
return { ok: false, code: WAKE_CODES.TICKET_INVALID, message: `未知触发源: ${kind || '(空)'}`, allowed: [...WAKE_KINDS] };
|
|
1621
|
+
}
|
|
1622
|
+
const triggers = Array.isArray(cfg.triggers) ? cfg.triggers : WAKE_DEFAULTS.triggers;
|
|
1623
|
+
if (!triggers.includes(kind)) {
|
|
1624
|
+
return { ok: false, code: WAKE_CODES.TRIGGER_DISABLED, message: `触发源 ${kind} 已在配置里关闭` };
|
|
1625
|
+
}
|
|
1626
|
+
const targetRaw = raw.target;
|
|
1627
|
+
const target = typeof targetRaw === 'string' ? targetRaw.trim() : (typeof targetRaw?.file === 'string' ? targetRaw.file.trim() : '');
|
|
1628
|
+
if (target === '') {
|
|
1629
|
+
return { ok: false, code: WAKE_CODES.TICKET_INVALID, message: 'target 不能为空(写目标文件相对路径)' };
|
|
1630
|
+
}
|
|
1631
|
+
const action = typeof raw.action === 'string' && raw.action !== '' ? raw.action : 'propose';
|
|
1632
|
+
if (action !== 'propose') {
|
|
1633
|
+
return { ok: false, code: WAKE_CODES.TICKET_INVALID, message: `不支持 action=${action}(只允许 propose)` };
|
|
1634
|
+
}
|
|
1635
|
+
const params = isPlainObject(raw.params) ? raw.params : {};
|
|
1636
|
+
const evidence = Array.isArray(raw.evidence) ? raw.evidence : [];
|
|
1637
|
+
const dedupeKey = typeof raw.dedupeKey === 'string' && raw.dedupeKey !== ''
|
|
1638
|
+
? raw.dedupeKey
|
|
1639
|
+
: dedupeKeyOf({ kind, target, params, now });
|
|
1640
|
+
const rows = readQueue(paths);
|
|
1641
|
+
const dup = rows.find((row) => row?.dedupeKey === dedupeKey && ['queued', 'failed', 'running', 'escalated'].includes(String(row.status ?? 'queued')));
|
|
1642
|
+
if (dup) {
|
|
1643
|
+
return { ok: true, dup: true, ticketId: String(dup.id ?? ''), ticket: dup, code: 'E_WAKE_TICKET_DUPLICATE', reason: 'DEDUPE' };
|
|
1644
|
+
}
|
|
1645
|
+
const ttlHours = Math.min(WAKE_BOUNDS.ticketTtlDays * 24, Math.max(1, Number(cfg.ticketTtlHours ?? WAKE_DEFAULTS.ticketTtlHours)));
|
|
1646
|
+
const createdAt = isoOf(now);
|
|
1647
|
+
const expiresAt = new Date(now.getTime() + ttlHours * 3600000).toISOString();
|
|
1648
|
+
let value;
|
|
1649
|
+
try {
|
|
1650
|
+
value = appendQueueRow(
|
|
1651
|
+
{ ...paths, cfg, now },
|
|
1652
|
+
{
|
|
1653
|
+
id: newTicketId(),
|
|
1654
|
+
ticket: null,
|
|
1655
|
+
createdAt,
|
|
1656
|
+
expiresAt,
|
|
1657
|
+
kind,
|
|
1658
|
+
action,
|
|
1659
|
+
target,
|
|
1660
|
+
params,
|
|
1661
|
+
evidence,
|
|
1662
|
+
expectedEffect: typeof raw.expectedEffect === 'string' ? raw.expectedEffect : (typeof raw.expected_effect === 'string' ? raw.expected_effect : ''),
|
|
1663
|
+
risk: typeof raw.risk === 'string' ? raw.risk : '',
|
|
1664
|
+
dedupeKey,
|
|
1665
|
+
status: 'queued',
|
|
1666
|
+
retries: 0,
|
|
1667
|
+
},
|
|
1668
|
+
);
|
|
1669
|
+
} catch (error) {
|
|
1670
|
+
return { ok: false, code: error?.code ?? WAKE_CODES.STORE_WRITE_FAILED, message: error?.message ?? String(error) };
|
|
1671
|
+
}
|
|
1672
|
+
value.ticket = value.id;
|
|
1673
|
+
rewriteQueueTicketAlias(paths, value.id);
|
|
1674
|
+
return { ok: true, dup: false, ticketId: value.id, ticket: value };
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
// 队列行同时带 id / ticket(契约字段);首写时 ticket 先占位,这里补齐成同名。
|
|
1678
|
+
function rewriteQueueTicketAlias(paths, id) {
|
|
1679
|
+
const rows = readQueue(paths);
|
|
1680
|
+
let changed = false;
|
|
1681
|
+
for (const row of rows) {
|
|
1682
|
+
if (row.id === id && row.ticket !== id) {
|
|
1683
|
+
row.ticket = id;
|
|
1684
|
+
changed = true;
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
if (changed) rewriteJsonl(paths.queue, rows);
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
/** 取消一张票(queued/failed)。 */
|
|
1691
|
+
export function cancelTicket(input = {}, ticketId) {
|
|
1692
|
+
const paths = asPaths(input.root ?? input.memoryRoot ?? input);
|
|
1693
|
+
const id = typeof ticketId === 'object' ? String(ticketId?.ticketId ?? '') : String(ticketId ?? '');
|
|
1694
|
+
if (id === '') return { ok: false, code: WAKE_CODES.TICKET_INVALID, message: 'ticketId 为空' };
|
|
1695
|
+
const rows = readQueue(paths);
|
|
1696
|
+
const index = rows.findIndex((row) => row?.id === id);
|
|
1697
|
+
if (index < 0) return { ok: false, code: WAKE_CODES.TICKET_NOT_FOUND, message: `找不到票据 ${id}` };
|
|
1698
|
+
if (!['queued', 'failed'].includes(String(rows[index].status))) {
|
|
1699
|
+
return { ok: false, code: WAKE_CODES.TICKET_INVALID, message: `票据 ${id} 状态 ${rows[index].status} 不可取消` };
|
|
1700
|
+
}
|
|
1701
|
+
const [removed] = rows.splice(index, 1);
|
|
1702
|
+
rewriteJsonl(paths.queue, rows);
|
|
1703
|
+
return { ok: true, cancelled: true, ticketId: id, ticket: removed };
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
/**
|
|
1707
|
+
* 拾取一张票(§6.1 / P1-04):
|
|
1708
|
+
* queued ∪ failed(retries < retryMax);TTL 过期与 failed 达到 retryMax → expired + gate-log。
|
|
1709
|
+
* 返回 {ticket, expired}。
|
|
1710
|
+
*/
|
|
1711
|
+
export function pickTicket(input = {}, options = {}) {
|
|
1712
|
+
const paths = asPaths(input.root ?? input.memoryRoot ?? input);
|
|
1713
|
+
const now = nowDateOf(options.now ?? input.now);
|
|
1714
|
+
const retryMax = Number.isFinite(Number(options.retryMax)) ? Number(options.retryMax) : WAKE_DEFAULTS.retryMax;
|
|
1715
|
+
const rows = readQueue(paths);
|
|
1716
|
+
const candidates = [];
|
|
1717
|
+
const expired = [];
|
|
1718
|
+
for (const row of rows) {
|
|
1719
|
+
const status = String(row.status ?? 'queued');
|
|
1720
|
+
const expiresAt = Date.parse(row.expiresAt);
|
|
1721
|
+
const ttlOut = Number.isFinite(expiresAt) && expiresAt <= now.getTime();
|
|
1722
|
+
if (status === 'running') continue;
|
|
1723
|
+
if (ttlOut) {
|
|
1724
|
+
expired.push({ id: row.id, ticketId: row.ticket ?? row.id, reason: 'ttl' });
|
|
1725
|
+
continue;
|
|
1726
|
+
}
|
|
1727
|
+
if (status === 'queued') {
|
|
1728
|
+
candidates.push(row);
|
|
1729
|
+
continue;
|
|
1730
|
+
}
|
|
1731
|
+
if (status === 'failed') {
|
|
1732
|
+
const retries = Number(row.retries ?? 0);
|
|
1733
|
+
if (retries < retryMax) candidates.push(row);
|
|
1734
|
+
else expired.push({ id: row.id, ticketId: row.ticket ?? row.id, reason: 'retry-max', retries });
|
|
1735
|
+
continue;
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
if (expired.length > 0) {
|
|
1739
|
+
const drop = new Set(expired.map((item) => item.id));
|
|
1740
|
+
rewriteJsonl(paths.queue, rows.filter((row) => !drop.has(row.id)));
|
|
1741
|
+
for (const item of expired) {
|
|
1742
|
+
safeGate(paths, GATE_EVENTS.WAKE_FAIL, {
|
|
1743
|
+
decision: 'fail',
|
|
1744
|
+
code: WAKE_CODES.TICKET_EXPIRED,
|
|
1745
|
+
reason: `票据 ${item.ticketId ?? item.id} 过期(${item.reason})`,
|
|
1746
|
+
evidence: [stringifyCounts(item)],
|
|
1747
|
+
});
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
candidates.sort((a, b) => {
|
|
1751
|
+
const at = Date.parse(a.createdAt) || 0;
|
|
1752
|
+
const bt = Date.parse(b.createdAt) || 0;
|
|
1753
|
+
if (at !== bt) return at - bt;
|
|
1754
|
+
return String(a.id).localeCompare(String(b.id));
|
|
1755
|
+
});
|
|
1756
|
+
return { ticket: candidates[0] ?? null, expired };
|
|
1757
|
+
}
|
|
1758
|
+
|
|
1759
|
+
function updateTicket(input, ticketId, patch) {
|
|
1760
|
+
const paths = asPaths(input.root ?? input.memoryRoot ?? input);
|
|
1761
|
+
const rows = readQueue(paths);
|
|
1762
|
+
const index = rows.findIndex((row) => row?.id === ticketId);
|
|
1763
|
+
if (index < 0) return null;
|
|
1764
|
+
rows[index] = { ...rows[index], ...patch };
|
|
1765
|
+
rewriteJsonl(paths.queue, rows);
|
|
1766
|
+
return rows[index];
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
/** queued/failed → running。 */
|
|
1770
|
+
export function markRunning(input = {}, ticketId, options = {}) {
|
|
1771
|
+
const row = updateTicket(input, ticketId, {
|
|
1772
|
+
status: 'running',
|
|
1773
|
+
runId: options.runId ?? null,
|
|
1774
|
+
startedAt: options.startedAt ?? isoOf(options.now ?? input.now),
|
|
1775
|
+
});
|
|
1776
|
+
if (!row) throw wakeError(WAKE_CODES.TICKET_NOT_FOUND, `找不到票据 ${ticketId}`);
|
|
1777
|
+
return row;
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
/**
|
|
1781
|
+
* 失败迁移:retries+1;未到 retryMax → status='failed' 留在队列(可重试);
|
|
1782
|
+
* 达到 retryMax → status='expired' 并写 gate-log hg.wake.fail{E_WAKE_TICKET_EXPIRED}。
|
|
1783
|
+
*/
|
|
1784
|
+
export function markFailed(input = {}, ticketId, options = {}) {
|
|
1785
|
+
const paths = asPaths(input.root ?? input.memoryRoot ?? input);
|
|
1786
|
+
const retryMax = Number.isFinite(Number(options.retryMax)) ? Number(options.retryMax) : WAKE_DEFAULTS.retryMax;
|
|
1787
|
+
const row = readQueue(paths).find((item) => item?.id === ticketId);
|
|
1788
|
+
if (!row) return { ok: false, code: WAKE_CODES.TICKET_NOT_FOUND, row: null, expired: false, retries: 0 };
|
|
1789
|
+
const retries = Number(row.retries ?? 0) + 1;
|
|
1790
|
+
const expired = retries >= retryMax;
|
|
1791
|
+
const lastError = {
|
|
1792
|
+
code: options.code ?? WAKE_CODES.UNEXPECTED,
|
|
1793
|
+
message: typeof options.message === 'string' ? options.message : '',
|
|
1794
|
+
at: isoOf(options.now ?? input.now),
|
|
1795
|
+
};
|
|
1796
|
+
if (expired) {
|
|
1797
|
+
const rows = readQueue(paths);
|
|
1798
|
+
rewriteJsonl(paths.queue, rows.filter((item) => item?.id !== ticketId));
|
|
1799
|
+
safeGate(paths, GATE_EVENTS.WAKE_FAIL, {
|
|
1800
|
+
decision: 'fail',
|
|
1801
|
+
code: WAKE_CODES.TICKET_EXPIRED,
|
|
1802
|
+
reason: `票据 ${ticketId} 失败 ${retries} 次达到 retryMax=${retryMax}`,
|
|
1803
|
+
evidence: [stringifyCounts({ ticketId, retries, code: lastError.code })],
|
|
1804
|
+
});
|
|
1805
|
+
} else {
|
|
1806
|
+
updateTicket(input, ticketId, { status: 'failed', retries, lastError, runId: options.runId ?? row.runId ?? null, failedAt: lastError.at });
|
|
1807
|
+
}
|
|
1808
|
+
return { ok: true, row: { ...row, retries, status: expired ? 'expired' : 'failed', lastError }, expired, retries };
|
|
1809
|
+
}
|
|
1810
|
+
|
|
1811
|
+
/** running → done/escalated(行从队列移除)。 */
|
|
1812
|
+
export function markDone(input = {}, ticketId, options = {}) {
|
|
1813
|
+
const paths = asPaths(input.root ?? input.memoryRoot ?? input);
|
|
1814
|
+
const rows = readQueue(paths);
|
|
1815
|
+
const index = rows.findIndex((row) => row?.id === ticketId);
|
|
1816
|
+
if (index < 0) return { ok: false, code: WAKE_CODES.TICKET_NOT_FOUND };
|
|
1817
|
+
const [row] = rows.splice(index, 1);
|
|
1818
|
+
rewriteJsonl(paths.queue, rows);
|
|
1819
|
+
return {
|
|
1820
|
+
ok: true,
|
|
1821
|
+
ticketId,
|
|
1822
|
+
status: options.status ?? 'done',
|
|
1823
|
+
ticket: { ...row, status: options.status ?? 'done', runId: options.runId ?? row.runId ?? null, retries: Number(row.retries ?? 0), finishedAt: isoOf(options.now ?? input.now) },
|
|
1824
|
+
};
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
// ---------------------------------------------------------------------------
|
|
1828
|
+
// 任务书 / 消息 / 拒绝识别(§5.4 / §6.3)
|
|
1829
|
+
// ---------------------------------------------------------------------------
|
|
1830
|
+
|
|
1831
|
+
/** 中文任务书(写进 followup;硬拦与非硬拦预算都逐条写明)。 */
|
|
1832
|
+
export function buildWakePrompt(ticket, cfg = WAKE_DEFAULTS) {
|
|
1833
|
+
const allow = Array.isArray(cfg.allowTools) ? cfg.allowTools : WAKE_DEFAULTS.allowTools;
|
|
1834
|
+
const deny = Array.isArray(cfg.denyTools) ? cfg.denyTools : WAKE_DEFAULTS.denyTools;
|
|
1835
|
+
const lines = [
|
|
1836
|
+
'【hardgate.wake 后台唤醒任务书】',
|
|
1837
|
+
`票据:${ticket?.ticket ?? ticket?.id ?? '(unknown)'}`,
|
|
1838
|
+
`触发源:${ticket?.kind ?? '(unknown)'}`,
|
|
1839
|
+
`目标:${ticket?.target ?? '(unknown)'}`,
|
|
1840
|
+
'',
|
|
1841
|
+
'规则(逐条遵守;违反即失败):',
|
|
1842
|
+
`1. 只能使用这些工具:${allow.join(' / ')}。其它工具(尤其 run_code / terminal / write / edit)不可用;被拒不要换写法重试。`,
|
|
1843
|
+
'2. 任何写盘动作都只能通过 memory_wake 的 propose 通道提交提议,由插件核按冻结规则表自动授权;你不得直接写文件、不得删除卡片、不得改规则库。',
|
|
1844
|
+
'3. 你的提议若被 auto-review 拒绝,不要重试、不要绕道、不要拆成多次规避——直接说明需要人工确认。',
|
|
1845
|
+
'4. 不要碰墓碑(archive/tombstones)、不要删除任何东西;不可逆操作一律升级。',
|
|
1846
|
+
`5. 预算:最多 ${cfg.maxRounds} 轮、约 ${cfg.maxOutputTokens} tokens、约 ${cfg.maxOutputChars} 字符。这是任务书预算,不是硬中断;但超出会在 run 审计里记为超预算。`,
|
|
1847
|
+
'6. 结束时输出一行结论:WAKE-SUMMARY {"proposalIds":[...],"reason":"<=200字>"};需要人工判断就直接说明,不要编造完成。',
|
|
1848
|
+
'',
|
|
1849
|
+
`证据(只读):${JSON.stringify(ticket?.evidence ?? [])}`,
|
|
1850
|
+
`参数摘要:${JSON.stringify(ticket?.params ?? {})}`,
|
|
1851
|
+
];
|
|
1852
|
+
return lines.join('\n');
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
/** 唤醒消息(followup 输入形状;source.kind='schedule' 让 UI/审计可辨)。 */
|
|
1856
|
+
export function buildWakeMessage(text) {
|
|
1857
|
+
return {
|
|
1858
|
+
id: `msg-${randomUUID()}`,
|
|
1859
|
+
role: 'user',
|
|
1860
|
+
content: [{ type: 'text', text: String(text ?? '') }],
|
|
1861
|
+
source: { kind: 'schedule' },
|
|
1862
|
+
};
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
function collectCodes(value, depth = 0, out = []) {
|
|
1866
|
+
if (depth > 6 || value === null || value === undefined) return out;
|
|
1867
|
+
if (typeof value === 'string') {
|
|
1868
|
+
if (/^[A-Z][A-Z0-9_]{3,}$/.test(value) && /AUTO_REVIEW|AutoReview/.test(value)) out.push(value);
|
|
1869
|
+
return out;
|
|
1870
|
+
}
|
|
1871
|
+
if (Array.isArray(value)) {
|
|
1872
|
+
for (const item of value) collectCodes(item, depth + 1, out);
|
|
1873
|
+
return out;
|
|
1874
|
+
}
|
|
1875
|
+
if (typeof value !== 'object') return out;
|
|
1876
|
+
if (typeof value.code === 'string' && /AUTO_REVIEW|AutoReview/.test(value.code)) out.push(value.code);
|
|
1877
|
+
for (const key of ['error', 'info', 'result', 'content', 'cause', 'data', 'message']) {
|
|
1878
|
+
if (value[key] !== undefined) collectCodes(value[key], depth + 1, out);
|
|
1879
|
+
}
|
|
1880
|
+
return out;
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
function isToolResultMessage(message) {
|
|
1884
|
+
if (!message || typeof message !== 'object') return false;
|
|
1885
|
+
if (message.role === 'tool') return true;
|
|
1886
|
+
if (message.type === 'tool-result' || message.type === 'tool_result') return true;
|
|
1887
|
+
const content = message.content;
|
|
1888
|
+
if (Array.isArray(content)) return content.some((item) => item && (item.type === 'tool-result' || item.type === 'tool_result'));
|
|
1889
|
+
return false;
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
/**
|
|
1893
|
+
* 只认结构化 tool-result.error.info.code(§5 / P0 草案被否行为 8 的反面):
|
|
1894
|
+
* 不解析自然语言、不猜“看起来像拒绝”。
|
|
1895
|
+
* @returns {{denied:boolean, unavailable:boolean, codes:string[], entries:object[]}}
|
|
1896
|
+
*/
|
|
1897
|
+
export function classifyDenials(messages = []) {
|
|
1898
|
+
const codes = [];
|
|
1899
|
+
const entries = [];
|
|
1900
|
+
const list = Array.isArray(messages) ? messages : [];
|
|
1901
|
+
for (const message of list) {
|
|
1902
|
+
if (!isToolResultMessage(message)) continue;
|
|
1903
|
+
const found = collectCodes(message);
|
|
1904
|
+
for (const code of found) codes.push(code);
|
|
1905
|
+
}
|
|
1906
|
+
const unique = [...new Set(codes)];
|
|
1907
|
+
const denied = unique.some((code) => /AUTO_REVIEW[^A-Z]*(DENIED|DENY|REJECTED)|(DENIED|REJECTED)[^A-Z]*AUTO_REVIEW/i.test(code));
|
|
1908
|
+
const unavailable = unique.some((code) => /AUTO_REVIEW[^A-Z]*(FAILED|FAILURE|UNAVAILABLE|ERROR|TIMEOUT|MISSING)/i.test(code));
|
|
1909
|
+
for (const code of unique) entries.push({ code, source: 'structured' });
|
|
1910
|
+
return { denied, unavailable, codes: unique, entries };
|
|
1911
|
+
}
|
|
1912
|
+
|
|
1913
|
+
function readSessionMessages(deps, agent) {
|
|
1914
|
+
try {
|
|
1915
|
+
if (typeof deps?.readSessionMessages === 'function') return deps.readSessionMessages(agent) ?? [];
|
|
1916
|
+
} catch {
|
|
1917
|
+
// fall through
|
|
1918
|
+
}
|
|
1919
|
+
try {
|
|
1920
|
+
const session = agent?.session;
|
|
1921
|
+
if (session && typeof session.deriveMessages === 'function') return session.deriveMessages() ?? [];
|
|
1922
|
+
} catch {
|
|
1923
|
+
// fall through
|
|
1924
|
+
}
|
|
1925
|
+
return Array.isArray(agent?.messages) ? agent.messages : [];
|
|
1926
|
+
}
|
|
1927
|
+
|
|
1928
|
+
function lastAssistantText(messages = []) {
|
|
1929
|
+
const list = Array.isArray(messages) ? messages : [];
|
|
1930
|
+
for (let i = list.length - 1; i >= 0; i -= 1) {
|
|
1931
|
+
const message = list[i];
|
|
1932
|
+
if (!message || (message.role !== 'assistant' && message.type !== 'assistant')) continue;
|
|
1933
|
+
const content = message.content;
|
|
1934
|
+
if (typeof content === 'string') return content;
|
|
1935
|
+
if (Array.isArray(content)) {
|
|
1936
|
+
const text = content.filter((item) => item && (item.type === 'text' || typeof item.text === 'string')).map((item) => item.text ?? '').join('\n');
|
|
1937
|
+
if (text.trim() !== '') return text;
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
return '';
|
|
1941
|
+
}
|
|
1942
|
+
|
|
1943
|
+
function collectToolCalls(messages = []) {
|
|
1944
|
+
const list = Array.isArray(messages) ? messages : [];
|
|
1945
|
+
const calls = [];
|
|
1946
|
+
const visit = (item) => {
|
|
1947
|
+
if (!item || typeof item !== 'object') return;
|
|
1948
|
+
const type = String(item.type ?? '');
|
|
1949
|
+
if (type === 'tool-call' || type === 'tool_call' || type === 'toolCall') {
|
|
1950
|
+
const name = String(item.name ?? item.toolName ?? item.tool?.name ?? '(unknown)');
|
|
1951
|
+
const args = item.arguments ?? item.args ?? item.input ?? null;
|
|
1952
|
+
calls.push({ name, argsSha256: sha256Text(stringifyCounts(args ?? {})), ok: item.ok === true ? true : (item.ok === false ? false : null), durationMs: Number.isFinite(Number(item.durationMs)) ? Number(item.durationMs) : null });
|
|
1953
|
+
return;
|
|
1954
|
+
}
|
|
1955
|
+
if (Array.isArray(item.content)) for (const child of item.content) visit(child);
|
|
1956
|
+
};
|
|
1957
|
+
for (const message of list) visit(message);
|
|
1958
|
+
return calls;
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
function countRounds(messages = []) {
|
|
1962
|
+
const list = Array.isArray(messages) ? messages : [];
|
|
1963
|
+
return list.filter((message) => message && (message.role === 'assistant' || message.type === 'assistant')).length;
|
|
1964
|
+
}
|
|
1965
|
+
|
|
1966
|
+
// ---------------------------------------------------------------------------
|
|
1967
|
+
// 后台会话:deps / 门策略 / 工具集断言 / 创建与清理(§5 / §6.5)
|
|
1968
|
+
// ---------------------------------------------------------------------------
|
|
1969
|
+
|
|
1970
|
+
export function installWakeToolPolicy(agentCtx, {
|
|
1971
|
+
allowedTools = WAKE_ALLOW_TOOLS_DEFAULT,
|
|
1972
|
+
denyNames = null,
|
|
1973
|
+
agent = null,
|
|
1974
|
+
} = {}) {
|
|
1975
|
+
const tools = agentCtx?.tools;
|
|
1976
|
+
if (!tools || typeof tools.restrict !== 'function' || typeof tools.guard !== 'function') {
|
|
1977
|
+
throw wakeError(WAKE_CODES.TOOLSET_VIOLATION, 'E_TOOL_SURFACE: agent ctx 没有 tools.restrict()/guard()');
|
|
1978
|
+
}
|
|
1979
|
+
const deny = Array.isArray(denyNames) ? denyNames.filter((name) => typeof name === 'string' && name !== '') : [];
|
|
1980
|
+
const never = new Set(['run_code', 'rpc', 'ptc']);
|
|
1981
|
+
const allow = [...allowedTools].filter((name) => typeof name === 'string' && name !== '' && !never.has(name) && !deny.includes(name));
|
|
1982
|
+
if (allow.length === 0) throw wakeError(WAKE_CODES.TOOLSET_VIOLATION, '唤醒会话白名单为空(配置错误)');
|
|
1983
|
+
const agentId = agent?.id ?? agentCtx?.agent?.id ?? null;
|
|
1984
|
+
let disposeRestrict = null;
|
|
1985
|
+
let disposeGuard = null;
|
|
1986
|
+
try {
|
|
1987
|
+
disposeRestrict = tools.restrict({ allow });
|
|
1988
|
+
disposeGuard = tools.guard((exec) => {
|
|
1989
|
+
const name = typeof exec?.name === 'string' ? exec.name : '';
|
|
1990
|
+
if (agentId && exec?.agent && exec.agent.id !== agentId) return undefined;
|
|
1991
|
+
if (name === '') return 'tool_denied: missing tool name';
|
|
1992
|
+
if (never.has(name)) return `tool_denied: "${name}" 是后台会话永久禁止的通道`;
|
|
1993
|
+
if (deny.includes(name)) return `tool_denied: "${name}" 在 hardgate.wake.toolExclude 拒绝表里`;
|
|
1994
|
+
if (!allow.includes(name)) return `tool_denied: "${name}" 不在唤醒会话白名单里`;
|
|
1995
|
+
return undefined;
|
|
1996
|
+
});
|
|
1997
|
+
} catch (error) {
|
|
1998
|
+
try { disposeGuard?.(); } catch { /* ignore */ }
|
|
1999
|
+
try { disposeRestrict?.(); } catch { /* ignore */ }
|
|
2000
|
+
throw error;
|
|
2001
|
+
}
|
|
2002
|
+
let disposed = false;
|
|
2003
|
+
return {
|
|
2004
|
+
deny,
|
|
2005
|
+
allow,
|
|
2006
|
+
strategy: 'allow-filter',
|
|
2007
|
+
known: null,
|
|
2008
|
+
never: [...never],
|
|
2009
|
+
dispose() {
|
|
2010
|
+
if (disposed) return;
|
|
2011
|
+
disposed = true;
|
|
2012
|
+
disposeGuard?.();
|
|
2013
|
+
disposeRestrict?.();
|
|
2014
|
+
},
|
|
2015
|
+
};
|
|
2016
|
+
}
|
|
2017
|
+
|
|
2018
|
+
function resolveDeps(ctx, options = {}) {
|
|
2019
|
+
const get = (name) => {
|
|
2020
|
+
try {
|
|
2021
|
+
return typeof ctx?.get === 'function' ? ctx.get(name) : ctx?.[name];
|
|
2022
|
+
} catch {
|
|
2023
|
+
return undefined;
|
|
2024
|
+
}
|
|
2025
|
+
};
|
|
2026
|
+
return {
|
|
2027
|
+
agents: options.agents ?? get('agents'),
|
|
2028
|
+
permissionPresets: options.permissionPresets ?? get('permissionPresets'),
|
|
2029
|
+
approval: options.approval ?? get('approval'),
|
|
2030
|
+
installToolPolicy: options.installToolPolicy
|
|
2031
|
+
?? get('installToolPolicy')
|
|
2032
|
+
?? installWakeToolPolicy,
|
|
2033
|
+
forceDispose: options.forceDispose ?? get('forceDispose') ?? null,
|
|
2034
|
+
readSessionMessages: options.readSessionMessages ?? null,
|
|
2035
|
+
};
|
|
2036
|
+
}
|
|
2037
|
+
|
|
2038
|
+
async function setGates(runtime, agent, sessionId) {
|
|
2039
|
+
const { permissionPresets, approval } = runtime.deps;
|
|
2040
|
+
if (typeof permissionPresets?.set !== 'function') throw wakeError(WAKE_CODES.DEPS_MISSING, 'permissionPresets.set 不可用');
|
|
2041
|
+
if (typeof approval?.setPolicy !== 'function') throw wakeError(WAKE_CODES.DEPS_MISSING, 'approval.setPolicy 不可用');
|
|
2042
|
+
const sessionKey = agent?.session ?? agent?.sessionId ?? sessionId;
|
|
2043
|
+
await permissionPresets.set(sessionKey, runtime.cfg.preset);
|
|
2044
|
+
await approval.setPolicy(agent, runtime.cfg.approvalPolicy);
|
|
2045
|
+
}
|
|
2046
|
+
|
|
2047
|
+
function assertToolset(ticketId, policy, cfg) {
|
|
2048
|
+
if (!policy || typeof policy !== 'object') throw wakeError(WAKE_CODES.TOOLSET_VIOLATION, 'installToolPolicy 未返回策略对象');
|
|
2049
|
+
// installToolPolicy 的真实返回是 { deny, allow, strategy, known, dispose }:
|
|
2050
|
+
// denyNames 非空 → strategy='explicit-deny',allow === null,白名单由 tools.guard 强制;
|
|
2051
|
+
// 因此这里必须同时接受 cfg 侧白名单记录与真实返回两种形态。
|
|
2052
|
+
const allow = Array.isArray(policy.allowedTools) ? policy.allowedTools : (Array.isArray(policy.allow) ? policy.allow : []);
|
|
2053
|
+
const deny = Array.isArray(policy.denyNames) ? policy.denyNames : (Array.isArray(policy.deny) ? policy.deny : []);
|
|
2054
|
+
const violations = [];
|
|
2055
|
+
if (deny.length > 0) {
|
|
2056
|
+
for (const name of cfg.allowTools) {
|
|
2057
|
+
if (deny.includes(name)) violations.push(`${name} 同时在白名单与拒绝表`);
|
|
2058
|
+
}
|
|
2059
|
+
for (const name of ['run_code', 'rpc', 'ptc', 'bash', 'pwsh', 'write', 'edit']) {
|
|
2060
|
+
if (!deny.includes(name)) violations.push(`拒绝表缺 ${name}`);
|
|
2061
|
+
}
|
|
2062
|
+
for (const name of allow) {
|
|
2063
|
+
if (name === 'run_code' || name === 'rpc' || name === 'ptc') violations.push(`${name} 不允许进入后台会话`);
|
|
2064
|
+
}
|
|
2065
|
+
} else {
|
|
2066
|
+
for (const name of cfg.allowTools) {
|
|
2067
|
+
if (!allow.includes(name)) violations.push(`白名单缺 ${name}`);
|
|
2068
|
+
}
|
|
2069
|
+
for (const name of allow) {
|
|
2070
|
+
if (name === 'run_code' || name === 'rpc' || name === 'ptc') violations.push(`${name} 不允许进入后台会话`);
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
if (violations.length > 0) {
|
|
2074
|
+
throw wakeError(WAKE_CODES.TOOLSET_VIOLATION, `后台会话工具集不合规(${ticketId}):${violations.join('; ')}`, { violations, strategy: policy.strategy ?? null });
|
|
2075
|
+
}
|
|
2076
|
+
return { ok: true, allow: allow.length > 0 ? allow : [...cfg.allowTools], deny, strategy: policy.strategy ?? null, policyAllow: policy.allow ?? null, known: policy.known ?? null };
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
function applyToolPolicy(runtime, agentCtx, agent, run) {
|
|
2080
|
+
const cfg = runtime.cfg;
|
|
2081
|
+
const denyNames = cfg.toolExclude.length > 0 ? [...cfg.toolExclude] : null;
|
|
2082
|
+
const policy = runtime.deps.installToolPolicy(agentCtx, {
|
|
2083
|
+
allowedTools: [...cfg.allowTools],
|
|
2084
|
+
denyNames,
|
|
2085
|
+
agent,
|
|
2086
|
+
});
|
|
2087
|
+
const checked = assertToolset(run.runId, policy, cfg);
|
|
2088
|
+
run.policy = { allowedTools: [...cfg.allowTools], denyNames: denyNames ?? [], strategy: checked.strategy, known: policy?.known ?? null };
|
|
2089
|
+
return policy;
|
|
2090
|
+
}
|
|
2091
|
+
|
|
2092
|
+
async function createWakeSession(runtime, run) {
|
|
2093
|
+
const deps = runtime.deps;
|
|
2094
|
+
if (typeof deps.agents?.create !== 'function') throw wakeError(WAKE_CODES.DEPS_MISSING, 'agents.create 不可用');
|
|
2095
|
+
if (typeof deps.installToolPolicy !== 'function') throw wakeError(WAKE_CODES.DEPS_MISSING, 'installToolPolicy 不可用');
|
|
2096
|
+
const cfg = runtime.cfg;
|
|
2097
|
+
const sessionId = `wake-${run.runId}-${randomUUID().slice(0, 8)}`;
|
|
2098
|
+
const created = await deps.agents.create({
|
|
2099
|
+
sessionId,
|
|
2100
|
+
agentOptions: { title: `hardgate.wake ${run.ticketId}`, permissionPreset: cfg.preset },
|
|
2101
|
+
setup: (agentCtx, agent) => {
|
|
2102
|
+
const target = agentCtx ?? agent;
|
|
2103
|
+
const policy = applyToolPolicy(runtime, target, agent ?? null, run);
|
|
2104
|
+
run.sessionId8 = sessionId.slice(0, 8);
|
|
2105
|
+
return policy;
|
|
2106
|
+
},
|
|
2107
|
+
});
|
|
2108
|
+
const agent = created?.agent ?? created;
|
|
2109
|
+
if (!agent || typeof agent !== 'object') throw wakeError(WAKE_CODES.SHAPE_INVALID, 'agents.create 未返回 agent');
|
|
2110
|
+
if (typeof agent.followup !== 'function') throw wakeError(WAKE_CODES.SHAPE_INVALID, '后台 agent 缺 followup()');
|
|
2111
|
+
if (typeof agent.whenIdle !== 'function') throw wakeError(WAKE_CODES.SHAPE_INVALID, '后台 agent 缺 whenIdle()');
|
|
2112
|
+
const dispose = created?.dispose ?? created?.close ?? ((typeof agent.dispose === 'function') ? () => agent.dispose() : deps.forceDispose);
|
|
2113
|
+
run.sessionId8 = run.sessionId8 ?? sessionId.slice(0, 8);
|
|
2114
|
+
runtime.activeRuns = runtime.activeRuns ?? new Map();
|
|
2115
|
+
runtime.activeRuns.set(sessionId, { runId: run.runId, ticketId: run.ticketId });
|
|
2116
|
+
return { sessionId, agent, dispose, created };
|
|
2117
|
+
}
|
|
2118
|
+
|
|
2119
|
+
async function disposeCreated(runtime, handle, run) {
|
|
2120
|
+
if (!handle) return false;
|
|
2121
|
+
runtime.activeRuns?.delete?.(handle.sessionId);
|
|
2122
|
+
const dispose = handle.dispose;
|
|
2123
|
+
if (typeof dispose !== 'function') return false;
|
|
2124
|
+
try {
|
|
2125
|
+
await withTimeout(Promise.resolve(dispose()), 1000, WAKE_CODES.TIMEOUT, 'dispose 超时');
|
|
2126
|
+
return true;
|
|
2127
|
+
} catch (error) {
|
|
2128
|
+
run?.errors?.push({ code: error?.code ?? WAKE_CODES.TIMEOUT, message: String(error?.message ?? error), phase: 'dispose' });
|
|
2129
|
+
return false;
|
|
2130
|
+
}
|
|
2131
|
+
}
|
|
2132
|
+
|
|
2133
|
+
// ---------------------------------------------------------------------------
|
|
2134
|
+
// 提议通道:auto-authz 规则表判定 + 审计(§3 / §6)
|
|
2135
|
+
// ---------------------------------------------------------------------------
|
|
2136
|
+
|
|
2137
|
+
function appendAuthzAudit(paths, entry) {
|
|
2138
|
+
const row = auditRow(entry);
|
|
2139
|
+
appendJsonl(paths.autoAuthz, { schema: WAKE_SCHEMAS.authz, ...row });
|
|
2140
|
+
rotateAuthzLog(paths, { now: entry.ts });
|
|
2141
|
+
return row;
|
|
2142
|
+
}
|
|
2143
|
+
|
|
2144
|
+
/**
|
|
2145
|
+
* 提交一条提议给本模块 auto-authz 规则表(AUTO 才写;ESCALATE/DENY 只记账)。
|
|
2146
|
+
* 后台会话只能通过 memory_wake propose 通道走到这里;插件核自己做写盘,模型不碰文件。
|
|
2147
|
+
*/
|
|
2148
|
+
export async function submitProposal(runtime, run, proposal, options = {}) {
|
|
2149
|
+
const paths = runtime.paths ?? asPaths(runtime.root);
|
|
2150
|
+
const now = nowDateOf(options.now ?? runtime.now?.() ?? Date.now());
|
|
2151
|
+
const at = isoOf(now);
|
|
2152
|
+
const startedAt = Date.now();
|
|
2153
|
+
const result = await authorizeAndApply({
|
|
2154
|
+
root: runtime.root,
|
|
2155
|
+
proposal,
|
|
2156
|
+
rules: runtime.authzRules ?? DEFAULT_RULES,
|
|
2157
|
+
usage: {
|
|
2158
|
+
perRun: run?.usage?.perRun ?? 0,
|
|
2159
|
+
perDay: runtime.dailyAuthz ?? 0,
|
|
2160
|
+
},
|
|
2161
|
+
now,
|
|
2162
|
+
maxFilesPerProposal: runtime.cfg?.maxFilesPerRun ?? WAKE_DEFAULTS.maxFilesPerRun,
|
|
2163
|
+
});
|
|
2164
|
+
const entry = {
|
|
2165
|
+
ts: at,
|
|
2166
|
+
runId: run?.runId ?? null,
|
|
2167
|
+
sessionId: run?.sessionId8 ?? null,
|
|
2168
|
+
proposalId: result.proposalId ?? proposal?.proposalId ?? null,
|
|
2169
|
+
kind: proposal?.kind ?? null,
|
|
2170
|
+
target: result.target ?? proposal?.target?.file ?? proposal?.target ?? null,
|
|
2171
|
+
paramsSha: result.paramsSha ?? null,
|
|
2172
|
+
verdict: result.verdict ?? 'DENY',
|
|
2173
|
+
ruleHits: result.ruleHits ?? [],
|
|
2174
|
+
reason: result.reason ?? null,
|
|
2175
|
+
code: result.code ?? null,
|
|
2176
|
+
beforeSha: result.beforeSha ?? null,
|
|
2177
|
+
afterSha: result.afterSha ?? null,
|
|
2178
|
+
result: result.applied === true ? 'applied' : 'not-applied',
|
|
2179
|
+
durationMs: typeof result.durationMs === 'number' ? result.durationMs : Date.now() - startedAt,
|
|
2180
|
+
tokens: null,
|
|
2181
|
+
};
|
|
2182
|
+
appendAuthzAudit(paths, entry);
|
|
2183
|
+
if (run) {
|
|
2184
|
+
run.verdicts = run.verdicts ?? [];
|
|
2185
|
+
run.verdicts.push({ proposalId: entry.proposalId, verdict: entry.verdict, ruleHits: entry.ruleHits, code: entry.code, applied: result.applied === true, paramsSha: entry.paramsSha });
|
|
2186
|
+
run.proposals = run.proposals ?? [];
|
|
2187
|
+
run.proposals.push({ proposalId: entry.proposalId, kind: entry.kind, target: entry.target, verdict: entry.verdict, applied: result.applied === true, ruleId: result.ruleId ?? null, code: entry.code, reason: entry.reason });
|
|
2188
|
+
}
|
|
2189
|
+
return {
|
|
2190
|
+
ok: result.verdict === 'AUTO' && result.applied === true,
|
|
2191
|
+
verdict: result.verdict,
|
|
2192
|
+
applied: result.applied === true,
|
|
2193
|
+
ruleId: result.ruleId ?? null,
|
|
2194
|
+
ruleHits: result.ruleHits ?? [],
|
|
2195
|
+
reason: result.reason ?? null,
|
|
2196
|
+
code: result.code ?? null,
|
|
2197
|
+
target: entry.target,
|
|
2198
|
+
proposalId: entry.proposalId,
|
|
2199
|
+
paramsSha: entry.paramsSha,
|
|
2200
|
+
beforeSha: entry.beforeSha,
|
|
2201
|
+
afterSha: entry.afterSha,
|
|
2202
|
+
bytes: result.bytes ?? null,
|
|
2203
|
+
};
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
// ---------------------------------------------------------------------------
|
|
2207
|
+
// 状态机主体:runWakeCycle(§6.1–6.2 / §6.3)
|
|
2208
|
+
// ---------------------------------------------------------------------------
|
|
2209
|
+
|
|
2210
|
+
function refused(state, paths, { at, code, reason, extra = {} }) {
|
|
2211
|
+
state.lastRun = { runId: null, status: 'refused', code, reason, at: isoOf(at) };
|
|
2212
|
+
try {
|
|
2213
|
+
writeWakeState(paths, state);
|
|
2214
|
+
} catch {
|
|
2215
|
+
// state 写不了也要让 panel 尽量可见。
|
|
2216
|
+
}
|
|
2217
|
+
const panel = refreshWakePanel(paths, { now: at, enabled: true, capability: state.capability ?? null });
|
|
2218
|
+
return { ok: true, ran: false, refused: reason, code, at: isoOf(at), panel, ...extra };
|
|
2219
|
+
}
|
|
2220
|
+
|
|
2221
|
+
function escalate(run, ticket, code, denial, paths, at) {
|
|
2222
|
+
const entry = {
|
|
2223
|
+
ts: isoOf(at),
|
|
2224
|
+
ticketId: String(ticket?.ticket ?? ticket?.id ?? ''),
|
|
2225
|
+
code,
|
|
2226
|
+
reason: `auto-review ${code === WAKE_CODES.DENIED ? 'denied' : 'unavailable'}`,
|
|
2227
|
+
ruleHits: denial?.codes ?? [],
|
|
2228
|
+
proposalSha: null,
|
|
2229
|
+
evidence: (denial?.entries ?? []).slice(0, 10),
|
|
2230
|
+
};
|
|
2231
|
+
const row = appendPending(paths, entry);
|
|
2232
|
+
run.escalations.push({ code, at: entry.ts, codes: denial?.codes ?? [], pendingId: row?.ts ?? null });
|
|
2233
|
+
run.status = 'escalated';
|
|
2234
|
+
run.code = code;
|
|
2235
|
+
return row;
|
|
2236
|
+
}
|
|
2237
|
+
|
|
2238
|
+
function finishRun(runtime, run, paths, at) {
|
|
2239
|
+
run.finishedAt = isoOf(at);
|
|
2240
|
+
return writeRunRecord(paths, run);
|
|
2241
|
+
}
|
|
2242
|
+
|
|
2243
|
+
/**
|
|
2244
|
+
* 一次唤醒循环(唯一状态机入口;由 pre-step / daily / memory_wake drain 调用)。
|
|
2245
|
+
*
|
|
2246
|
+
* @param {{runtime:object, trigger?:string, now?:Date}} input
|
|
2247
|
+
* @returns {Promise<object>} {ok, ran, runId?, status?, code?, refused?, ...}
|
|
2248
|
+
*/
|
|
2249
|
+
export async function runWakeCycle(input = {}) {
|
|
2250
|
+
const runtime = input?.runtime ?? input;
|
|
2251
|
+
const trigger = String(input?.trigger ?? 'tick');
|
|
2252
|
+
if (!runtime || typeof runtime !== 'object' || typeof runtime.root !== 'string' || runtime.root === '') {
|
|
2253
|
+
return { ok: false, ran: false, code: WAKE_CODES.ROOT_UNRESOLVED, reason: 'ROOT_UNRESOLVED' };
|
|
2254
|
+
}
|
|
2255
|
+
const paths = runtime.paths ?? asPaths(runtime.root);
|
|
2256
|
+
const cfg = runtime.cfg ?? WAKE_DEFAULTS;
|
|
2257
|
+
const at = nowOf({ now: input?.now !== undefined ? input.now : runtime.now });
|
|
2258
|
+
if (!cfg.enabled) return { ok: false, ran: false, code: WAKE_CODES.DISABLED, reason: 'DISABLED' };
|
|
2259
|
+
if (runtime.running) return { ok: false, ran: false, code: WAKE_CODES.BUSY, reason: 'BUSY' };
|
|
2260
|
+
|
|
2261
|
+
// 每次 run 前重探能力(§4);失败 → 0 会话 0 重试 + 可见。
|
|
2262
|
+
const probe = probeWakeCapabilities(runtime, { version: runtime.capabilityVersion, bundleList: runtime.bundleList });
|
|
2263
|
+
runtime.capability = probe.capability;
|
|
2264
|
+
if (!probe.ok) {
|
|
2265
|
+
safeGate(paths, GATE_EVENTS.WAKE_FAIL, { decision: 'fail', code: CAPABILITY_MISSING_CODE, reason: `capability ${probe.detail?.reason ?? 'missing'}` });
|
|
2266
|
+
const failedState = readWakeState(paths);
|
|
2267
|
+
failedState.capability = probe.capability;
|
|
2268
|
+
try {
|
|
2269
|
+
writeWakeState(paths, failedState);
|
|
2270
|
+
} catch {
|
|
2271
|
+
// 状态写不了也有 gate-log + panel 可见。
|
|
2272
|
+
}
|
|
2273
|
+
refreshWakePanel(paths, { now: at, enabled: cfg.enabled === true, capability: probe.capability });
|
|
2274
|
+
return { ok: false, ran: false, code: CAPABILITY_MISSING_CODE, capability: probe.capability, detail: probe.detail, retried: 0, created: 0 };
|
|
2275
|
+
}
|
|
2276
|
+
|
|
2277
|
+
const state = readWakeState(paths);
|
|
2278
|
+
state.enabled = true;
|
|
2279
|
+
state.capability = probe.capability;
|
|
2280
|
+
const dayKey = dateKeyOf(at);
|
|
2281
|
+
if (state.dayKey !== dayKey) {
|
|
2282
|
+
state.dayKey = dayKey;
|
|
2283
|
+
state.dayCount = 0;
|
|
2284
|
+
}
|
|
2285
|
+
const cooldownUntil = Date.parse(state.cooldownUntil ?? '');
|
|
2286
|
+
if (Number.isFinite(cooldownUntil) && cooldownUntil > at.getTime()) {
|
|
2287
|
+
const retryAfterSeconds = Math.ceil((cooldownUntil - at.getTime()) / 1000);
|
|
2288
|
+
return refused(state, paths, { at, code: WAKE_CODES.COOLDOWN, reason: 'COOLDOWN', extra: { retryAfterSeconds } });
|
|
2289
|
+
}
|
|
2290
|
+
if (Number(state.dayCount ?? 0) >= Number(cfg.maxPerDay ?? WAKE_DEFAULTS.maxPerDay)) {
|
|
2291
|
+
return refused(state, paths, { at, code: WAKE_CODES.QUOTA, reason: 'QUOTA', extra: { dayCount: state.dayCount, maxPerDay: cfg.maxPerDay } });
|
|
2292
|
+
}
|
|
2293
|
+
|
|
2294
|
+
const pick = pickTicket(paths, { now: at, retryMax: cfg.retryMax });
|
|
2295
|
+
if (!pick.ticket) {
|
|
2296
|
+
// 空队列:不建会话、不写 run(§7.2 c8)。
|
|
2297
|
+
return { ok: true, ran: false, refused: 'EMPTY', code: WAKE_CODES.EMPTY, reason: 'EMPTY', expired: pick.expired.length };
|
|
2298
|
+
}
|
|
2299
|
+
const ticket = pick.ticket;
|
|
2300
|
+
const startedAt = isoOf(at);
|
|
2301
|
+
const runId = `wake-${dayKey.replace(/-/g, '')}-${String(ticket.id).slice(-8)}-${randomUUID().slice(0, 8)}`;
|
|
2302
|
+
const run = {
|
|
2303
|
+
schema: WAKE_SCHEMAS.run,
|
|
2304
|
+
runId,
|
|
2305
|
+
ticketId: String(ticket.id ?? ''),
|
|
2306
|
+
trigger,
|
|
2307
|
+
startedAt,
|
|
2308
|
+
finishedAt: null,
|
|
2309
|
+
status: 'running',
|
|
2310
|
+
capabilitySnapshot: probe.capability,
|
|
2311
|
+
capabilityOk: true,
|
|
2312
|
+
configClamps: Array.isArray(cfg.clamps) ? cfg.clamps : [],
|
|
2313
|
+
sessionId8: null,
|
|
2314
|
+
retries: Number(ticket.retries ?? 0),
|
|
2315
|
+
rounds: null,
|
|
2316
|
+
tokens: null,
|
|
2317
|
+
outputChars: null,
|
|
2318
|
+
toolCalls: [],
|
|
2319
|
+
verdicts: [],
|
|
2320
|
+
proposals: [],
|
|
2321
|
+
escalations: [],
|
|
2322
|
+
errors: [],
|
|
2323
|
+
policy: null,
|
|
2324
|
+
receiptSha256: null,
|
|
2325
|
+
};
|
|
2326
|
+
runtime.running = { runId, startedAt };
|
|
2327
|
+
let handle = null;
|
|
2328
|
+
let outcome = { ok: false, ran: true, runId, status: 'failed' };
|
|
2329
|
+
try {
|
|
2330
|
+
markRunning(paths, ticket.id, { runId, startedAt, now: at });
|
|
2331
|
+
handle = await createWakeSession(runtime, run);
|
|
2332
|
+
await setGates(runtime, handle.agent, handle.sessionId);
|
|
2333
|
+
const prompt = buildWakePrompt(ticket, cfg);
|
|
2334
|
+
await handle.agent.followup(buildWakeMessage(prompt));
|
|
2335
|
+
await withTimeout(Promise.resolve(handle.agent.whenIdle()), Math.max(1000, Number(cfg.timeoutSeconds) * 1000), WAKE_CODES.TIMEOUT, `whenIdle 超过 ${cfg.timeoutSeconds}s`);
|
|
2336
|
+
const messages = readSessionMessages(runtime.deps, handle.agent);
|
|
2337
|
+
const denial = classifyDenials(messages);
|
|
2338
|
+
run.rounds = countRounds(messages);
|
|
2339
|
+
run.toolCalls = collectToolCalls(messages);
|
|
2340
|
+
const finalText = lastAssistantText(messages);
|
|
2341
|
+
run.outputChars = finalText === '' ? 0 : clampText(finalText, cfg.maxOutputChars).length;
|
|
2342
|
+
run.outputCharsRaw = finalText.length;
|
|
2343
|
+
run.outputOverBudget = finalText.length > cfg.maxOutputChars;
|
|
2344
|
+
run.roundsOverBudget = run.rounds > cfg.maxRounds;
|
|
2345
|
+
if (denial.denied || denial.unavailable) {
|
|
2346
|
+
const code = denial.denied ? WAKE_CODES.DENIED : WAKE_CODES.REVIEW_UNAVAILABLE;
|
|
2347
|
+
escalate(run, ticket, code, denial, paths, at);
|
|
2348
|
+
markDone(paths, ticket.id, { status: 'escalated', now: at, runId });
|
|
2349
|
+
state.totals.escalated = Number(state.totals.escalated ?? 0) + 1;
|
|
2350
|
+
state.lastRun = { runId, status: 'escalated', code, at: isoOf(at) };
|
|
2351
|
+
} else {
|
|
2352
|
+
run.status = 'done';
|
|
2353
|
+
markDone(paths, ticket.id, { status: 'done', now: at, runId });
|
|
2354
|
+
state.totals.runs = Number(state.totals.runs ?? 0) + 1;
|
|
2355
|
+
state.lastRun = { runId, status: 'done', code: null, at: isoOf(at) };
|
|
2356
|
+
}
|
|
2357
|
+
state.dayCount = Number(state.dayCount ?? 0) + 1;
|
|
2358
|
+
state.cooldownUntil = new Date(at.getTime() + Number(cfg.cooldownSeconds) * 1000).toISOString();
|
|
2359
|
+
state.seq = Number(state.seq ?? 0) + 1;
|
|
2360
|
+
state.lastTicketId = String(ticket.ticket ?? ticket.id ?? '');
|
|
2361
|
+
outcome = { ok: run.status === 'done', ran: true, runId, ticketId: run.ticketId, status: run.status, code: run.code ?? null };
|
|
2362
|
+
} catch (error) {
|
|
2363
|
+
const code = error?.code ?? WAKE_CODES.UNEXPECTED;
|
|
2364
|
+
run.status = 'failed';
|
|
2365
|
+
run.code = code;
|
|
2366
|
+
run.errors.push({ code, message: String(error?.message ?? error), phase: 'run' });
|
|
2367
|
+
const failed = markFailed(paths, ticket.id, { code, message: String(error?.message ?? error), runId, now: at, retryMax: cfg.retryMax });
|
|
2368
|
+
if (failed.expired) {
|
|
2369
|
+
run.status = 'expired';
|
|
2370
|
+
run.expired = true;
|
|
2371
|
+
}
|
|
2372
|
+
run.retries = failed.retries ?? run.retries;
|
|
2373
|
+
run.attempts = failed.retries ?? null;
|
|
2374
|
+
safeGate(paths, GATE_EVENTS.WAKE_FAIL, { decision: 'fail', code, reason: String(error?.message ?? error), evidence: [runId, String(ticket.id ?? '')] });
|
|
2375
|
+
state.totals.failed = Number(state.totals.failed ?? 0) + 1;
|
|
2376
|
+
state.lastRun = { runId, status: run.status, code, at: isoOf(at) };
|
|
2377
|
+
// 超时/结构失败也要硬取消(whenIdle 已超时 → cancel 后走 dispose)。
|
|
2378
|
+
if (handle?.agent && typeof handle.agent.cancel === 'function') {
|
|
2379
|
+
try {
|
|
2380
|
+
handle.agent.cancel();
|
|
2381
|
+
} catch {
|
|
2382
|
+
// 取消失败由 dispose 兜底。
|
|
2383
|
+
}
|
|
2384
|
+
}
|
|
2385
|
+
outcome = { ok: false, ran: true, runId, ticketId: run.ticketId, status: run.status, code, retried: !failed.expired, expired: failed.expired === true };
|
|
2386
|
+
} finally {
|
|
2387
|
+
state.capability = probe.capability;
|
|
2388
|
+
if (handle) await disposeCreated(runtime, handle, run);
|
|
2389
|
+
const finishedAt = isoOf(nowOf({ now: input?.now !== undefined ? input.now : runtime.now }));
|
|
2390
|
+
run.finishedAt = finishedAt;
|
|
2391
|
+
try {
|
|
2392
|
+
finishRun(runtime, run, paths, new Date(finishedAt));
|
|
2393
|
+
} catch (error) {
|
|
2394
|
+
run.errors.push({ code: error?.code ?? WAKE_CODES.STORE_WRITE_FAILED, message: String(error?.message ?? error), phase: 'record' });
|
|
2395
|
+
}
|
|
2396
|
+
try {
|
|
2397
|
+
writeWakeState(paths, state);
|
|
2398
|
+
} catch {
|
|
2399
|
+
// 状态写不了由 panel/gate 兜底。
|
|
2400
|
+
}
|
|
2401
|
+
refreshWakePanel(paths, { now: new Date(finishedAt), enabled: true, capability: probe.capability });
|
|
2402
|
+
runtime.running = null;
|
|
2403
|
+
}
|
|
2404
|
+
return outcome;
|
|
2405
|
+
}
|
|
2406
|
+
// ---------------------------------------------------------------------------
|
|
2407
|
+
// 进程内注册表(按 memoryRoot 解析,同进程多根互不串)
|
|
2408
|
+
// ---------------------------------------------------------------------------
|
|
2409
|
+
|
|
2410
|
+
const RUNTIMES = new Map();
|
|
2411
|
+
|
|
2412
|
+
function runtimeFor(input) {
|
|
2413
|
+
const {
|
|
2414
|
+
ctx = null,
|
|
2415
|
+
root,
|
|
2416
|
+
paths,
|
|
2417
|
+
cfg,
|
|
2418
|
+
deps,
|
|
2419
|
+
now,
|
|
2420
|
+
capability = null,
|
|
2421
|
+
warnings = [],
|
|
2422
|
+
bundleList = null,
|
|
2423
|
+
capabilityVersion = null,
|
|
2424
|
+
authzRules = null,
|
|
2425
|
+
} = input;
|
|
2426
|
+
return {
|
|
2427
|
+
ctx,
|
|
2428
|
+
root,
|
|
2429
|
+
paths: paths ?? wakePaths(root),
|
|
2430
|
+
cfg,
|
|
2431
|
+
deps,
|
|
2432
|
+
now: typeof now === 'function' ? now : (now === undefined ? undefined : (() => nowDateOf(now))),
|
|
2433
|
+
capability,
|
|
2434
|
+
bundleList,
|
|
2435
|
+
capabilityVersion,
|
|
2436
|
+
warnings,
|
|
2437
|
+
authzRules: authzRules ?? DEFAULT_RULES,
|
|
2438
|
+
dailyAuthz: 0,
|
|
2439
|
+
activeRuns: new Map(),
|
|
2440
|
+
running: null,
|
|
2441
|
+
disposed: false,
|
|
2442
|
+
};
|
|
2443
|
+
}
|
|
2444
|
+
|
|
2445
|
+
/** 当前已注册的 runtime(只读诊断用;工具/夹具可据此判断「启用」还是「未启用」)。 */
|
|
2446
|
+
export function getWakeRuntime(memoryRoot) {
|
|
2447
|
+
try {
|
|
2448
|
+
return RUNTIMES.get(path.resolve(String(memoryRoot))) ?? null;
|
|
2449
|
+
} catch {
|
|
2450
|
+
return null;
|
|
2451
|
+
}
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
// ---------------------------------------------------------------------------
|
|
2455
|
+
// 应用唤醒桥:能力探测 → 依赖检查 → runtime 注册(§4 / §5)
|
|
2456
|
+
// ---------------------------------------------------------------------------
|
|
2457
|
+
|
|
2458
|
+
function disabledBridge(input) {
|
|
2459
|
+
const { enabled = false, cfg = null, root = null, paths = null, reason, code = null, capability = null, detail = null, warnings = [], runtime = null, extra = {} } = input;
|
|
2460
|
+
return {
|
|
2461
|
+
enabled,
|
|
2462
|
+
registered: false,
|
|
2463
|
+
cfg,
|
|
2464
|
+
root,
|
|
2465
|
+
paths,
|
|
2466
|
+
reason,
|
|
2467
|
+
code,
|
|
2468
|
+
capability,
|
|
2469
|
+
detail,
|
|
2470
|
+
warnings,
|
|
2471
|
+
runtime,
|
|
2472
|
+
dispose: () => {},
|
|
2473
|
+
...extra,
|
|
2474
|
+
};
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
/**
|
|
2478
|
+
* 建立唤醒桥运行期(不注册钩子;钩子由 registerHardgateWake 装)。
|
|
2479
|
+
* 失败一律 fail-closed 且可见(gate-log + panel.capability),绝不静默降级。
|
|
2480
|
+
*/
|
|
2481
|
+
export function applyWakeBridge(ctx, options = {}) {
|
|
2482
|
+
const warn = typeof options.warn === 'function' ? options.warn : null;
|
|
2483
|
+
const cfg = options.cfg ?? normalizeWakeConfig(options.config ?? {}, { warn });
|
|
2484
|
+
const warnings = Array.isArray(cfg.warnings) ? cfg.warnings : [];
|
|
2485
|
+
if (cfg.enabled !== true) {
|
|
2486
|
+
return disabledBridge({ enabled: false, cfg, reason: 'DISABLED', code: WAKE_CODES.DISABLED, warnings });
|
|
2487
|
+
}
|
|
2488
|
+
const memoryRoot = options.memoryRoot ?? null;
|
|
2489
|
+
if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') {
|
|
2490
|
+
return disabledBridge({ enabled: false, cfg, reason: 'ROOT_UNRESOLVED', code: WAKE_CODES.ROOT_UNRESOLVED, warnings });
|
|
2491
|
+
}
|
|
2492
|
+
const root = path.resolve(memoryRoot);
|
|
2493
|
+
const paths = wakePaths(root);
|
|
2494
|
+
const at = nowDateOf(options.now);
|
|
2495
|
+
|
|
2496
|
+
// 能力探测(§4):同步一次;失败 → enabled=false + 码 + 可见,0 会话 0 重试。
|
|
2497
|
+
const probe = probeWakeCapabilities(
|
|
2498
|
+
{ ctx, bundleList: options.bundleList, capabilityVersion: options.capabilityVersion },
|
|
2499
|
+
{ version: options.capabilityVersion, bundleList: options.bundleList },
|
|
2500
|
+
);
|
|
2501
|
+
if (!probe.ok) {
|
|
2502
|
+
safeGate(paths, GATE_EVENTS.WAKE_FAIL, {
|
|
2503
|
+
decision: 'fail',
|
|
2504
|
+
code: CAPABILITY_MISSING_CODE,
|
|
2505
|
+
reason: `capability ${probe.detail?.reason ?? 'missing'}`,
|
|
2506
|
+
evidence: [`version=${probe.capability?.version ?? 'unknown'}`],
|
|
2507
|
+
});
|
|
2508
|
+
try {
|
|
2509
|
+
const state = readWakeState(paths);
|
|
2510
|
+
state.enabled = false;
|
|
2511
|
+
state.capability = probe.capability;
|
|
2512
|
+
writeWakeState(paths, state);
|
|
2513
|
+
} catch {
|
|
2514
|
+
// 状态写不了也有 gate-log + panel。
|
|
2515
|
+
}
|
|
2516
|
+
refreshWakePanel(paths, { now: at, enabled: false, capability: probe.capability });
|
|
2517
|
+
return disabledBridge({
|
|
2518
|
+
enabled: false,
|
|
2519
|
+
cfg,
|
|
2520
|
+
root,
|
|
2521
|
+
paths,
|
|
2522
|
+
reason: 'CAPABILITY_MISSING',
|
|
2523
|
+
code: CAPABILITY_MISSING_CODE,
|
|
2524
|
+
capability: probe.capability,
|
|
2525
|
+
detail: probe.detail,
|
|
2526
|
+
warnings,
|
|
2527
|
+
});
|
|
2528
|
+
}
|
|
2529
|
+
|
|
2530
|
+
const deps = resolveDeps(ctx, options);
|
|
2531
|
+
const missing = [];
|
|
2532
|
+
if (typeof deps.agents?.create !== 'function') missing.push('agents.create');
|
|
2533
|
+
if (typeof deps.permissionPresets?.set !== 'function') missing.push('permissionPresets.set');
|
|
2534
|
+
if (typeof deps.approval?.setPolicy !== 'function') missing.push('approval.setPolicy');
|
|
2535
|
+
if (typeof deps.installToolPolicy !== 'function') missing.push('installToolPolicy');
|
|
2536
|
+
if (missing.length > 0) {
|
|
2537
|
+
safeGate(paths, GATE_EVENTS.WAKE_FAIL, { decision: 'fail', code: WAKE_CODES.DEPS_MISSING, reason: missing.join(','), evidence: missing });
|
|
2538
|
+
try {
|
|
2539
|
+
const state = readWakeState(paths);
|
|
2540
|
+
state.enabled = false;
|
|
2541
|
+
state.capability = probe.capability;
|
|
2542
|
+
writeWakeState(paths, state);
|
|
2543
|
+
} catch {
|
|
2544
|
+
// 同上。
|
|
2545
|
+
}
|
|
2546
|
+
refreshWakePanel(paths, { now: at, enabled: false, capability: probe.capability });
|
|
2547
|
+
return disabledBridge({
|
|
2548
|
+
enabled: false,
|
|
2549
|
+
cfg,
|
|
2550
|
+
root,
|
|
2551
|
+
paths,
|
|
2552
|
+
reason: 'DEPS_MISSING',
|
|
2553
|
+
code: WAKE_CODES.DEPS_MISSING,
|
|
2554
|
+
capability: probe.capability,
|
|
2555
|
+
detail: { missing },
|
|
2556
|
+
warnings,
|
|
2557
|
+
});
|
|
2558
|
+
}
|
|
2559
|
+
|
|
2560
|
+
const runtime = runtimeFor({
|
|
2561
|
+
ctx,
|
|
2562
|
+
root,
|
|
2563
|
+
paths,
|
|
2564
|
+
cfg,
|
|
2565
|
+
deps,
|
|
2566
|
+
now: options.now,
|
|
2567
|
+
capability: probe.capability,
|
|
2568
|
+
warnings,
|
|
2569
|
+
bundleList: options.bundleList ?? null,
|
|
2570
|
+
capabilityVersion: options.capabilityVersion ?? null,
|
|
2571
|
+
authzRules: options.authzRules ?? null,
|
|
2572
|
+
});
|
|
2573
|
+
RUNTIMES.set(root, runtime);
|
|
2574
|
+
|
|
2575
|
+
// 启用瞬间同步一次状态与面板(可见性;不建会话)。
|
|
2576
|
+
try {
|
|
2577
|
+
const state = readWakeState(paths);
|
|
2578
|
+
state.enabled = true;
|
|
2579
|
+
state.capability = probe.capability;
|
|
2580
|
+
state.lastPruneAt = isoOf(at);
|
|
2581
|
+
writeWakeState(paths, state);
|
|
2582
|
+
} catch (error) {
|
|
2583
|
+
safeGate(paths, GATE_EVENTS.WAKE_FAIL, { decision: 'fail', code: error?.code ?? WAKE_CODES.STORE_WRITE_FAILED, reason: error?.message ?? String(error) });
|
|
2584
|
+
}
|
|
2585
|
+
refreshWakePanel(paths, { now: at, enabled: true, capability: probe.capability });
|
|
2586
|
+
|
|
2587
|
+
const dispose = () => {
|
|
2588
|
+
if (runtime.disposed) return;
|
|
2589
|
+
runtime.disposed = true;
|
|
2590
|
+
runtime.cfg = { ...runtime.cfg, enabled: false };
|
|
2591
|
+
if (RUNTIMES.get(root) === runtime) RUNTIMES.delete(root);
|
|
2592
|
+
};
|
|
2593
|
+
return {
|
|
2594
|
+
enabled: true,
|
|
2595
|
+
registered: false,
|
|
2596
|
+
cfg,
|
|
2597
|
+
root,
|
|
2598
|
+
paths,
|
|
2599
|
+
reason: 'ENABLED',
|
|
2600
|
+
code: null,
|
|
2601
|
+
capability: probe.capability,
|
|
2602
|
+
detail: { missing: [] },
|
|
2603
|
+
warnings,
|
|
2604
|
+
runtime,
|
|
2605
|
+
dispose,
|
|
2606
|
+
};
|
|
2607
|
+
}
|
|
2608
|
+
|
|
2609
|
+
// ---------------------------------------------------------------------------
|
|
2610
|
+
// daily 对账定时器(§5:独立 timer,不共用 autoMaintenance scheduler)
|
|
2611
|
+
// ---------------------------------------------------------------------------
|
|
2612
|
+
|
|
2613
|
+
/**
|
|
2614
|
+
* daily 对账:reconcileWakeStore + 到期 failed 票重试 + 重建 panel。
|
|
2615
|
+
* 只由 registerHardgateWake 启动;运行失败降级为 gate-log fail,不阻塞主会话。
|
|
2616
|
+
*/
|
|
2617
|
+
export function createWakeDaily(options = {}) {
|
|
2618
|
+
const rootRaw = options.root ?? options.memoryRoot;
|
|
2619
|
+
if (typeof rootRaw !== 'string' || rootRaw.trim() === '') throw wakeError(WAKE_CODES.ROOT_UNRESOLVED, 'createWakeDaily 缺少 memoryRoot');
|
|
2620
|
+
const root = path.resolve(rootRaw);
|
|
2621
|
+
const paths = wakePaths(root);
|
|
2622
|
+
const cfg = options.cfg ?? WAKE_DEFAULTS;
|
|
2623
|
+
const timers = options.timers ?? { setTimeout, clearTimeout };
|
|
2624
|
+
const warn = typeof options.warn === 'function' ? options.warn : null;
|
|
2625
|
+
const nowFn = () => nowDateOf(typeof options.now === 'function' ? options.now() : options.now);
|
|
2626
|
+
let timer = null;
|
|
2627
|
+
let stopped = false;
|
|
2628
|
+
let cycles = 0;
|
|
2629
|
+
let last = null;
|
|
2630
|
+
|
|
2631
|
+
const runOnce = async () => {
|
|
2632
|
+
if (stopped) return null;
|
|
2633
|
+
const at = nowFn();
|
|
2634
|
+
let summary = null;
|
|
2635
|
+
try {
|
|
2636
|
+
summary = reconcileWakeStore(paths, { now: at, retryMax: cfg.retryMax, queueMax: cfg.queueMax, enabled: cfg.enabled === true });
|
|
2637
|
+
} catch (error) {
|
|
2638
|
+
safeGate(paths, GATE_EVENTS.WAKE_FAIL, { decision: 'fail', code: error?.code ?? WAKE_CODES.STORE_WRITE_FAILED, reason: error?.message ?? String(error), evidence: ['daily-reconcile'] });
|
|
2639
|
+
return null;
|
|
2640
|
+
}
|
|
2641
|
+
// 到期 failed 票重试(同一天内 daily 也补一次;runWakeCycle 自己会限并发/冷却)。
|
|
2642
|
+
try {
|
|
2643
|
+
const runtime = options.runtime ?? RUNTIMES.get(root) ?? null;
|
|
2644
|
+
if (runtime && cfg.enabled === true && runtime.running === null) {
|
|
2645
|
+
const picked = pickTicket(paths, { now: at, retryMax: cfg.retryMax });
|
|
2646
|
+
if (picked.ticket) await runWakeCycle({ runtime, trigger: 'daily', now: at });
|
|
2647
|
+
}
|
|
2648
|
+
} catch (error) {
|
|
2649
|
+
safeGate(paths, GATE_EVENTS.WAKE_FAIL, { decision: 'fail', code: error?.code ?? WAKE_CODES.UNEXPECTED, reason: error?.message ?? String(error), evidence: ['daily-retry'] });
|
|
2650
|
+
}
|
|
2651
|
+
cycles += 1;
|
|
2652
|
+
last = { at: isoOf(at), cycles };
|
|
2653
|
+
return summary;
|
|
2654
|
+
};
|
|
2655
|
+
|
|
2656
|
+
const schedule = () => {
|
|
2657
|
+
if (stopped) return;
|
|
2658
|
+
const at = nowFn();
|
|
2659
|
+
const next = nextLocalMidnight(at, MIDNIGHT_PAD_MS);
|
|
2660
|
+
const delay = Math.max(1000, next.getTime() - at.getTime());
|
|
2661
|
+
timer = timers.setTimeout(async () => {
|
|
2662
|
+
try {
|
|
2663
|
+
await runOnce();
|
|
2664
|
+
} finally {
|
|
2665
|
+
schedule();
|
|
2666
|
+
}
|
|
2667
|
+
}, delay);
|
|
2668
|
+
if (timer && typeof timer.unref === 'function') timer.unref();
|
|
2669
|
+
};
|
|
2670
|
+
|
|
2671
|
+
return {
|
|
2672
|
+
root,
|
|
2673
|
+
paths,
|
|
2674
|
+
get active() {
|
|
2675
|
+
return timer !== null && !stopped;
|
|
2676
|
+
},
|
|
2677
|
+
get stopped() {
|
|
2678
|
+
return stopped;
|
|
2679
|
+
},
|
|
2680
|
+
get cycles() {
|
|
2681
|
+
return cycles;
|
|
2682
|
+
},
|
|
2683
|
+
get last() {
|
|
2684
|
+
return last;
|
|
2685
|
+
},
|
|
2686
|
+
runOnce,
|
|
2687
|
+
start() {
|
|
2688
|
+
if (stopped) return this;
|
|
2689
|
+
if (cfg.runOnStart !== false) {
|
|
2690
|
+
void Promise.resolve()
|
|
2691
|
+
.then(() => runOnce())
|
|
2692
|
+
.catch((error) => {
|
|
2693
|
+
if (warn) warn(`[longlive] hardgate.wake daily 首跑失败: ${error?.message ?? error}`);
|
|
2694
|
+
});
|
|
2695
|
+
}
|
|
2696
|
+
schedule();
|
|
2697
|
+
return this;
|
|
2698
|
+
},
|
|
2699
|
+
stop() {
|
|
2700
|
+
stopped = true;
|
|
2701
|
+
if (timer) {
|
|
2702
|
+
try {
|
|
2703
|
+
timers.clearTimeout(timer);
|
|
2704
|
+
} catch {
|
|
2705
|
+
// ignore
|
|
2706
|
+
}
|
|
2707
|
+
}
|
|
2708
|
+
timer = null;
|
|
2709
|
+
},
|
|
2710
|
+
};
|
|
2711
|
+
}
|
|
2712
|
+
|
|
2713
|
+
// ---------------------------------------------------------------------------
|
|
2714
|
+
// 注册(pre-step 常驻钩子 + daily),features.js 只调这一个入口
|
|
2715
|
+
// ---------------------------------------------------------------------------
|
|
2716
|
+
|
|
2717
|
+
const SUBAGENT_ORIGINS = new Set(['subagent', 'sub-agent', 'delegated']);
|
|
2718
|
+
|
|
2719
|
+
function isSubagentPayload(payload) {
|
|
2720
|
+
if (!payload || typeof payload !== 'object') return false;
|
|
2721
|
+
if (payload.isSubagent === true) return true;
|
|
2722
|
+
if (typeof payload.origin === 'string' && SUBAGENT_ORIGINS.has(payload.origin)) return true;
|
|
2723
|
+
if (payload.agent && payload.agent.isSubagent === true) return true;
|
|
2724
|
+
return false;
|
|
2725
|
+
}
|
|
2726
|
+
|
|
2727
|
+
/**
|
|
2728
|
+
* 注册 hardgate.wake:
|
|
2729
|
+
* 1) applyWakeBridge(能力探测 + 依赖检查 + runtime);
|
|
2730
|
+
* 2) pre-step 常驻钩子(role kernel 之后注入;step!==1 或子代理直接 next);
|
|
2731
|
+
* 3) daily 对账定时器(独立 timer;ctx.effect 由 features.js 负责 dispose)。
|
|
2732
|
+
*
|
|
2733
|
+
* @param {object} ctx cordis 上下文
|
|
2734
|
+
* @param {object} rawCfg config.hardgate.wake 原始配置(raw passthrough)
|
|
2735
|
+
* @param {object} options {memoryRoot, now, warn, timers, installToolPolicy, ...}
|
|
2736
|
+
*/
|
|
2737
|
+
export function registerHardgateWake(ctx, rawCfg = {}, options = {}) {
|
|
2738
|
+
const warn = typeof options.warn === 'function' ? options.warn : null;
|
|
2739
|
+
const cfg = options.cfg ?? normalizeWakeConfig(rawCfg, { warn });
|
|
2740
|
+
let bridge = options.bridge ?? applyWakeBridge(ctx, { ...options, cfg, config: rawCfg, warn });
|
|
2741
|
+
|
|
2742
|
+
// 版本取不到(version-unknown)时保留一次异步升级通道(pluginManager.listBundles);
|
|
2743
|
+
// 其余能力缺失(形状/resolve/版本不符)一律立即 fail-closed,不注册钩子。
|
|
2744
|
+
const upgradeable = bridge.enabled !== true
|
|
2745
|
+
&& bridge.code === CAPABILITY_MISSING_CODE
|
|
2746
|
+
&& bridge.detail?.reason === 'version-unknown';
|
|
2747
|
+
if (!bridge.enabled && !upgradeable) return { ...bridge, registered: false, preStep: false, daily: null, capabilityRefresh: async () => false };
|
|
2748
|
+
|
|
2749
|
+
const disposers = [];
|
|
2750
|
+
// 1) pre-step 常驻钩子({prepend:false}:排在 working-frame 等内建注入之后)。
|
|
2751
|
+
const handler = async (payload, next) => {
|
|
2752
|
+
if (Number(payload?.step ?? 1) !== 1) return next();
|
|
2753
|
+
if (isSubagentPayload(payload)) return next();
|
|
2754
|
+
const result = await next();
|
|
2755
|
+
try {
|
|
2756
|
+
const paths = bridge.paths;
|
|
2757
|
+
const runtime = bridge.runtime;
|
|
2758
|
+
if (bridge.enabled === true && runtime && runtime.cfg?.enabled === true && runtime.running === null && readQueue(paths).length > 0) {
|
|
2759
|
+
void drainWakeQueue({ runtime, trigger: 'pre-step' }).catch(() => {});
|
|
2760
|
+
}
|
|
2761
|
+
} catch {
|
|
2762
|
+
// 唤醒失败不能影响主会话 pre-step 结果。
|
|
2763
|
+
}
|
|
2764
|
+
return result;
|
|
2765
|
+
};
|
|
2766
|
+
let preStep = false;
|
|
2767
|
+
try {
|
|
2768
|
+
if (typeof ctx?.on === 'function') {
|
|
2769
|
+
const off = ctx.on('agent/pre-step', handler, { prepend: false });
|
|
2770
|
+
if (typeof off === 'function') disposers.push(off);
|
|
2771
|
+
else if (typeof off?.dispose === 'function') disposers.push(() => off.dispose());
|
|
2772
|
+
preStep = true;
|
|
2773
|
+
} else if (warn) {
|
|
2774
|
+
warn('[longlive] hardgate.wake: ctx.on 不可用,pre-step 钩子未注册');
|
|
2775
|
+
}
|
|
2776
|
+
} catch (error) {
|
|
2777
|
+
if (warn) warn(`[longlive] hardgate.wake: pre-step 注册失败 ${error?.message ?? error}`);
|
|
2778
|
+
}
|
|
2779
|
+
|
|
2780
|
+
// 2) daily 对账(独立 timer;能力升级成功后再启动)。
|
|
2781
|
+
let daily = null;
|
|
2782
|
+
const startDaily = () => {
|
|
2783
|
+
if (daily || bridge.enabled !== true) return;
|
|
2784
|
+
try {
|
|
2785
|
+
daily = options.daily ?? createWakeDaily({
|
|
2786
|
+
root: bridge.root,
|
|
2787
|
+
cfg: bridge.cfg,
|
|
2788
|
+
runtime: bridge.runtime,
|
|
2789
|
+
now: options.now,
|
|
2790
|
+
timers: options.timers,
|
|
2791
|
+
warn,
|
|
2792
|
+
});
|
|
2793
|
+
daily.start();
|
|
2794
|
+
disposers.push(() => daily.stop());
|
|
2795
|
+
} catch (error) {
|
|
2796
|
+
daily = null;
|
|
2797
|
+
if (warn) warn(`[longlive] hardgate.wake: daily 定时器启动失败 ${error?.message ?? error}`);
|
|
2798
|
+
safeGate(bridge.paths, GATE_EVENTS.WAKE_FAIL, { decision: 'fail', code: error?.code ?? WAKE_CODES.STORE_WRITE_FAILED, reason: error?.message ?? String(error), evidence: ['daily-start'] });
|
|
2799
|
+
}
|
|
2800
|
+
};
|
|
2801
|
+
startDaily();
|
|
2802
|
+
|
|
2803
|
+
// 3) 版本异步升级(只在 sync=version-unknown 时走;不可升级时不调用)。
|
|
2804
|
+
const capabilityRefresh = async () => {
|
|
2805
|
+
if (bridge.enabled === true) return true;
|
|
2806
|
+
const found = await resolveAutoReviewVersionAsync(ctx, options);
|
|
2807
|
+
if (!found) return false;
|
|
2808
|
+
const next = applyWakeBridge(ctx, { ...options, cfg, config: rawCfg, warn, capabilityVersion: found.version });
|
|
2809
|
+
if (next.enabled !== true) {
|
|
2810
|
+
safeGate(next.paths ?? bridge.paths, GATE_EVENTS.WAKE_CAPABILITY, {
|
|
2811
|
+
decision: 'fail',
|
|
2812
|
+
code: CAPABILITY_MISSING_CODE,
|
|
2813
|
+
reason: `capability-refresh ${next.detail?.reason ?? 'rejected'}`,
|
|
2814
|
+
evidence: [`version=${found.version}`, `source=${found.source}`],
|
|
2815
|
+
});
|
|
2816
|
+
return false;
|
|
2817
|
+
}
|
|
2818
|
+
bridge = next;
|
|
2819
|
+
startDaily();
|
|
2820
|
+
safeGate(bridge.paths, GATE_EVENTS.WAKE_CAPABILITY, {
|
|
2821
|
+
decision: 'ok',
|
|
2822
|
+
reason: 'capability-version-refreshed',
|
|
2823
|
+
evidence: [`version=${found.version}`, `source=${found.source}`],
|
|
2824
|
+
});
|
|
2825
|
+
return true;
|
|
2826
|
+
};
|
|
2827
|
+
if (upgradeable) {
|
|
2828
|
+
void Promise.resolve()
|
|
2829
|
+
.then(() => capabilityRefresh())
|
|
2830
|
+
.catch((error) => {
|
|
2831
|
+
if (warn) warn(`[longlive] hardgate.wake: 能力异步升级失败 ${error?.message ?? error}`);
|
|
2832
|
+
});
|
|
2833
|
+
}
|
|
2834
|
+
|
|
2835
|
+
const dispose = () => {
|
|
2836
|
+
for (const fn of disposers.reverse()) {
|
|
2837
|
+
try {
|
|
2838
|
+
fn();
|
|
2839
|
+
} catch {
|
|
2840
|
+
// dispose 逐个兜底。
|
|
2841
|
+
}
|
|
2842
|
+
}
|
|
2843
|
+
bridge.dispose?.();
|
|
2844
|
+
};
|
|
2845
|
+
return {
|
|
2846
|
+
get enabled() {
|
|
2847
|
+
return bridge.enabled === true;
|
|
2848
|
+
},
|
|
2849
|
+
get registered() {
|
|
2850
|
+
return true;
|
|
2851
|
+
},
|
|
2852
|
+
get cfg() {
|
|
2853
|
+
return bridge.cfg;
|
|
2854
|
+
},
|
|
2855
|
+
get root() {
|
|
2856
|
+
return bridge.root;
|
|
2857
|
+
},
|
|
2858
|
+
get paths() {
|
|
2859
|
+
return bridge.paths;
|
|
2860
|
+
},
|
|
2861
|
+
get runtime() {
|
|
2862
|
+
return bridge.runtime;
|
|
2863
|
+
},
|
|
2864
|
+
get capability() {
|
|
2865
|
+
return bridge.capability;
|
|
2866
|
+
},
|
|
2867
|
+
get detail() {
|
|
2868
|
+
return bridge.detail;
|
|
2869
|
+
},
|
|
2870
|
+
get code() {
|
|
2871
|
+
return bridge.code;
|
|
2872
|
+
},
|
|
2873
|
+
preStep,
|
|
2874
|
+
get daily() {
|
|
2875
|
+
return daily;
|
|
2876
|
+
},
|
|
2877
|
+
capabilityRefresh,
|
|
2878
|
+
dispose,
|
|
2879
|
+
};
|
|
2880
|
+
}
|
|
2881
|
+
|
|
2882
|
+
// ---------------------------------------------------------------------------
|
|
2883
|
+
// 外部触发入口:drain / status / memory_wake 工具
|
|
2884
|
+
// ---------------------------------------------------------------------------
|
|
2885
|
+
|
|
2886
|
+
/**
|
|
2887
|
+
* 排空队列入口(pre-step / daily / memory_wake drain 共用)。
|
|
2888
|
+
* 未注册(插件未启用)时返回 E_WAKE_DISABLED(不建会话、不重试、不写队列)。
|
|
2889
|
+
*/
|
|
2890
|
+
export async function drainWakeQueue(input = {}) {
|
|
2891
|
+
const rootRaw = input?.root ?? input?.memoryRoot ?? input?.runtime?.root ?? null;
|
|
2892
|
+
if (typeof rootRaw !== 'string' || rootRaw.trim() === '') {
|
|
2893
|
+
return { ok: false, ran: false, code: WAKE_CODES.ROOT_UNRESOLVED, reason: 'ROOT_UNRESOLVED' };
|
|
2894
|
+
}
|
|
2895
|
+
const root = path.resolve(rootRaw);
|
|
2896
|
+
const paths = wakePaths(root);
|
|
2897
|
+
const runtime = input?.runtime ?? RUNTIMES.get(root) ?? null;
|
|
2898
|
+
if (!runtime || runtime.cfg?.enabled !== true) {
|
|
2899
|
+
const state = readWakeState(paths);
|
|
2900
|
+
const panel = readWakePanel(paths);
|
|
2901
|
+
const capability = runtime?.capability ?? state.capability ?? panel?.capability ?? null;
|
|
2902
|
+
const code = capability?.code === CAPABILITY_MISSING_CODE ? CAPABILITY_MISSING_CODE : WAKE_CODES.DISABLED;
|
|
2903
|
+
return { ok: false, ran: false, code, reason: code === CAPABILITY_MISSING_CODE ? 'CAPABILITY_MISSING' : 'DISABLED', enabled: false, capability };
|
|
2904
|
+
}
|
|
2905
|
+
if (runtime.running) return { ok: false, ran: false, code: WAKE_CODES.BUSY, reason: 'BUSY' };
|
|
2906
|
+
return runWakeCycle({ runtime, trigger: input?.trigger ?? 'manual', now: input?.now });
|
|
2907
|
+
}
|
|
2908
|
+
|
|
2909
|
+
/** memory_wake status 的只读报告(不含会话、不建会话、不写文件)。 */
|
|
2910
|
+
export function wakeStatusReport(input = {}) {
|
|
2911
|
+
const rootRaw = input?.root ?? input?.memoryRoot ?? input?.memoryRootPath ?? null;
|
|
2912
|
+
if (typeof rootRaw !== 'string' || rootRaw.trim() === '') {
|
|
2913
|
+
return { ok: false, code: WAKE_CODES.ROOT_UNRESOLVED, message: 'memoryRoot 未解析,无法读取唤醒桥状态' };
|
|
2914
|
+
}
|
|
2915
|
+
const root = path.resolve(rootRaw);
|
|
2916
|
+
const paths = wakePaths(root);
|
|
2917
|
+
const runtime = input?.runtime ?? RUNTIMES.get(root) ?? null;
|
|
2918
|
+
const cfg = runtime?.cfg ?? null;
|
|
2919
|
+
const state = readWakeState(paths);
|
|
2920
|
+
const panel = readWakePanel(paths);
|
|
2921
|
+
const queue = readQueue(paths);
|
|
2922
|
+
const pending = readPending(paths);
|
|
2923
|
+
const now = nowOf({ now: input?.now });
|
|
2924
|
+
const enabled = cfg ? cfg.enabled === true : false;
|
|
2925
|
+
const capability = runtime?.capability
|
|
2926
|
+
?? state.capability
|
|
2927
|
+
?? panel?.capability
|
|
2928
|
+
?? { present: false, version: 'unknown', code: WAKE_CODES.DISABLED };
|
|
2929
|
+
const byKind = {};
|
|
2930
|
+
let due = 0;
|
|
2931
|
+
for (const row of queue) {
|
|
2932
|
+
const status = String(row.status ?? 'queued');
|
|
2933
|
+
if (!['queued', 'failed'].includes(status)) continue;
|
|
2934
|
+
if (status === 'failed' && Number(row.retries ?? 0) >= Number(cfg?.retryMax ?? WAKE_DEFAULTS.retryMax)) continue;
|
|
2935
|
+
bumpCount(byKind, String(row.kind ?? 'unknown'));
|
|
2936
|
+
const expiresAt = Date.parse(row.expiresAt);
|
|
2937
|
+
if (!Number.isFinite(expiresAt) || expiresAt > now.getTime()) due += 1;
|
|
2938
|
+
}
|
|
2939
|
+
const total = queue.filter((row) => ['queued', 'failed', 'running'].includes(String(row.status ?? 'queued'))).length;
|
|
2940
|
+
const missingCapability = capability?.code === CAPABILITY_MISSING_CODE;
|
|
2941
|
+
const code = enabled ? null : (missingCapability ? CAPABILITY_MISSING_CODE : WAKE_CODES.DISABLED);
|
|
2942
|
+
return {
|
|
2943
|
+
ok: true,
|
|
2944
|
+
action: 'status',
|
|
2945
|
+
enabled,
|
|
2946
|
+
code,
|
|
2947
|
+
reason: enabled ? 'ENABLED' : (missingCapability ? 'CAPABILITY_MISSING' : 'DISABLED'),
|
|
2948
|
+
capability,
|
|
2949
|
+
queue: { total, due, byKind },
|
|
2950
|
+
pendingCount: pending.length,
|
|
2951
|
+
lastRun: state.lastRun ?? panel?.lastRun ?? null,
|
|
2952
|
+
bounds: WAKE_BOUNDS,
|
|
2953
|
+
budget: WAKE_BUDGET_NOTE,
|
|
2954
|
+
config: cfg
|
|
2955
|
+
? {
|
|
2956
|
+
maxPerDay: cfg.maxPerDay,
|
|
2957
|
+
cooldownSeconds: cfg.cooldownSeconds,
|
|
2958
|
+
timeoutSeconds: cfg.timeoutSeconds,
|
|
2959
|
+
queueMax: cfg.queueMax,
|
|
2960
|
+
retryMax: cfg.retryMax,
|
|
2961
|
+
allowTools: [...cfg.allowTools],
|
|
2962
|
+
denyTools: [...cfg.denyTools],
|
|
2963
|
+
}
|
|
2964
|
+
: null,
|
|
2965
|
+
warnings: cfg?.warnings ?? [],
|
|
2966
|
+
generatedAt: isoOf(now),
|
|
2967
|
+
};
|
|
2968
|
+
}
|
|
2969
|
+
|
|
2970
|
+
/**
|
|
2971
|
+
* memory_wake 工具实现(tools.js 只做转发;不新增工具、不改参数形状)。
|
|
2972
|
+
* action: status | drain | enqueue。propose 是内部通道(H2 接任务书),工具面不暴露。
|
|
2973
|
+
*/
|
|
2974
|
+
export async function memoryWake(args = {}, config = {}) {
|
|
2975
|
+
const action = typeof args?.action === 'string' && args.action !== '' ? args.action : 'status';
|
|
2976
|
+
const rootRaw = config?.memoryRoot ?? config?.exec?.memoryRoot ?? null;
|
|
2977
|
+
if (action === 'status') return wakeStatusReport({ root: rootRaw });
|
|
2978
|
+
if (action === 'drain') return drainWakeQueue({ root: rootRaw, trigger: 'tool' });
|
|
2979
|
+
if (action === 'enqueue') {
|
|
2980
|
+
const root = typeof rootRaw === 'string' && rootRaw.trim() !== '' ? path.resolve(rootRaw) : null;
|
|
2981
|
+
const runtime = root ? RUNTIMES.get(root) : null;
|
|
2982
|
+
const cfg = runtime?.cfg ?? WAKE_DEFAULTS;
|
|
2983
|
+
if (!root) return { ok: false, code: WAKE_CODES.ROOT_UNRESOLVED, message: 'memoryRoot 未解析,无法入队' };
|
|
2984
|
+
return enqueueWakeTicket({ root, cfg }, args?.ticket ?? {});
|
|
2985
|
+
}
|
|
2986
|
+
if (action === 'propose') {
|
|
2987
|
+
// 内部通道:只有唤醒会话自己可以提交提议(H2 接任务书;H1 保留实现与审计)。
|
|
2988
|
+
const root = typeof rootRaw === 'string' && rootRaw.trim() !== '' ? path.resolve(rootRaw) : null;
|
|
2989
|
+
const runtime = root ? RUNTIMES.get(root) : null;
|
|
2990
|
+
if (!runtime) return { ok: false, code: WAKE_CODES.DISABLED, message: '唤醒桥未启用' };
|
|
2991
|
+
const sessionId = String(config?.exec?.agent?.session?.id ?? config?.exec?.sessionId ?? '');
|
|
2992
|
+
const active = sessionId !== '' && runtime.activeRuns?.has?.(sessionId);
|
|
2993
|
+
if (!active) return { ok: false, code: WAKE_CODES.NOT_WAKE_SESSION, message: 'propose 只能由唤醒会话提交' };
|
|
2994
|
+
const run = runtime.running ?? { runId: null, sessionId8: sessionId.slice(0, 8) };
|
|
2995
|
+
const result = await submitProposal(runtime, run, args?.proposal ?? args?.ticket ?? {}, {});
|
|
2996
|
+
return { ok: result.ok, ...result };
|
|
2997
|
+
}
|
|
2998
|
+
return { ok: false, code: WAKE_CODES.ACTION_INVALID, message: `未知 action: ${action}`, allowed: ['status', 'drain', 'enqueue'] };
|
|
2999
|
+
}
|