@ai-agent-forge/plugin-task-manager 0.0.0-stage → 0.88.29
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/README.md +28 -2
- package/agent-forge.json +19 -0
- package/dist/entry.d.ts +14 -0
- package/dist/entry.d.ts.map +1 -0
- package/dist/entry.js +23 -0
- package/dist/entry.js.map +1 -0
- package/dist/index.d.ts +201 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1243 -0
- package/dist/index.js.map +1 -0
- package/dist/ledger.d.ts +327 -0
- package/dist/ledger.d.ts.map +1 -0
- package/dist/ledger.js +535 -0
- package/dist/ledger.js.map +1 -0
- package/package.json +53 -5
- package/plugin.json +15 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 管家事项管理工具(助手管家化与完全访问改造设计草案 §4、§6.1)。
|
|
3
|
+
*
|
|
4
|
+
* `assistant_task` 只在主会话注册(`SessionAPI.getSessionKind() === "main"`):
|
|
5
|
+
* 子会话及其后代不注册,负责人拿不到管理面。执行派发走公共
|
|
6
|
+
* `agent-forge.agent-task-scheduler@2`——本插件不复制调度器,队列、预算、终态与
|
|
7
|
+
* 取消全部复用 runtime;requestId 以 `${workItemId}:${requirementsRevision}` 绑定,
|
|
8
|
+
* 同一要求版本的重放由调度器幂等吸收(AC-19 的插件层)。
|
|
9
|
+
*
|
|
10
|
+
* 查询不等待(草案 §6.1):list/inspect 只投影账本;结果回填由 `poll` 显式触发
|
|
11
|
+
* (对在途 taskId 非阻塞 peek,终态才写 dispatch_result),模型轮询不阻塞宿主。
|
|
12
|
+
*/
|
|
13
|
+
import { createHash } from "node:crypto";
|
|
14
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
15
|
+
import { isAbsolute, resolve } from "node:path";
|
|
16
|
+
import { AGENT_TASK_CHILD_PROFILE_KEY, AGENT_TASK_PARENT_SESSION_KEY, AGENT_TASK_SCHEDULER_CAPABILITY_ID, AGENT_TASK_SCHEDULER_CAPABILITY_VERSION, } from "@agent-forge/plugin-sdk";
|
|
17
|
+
import { INTENT_CANCEL_ENTRY_TYPE, LEDGER_ENTRY_TYPE, LedgerError, newOpId, newWorkItemId, replayLedger, validateApply, } from "./ledger.js";
|
|
18
|
+
/** §6.3 v1 冻结值:默认单次 attempt 租期 60 分钟。 */
|
|
19
|
+
const DEFAULT_LEASE_MS = 60 * 60_000;
|
|
20
|
+
/** §6.3 v1 冻结值:extendLease 单次最多延长 30 分钟。 */
|
|
21
|
+
const MAX_LEASE_EXTENSION_MS = 30 * 60_000;
|
|
22
|
+
/** §7.3 v1 冻结值:每事项实质变化最多 5 分钟一条进度。 */
|
|
23
|
+
const PROGRESS_THROTTLE_MS = 5 * 60_000;
|
|
24
|
+
/** §6.2 v1 冻结值:连续 15 分钟无可核对进展提示一次。 */
|
|
25
|
+
const SEMANTIC_STALL_MS = 15 * 60_000;
|
|
26
|
+
/** §6.2 v1 冻结值:活跃 runner 每 15 秒一次专用轻量 probe。 */
|
|
27
|
+
const PROBE_INTERVAL_MS = 15_000;
|
|
28
|
+
/** §6.2 v1 冻结值:每次 probe 5 秒回执期限。 */
|
|
29
|
+
const PROBE_DEADLINE_MS = 5_000;
|
|
30
|
+
/** §6.2 v1 冻结值:连续 3 次实际发送且超时判通讯无响应。 */
|
|
31
|
+
const PROBE_MAX_STRIKES = 3;
|
|
32
|
+
/** §6.2 v1 冻结值:probe 调度间隔超过 45 秒(宿主暂停)→ 清零计数重新探测。 */
|
|
33
|
+
const PROBE_SCHEDULE_RESET_MS = 45_000;
|
|
34
|
+
/** §6.4 v1 冻结值:首次复评点 24 个受理 run / 2 次质量退回;后续 +8 run / +1 返工(活动分钟维度暂不入触发,缺整树计量)。 */
|
|
35
|
+
const REVIEW_FIRST_RUNS = 24;
|
|
36
|
+
const REVIEW_FIRST_REWORKS = 2;
|
|
37
|
+
const REVIEW_NEXT_RUNS = 8;
|
|
38
|
+
const REVIEW_NEXT_REWORKS = 1;
|
|
39
|
+
const ITEM_ID_PATTERN = /^wi-\d{14}-[0-9a-f]{4}-[0-9a-f]{4}$/;
|
|
40
|
+
/**
|
|
41
|
+
* 从 capability 目录解析 @2 调度器。延迟调用:装载期不强依赖——第三方宿主可能
|
|
42
|
+
* 没有 subagent-delegate;此时账本工具仍可用(create/list/inspect),派发在
|
|
43
|
+
* dispatch 时以结构化错误拒绝(草案 §5.3:缺少可验证准入通路时拒绝派发并说明
|
|
44
|
+
* 能力缺失),插件独立失败不阻塞宿主装配。
|
|
45
|
+
*/
|
|
46
|
+
export function resolveScheduler(api) {
|
|
47
|
+
const handle = api.capabilities.require(AGENT_TASK_SCHEDULER_CAPABILITY_ID, {
|
|
48
|
+
version: AGENT_TASK_SCHEDULER_CAPABILITY_VERSION,
|
|
49
|
+
});
|
|
50
|
+
const call = async (request, signal) => {
|
|
51
|
+
const operation = handle.call(request, signal === undefined ? undefined : { signal });
|
|
52
|
+
return await operation.result;
|
|
53
|
+
};
|
|
54
|
+
return { call };
|
|
55
|
+
}
|
|
56
|
+
/** 管家插件装配:返回可注销注册(工具 + 命令)。 */
|
|
57
|
+
export function createTaskManagerCapability(api) {
|
|
58
|
+
const sessionKind = api.session?.getSessionKind?.();
|
|
59
|
+
// 子会话及其后代不注册管理面(草案 §4):负责人拿到 assistant_task 就能递归派单。
|
|
60
|
+
if (sessionKind !== "main" || api.session === undefined) {
|
|
61
|
+
return [];
|
|
62
|
+
}
|
|
63
|
+
const sessionApi = api.session;
|
|
64
|
+
const manager = new TaskManager(api, {
|
|
65
|
+
session: sessionApi,
|
|
66
|
+
// §7.3 通知通道(AC-24 持久事实面):进度/复评点/停滞经会话通知面
|
|
67
|
+
//(presentation=notification,持久化保留、不进 transcript)。发送失败不阻塞
|
|
68
|
+
// 账本动作;宿主缺 sendMessage 时静默无通知(不伪造投递)。
|
|
69
|
+
notify: sessionApi.sendMessage !== undefined
|
|
70
|
+
? (event) => {
|
|
71
|
+
void sessionApi
|
|
72
|
+
.sendMessage?.({
|
|
73
|
+
customType: "task-manager.notification",
|
|
74
|
+
content: `【管家事项】${event.title} [${event.status}] ${event.detail}`.trim(),
|
|
75
|
+
// display:true 是 TUI 通知面的路由键(interactive-events 的
|
|
76
|
+
// custom case 只处理 display 消息);display:false 会让通知在
|
|
77
|
+
// 任何宿主都不可见(镜像整机场景 butler-tasks-and-notice 取证)。
|
|
78
|
+
display: true,
|
|
79
|
+
presentation: "notification",
|
|
80
|
+
})
|
|
81
|
+
.catch(() => { });
|
|
82
|
+
}
|
|
83
|
+
: undefined,
|
|
84
|
+
// scheduler 不注入:延迟到首次 dispatch 经 capability 目录解析(装配顺序
|
|
85
|
+
// 无关;宿主没有 subagent-delegate 时账本工具仍可用,派发结构化拒绝)。
|
|
86
|
+
now: () => new Date(),
|
|
87
|
+
});
|
|
88
|
+
const registrations = [];
|
|
89
|
+
registrations.push(api.registerTool(manager.toolDefinition()));
|
|
90
|
+
// §6.1:TUI 可由同一插件提供一个 `/tasks` 命令,不新增默认快捷键(单入口规则)。
|
|
91
|
+
// 只读渲染账本投影;交互控制仍走 `assistant_task` 工具动作。
|
|
92
|
+
if (api.registerCommand !== undefined) {
|
|
93
|
+
registrations.push(api.registerCommand({
|
|
94
|
+
name: "tasks",
|
|
95
|
+
description: "Show this session's work items (status, revision, dispatch)",
|
|
96
|
+
execute: async (args) => {
|
|
97
|
+
try {
|
|
98
|
+
if (args.trim() !== "") {
|
|
99
|
+
return { status: "error", message: "Usage: /tasks" };
|
|
100
|
+
}
|
|
101
|
+
return { status: "success", message: renderWorkItems(manager) };
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
// A slash command must not crash the host (host command contract).
|
|
105
|
+
// The wrapper is the user-facing sentence; the inner error stays raw.
|
|
106
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
107
|
+
return { status: "error", message: `/tasks failed: ${detail}` };
|
|
108
|
+
}
|
|
109
|
+
},
|
|
110
|
+
}));
|
|
111
|
+
}
|
|
112
|
+
return registrations;
|
|
113
|
+
}
|
|
114
|
+
/** `/tasks` 文本渲染:每行一个事项(id 短形态 [状态] rN 标题 + 派发事实)。 */
|
|
115
|
+
export function renderWorkItems(manager) {
|
|
116
|
+
const view = manager.view();
|
|
117
|
+
const items = [...view.items.values()];
|
|
118
|
+
if (items.length === 0) {
|
|
119
|
+
return "no work items in this session; dispatch one with assistant_task action=create";
|
|
120
|
+
}
|
|
121
|
+
const lines = items.map((item) => {
|
|
122
|
+
const dispatch = item.dispatch === undefined
|
|
123
|
+
? ""
|
|
124
|
+
: ` [task ${item.dispatch.taskId} @ r${item.dispatch.requirementsRevisionAtSubmit}]`;
|
|
125
|
+
const note = item.note === undefined ? "" : ` — ${item.note}`;
|
|
126
|
+
return `${item.workItemId.slice(3, 12)} [${item.status}] r${item.requirementsRevision}/${item.recordRevision} ${item.title}${dispatch}${note}`;
|
|
127
|
+
});
|
|
128
|
+
return [`work items (${items.length}):`, ...lines].join("\n");
|
|
129
|
+
}
|
|
130
|
+
/** 账本 + 调度器的领域门面:全部控制转移与查询的唯一入口。 */
|
|
131
|
+
export class TaskManager {
|
|
132
|
+
options;
|
|
133
|
+
api;
|
|
134
|
+
schedulerCache;
|
|
135
|
+
/** §7.3 进度节流:workItemId → 上次进度通知时间(内存;重启后重新计时)。 */
|
|
136
|
+
/** opId/workItemId 的写入方单调序号(同会话内唯一性的责任主体,见 newOpId/newWorkItemId)。 */
|
|
137
|
+
opSeq = 0;
|
|
138
|
+
/** workItemId 的写入方单调序号(同 newWorkItemId 的唯一性纪律)。 */
|
|
139
|
+
workItemSeq = 0;
|
|
140
|
+
/** 宿主工具面注入的会话工作目录(CapabilityToolContext.cwd;hash 钉相对路径基准)。 */
|
|
141
|
+
toolContextCwd;
|
|
142
|
+
lastProgressNotifyAt = new Map();
|
|
143
|
+
/** §7.3 事件幂等:已通知的稳定事件 ID(`${workItemId}:${recordRevision}`)。 */
|
|
144
|
+
notifiedEventIds = new Set();
|
|
145
|
+
/** §6.2 语义进展:workItemId → 上次可核对进展时间(内存)。 */
|
|
146
|
+
lastSemanticProgressAt = new Map();
|
|
147
|
+
/** §6.2 已提示过的停滞(15 分钟一次,提示后不重复)。 */
|
|
148
|
+
stalledNotified = new Set();
|
|
149
|
+
/** §6.2 runner probe 健康判定:workItemId → 在途派发的探针状态(内存)。 */
|
|
150
|
+
healthStates = new Map();
|
|
151
|
+
/** §6.4 复评点提示去重:已提示过的用量快照键(复评后 planRevision 推进 → 新键)。 */
|
|
152
|
+
reviewNotifiedKeys = new Set();
|
|
153
|
+
/** §12 AC-04 capacity 队列:workItemId → 槽满待复查的原始派发输入(内存;重启后由模型重新派发)。 */
|
|
154
|
+
pendingDispatch = new Map();
|
|
155
|
+
constructor(api, options) {
|
|
156
|
+
this.api = api;
|
|
157
|
+
this.options = options;
|
|
158
|
+
}
|
|
159
|
+
/** 调度器解析:装配注入优先;否则经 capability 目录延迟解析(解析失败在 dispatch 时结构化拒绝)。 */
|
|
160
|
+
scheduler() {
|
|
161
|
+
if (this.options.scheduler !== undefined)
|
|
162
|
+
return this.options.scheduler;
|
|
163
|
+
if (this.schedulerCache === undefined) {
|
|
164
|
+
if (this.api === undefined) {
|
|
165
|
+
throw new LedgerError("ledger_invalid_transition", "dispatch unavailable: agent-forge.agent-task-scheduler@2 is not present in this host (no scheduler provider loaded)");
|
|
166
|
+
}
|
|
167
|
+
this.schedulerCache = resolveScheduler(this.api);
|
|
168
|
+
}
|
|
169
|
+
return this.schedulerCache;
|
|
170
|
+
}
|
|
171
|
+
now() {
|
|
172
|
+
return this.options.now?.() ?? new Date();
|
|
173
|
+
}
|
|
174
|
+
random() {
|
|
175
|
+
return this.options.random?.() ?? Math.random();
|
|
176
|
+
}
|
|
177
|
+
/** 当前账本投影(每控制步重放;账本规模 = 该会话事项数,重放成本有界)。 */
|
|
178
|
+
view() {
|
|
179
|
+
return replayLedger(this.options.session.getBranchEntries());
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* 追加一条账本记录:先对当前事项预演(validateApply),通过才落到会话账本——
|
|
183
|
+
* 被拒的控制动作(CAS 不符/非法转移/旧版本结果)不得污染 append-only 账本。
|
|
184
|
+
* create 无前置事项,跳过预演(replayWorkItem 校验账本首记录)。
|
|
185
|
+
*/
|
|
186
|
+
append(workItemId, op, data) {
|
|
187
|
+
const view = this.view();
|
|
188
|
+
const existing = view.items.get(workItemId);
|
|
189
|
+
// opId 唯一性是写入方责任(AC-34):序号随进程重启归零,可能与既有账本碰撞
|
|
190
|
+
// (重放去重会把后续写入判为损坏、会话不可用)——碰撞时原地前进重新生成。
|
|
191
|
+
let opId = newOpId(this.now(), () => this.random(), this.opSeq++);
|
|
192
|
+
while (view.opIds.has(opId)) {
|
|
193
|
+
opId = newOpId(this.now(), () => this.random(), this.opSeq++);
|
|
194
|
+
}
|
|
195
|
+
const record = Object.freeze({
|
|
196
|
+
seq: (view.seqByItem.get(workItemId) ?? 0) + 1,
|
|
197
|
+
opId,
|
|
198
|
+
op,
|
|
199
|
+
workItemId,
|
|
200
|
+
at: this.now().toISOString(),
|
|
201
|
+
data,
|
|
202
|
+
});
|
|
203
|
+
if (existing !== undefined)
|
|
204
|
+
validateApply(existing, record);
|
|
205
|
+
this.options.session.appendEntry(LEDGER_ENTRY_TYPE, record);
|
|
206
|
+
this.notifyIfChanged(workItemId, record);
|
|
207
|
+
return record;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* §7.3 通知与节流:状态实质变化才发进度;每事项最多 5 分钟一条,失败/取消/
|
|
211
|
+
* 验收完成不受节流。稳定事件 ID = `${workItemId}:${recordRevision}`,同 ID 只
|
|
212
|
+
* 发一次(AC-18);通知通道缺席时静默跳过(不伪造投递)。
|
|
213
|
+
*/
|
|
214
|
+
notifyIfChanged(workItemId, record) {
|
|
215
|
+
if (record.op === "note")
|
|
216
|
+
return;
|
|
217
|
+
const notify = this.options.notify;
|
|
218
|
+
if (notify === undefined)
|
|
219
|
+
return;
|
|
220
|
+
let item;
|
|
221
|
+
try {
|
|
222
|
+
item = this.replay(workItemId);
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
const eventId = `${workItemId}:${item.recordRevision}`;
|
|
228
|
+
if (this.notifiedEventIds.has(eventId))
|
|
229
|
+
return;
|
|
230
|
+
const important = item.status === "blocked" ||
|
|
231
|
+
item.status === "cancelled" ||
|
|
232
|
+
item.status === "completed" ||
|
|
233
|
+
item.status === "awaiting_review";
|
|
234
|
+
const now = this.now().getTime();
|
|
235
|
+
const last = this.lastProgressNotifyAt.get(workItemId);
|
|
236
|
+
if (!important && last !== undefined && now - last < PROGRESS_THROTTLE_MS)
|
|
237
|
+
return;
|
|
238
|
+
this.notifiedEventIds.add(eventId);
|
|
239
|
+
this.lastProgressNotifyAt.set(workItemId, now);
|
|
240
|
+
notify({
|
|
241
|
+
eventId,
|
|
242
|
+
workItemId,
|
|
243
|
+
title: item.title,
|
|
244
|
+
status: item.status,
|
|
245
|
+
detail: item.note ?? item.lastError ?? "",
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
/** 工具定义(TypeBox 参数面;Action 判别)。registerTool 按结构化消费。 */
|
|
249
|
+
toolDefinition() {
|
|
250
|
+
const self = this;
|
|
251
|
+
return {
|
|
252
|
+
name: "assistant_task",
|
|
253
|
+
label: "Manage work items",
|
|
254
|
+
description: "Manage work items for concrete multi-step or delegable outcomes; answer questions and quick lookups directly. " +
|
|
255
|
+
"Create one item per settled intent; clarify material ambiguity before dispatch. Dispatch one attempt per item " +
|
|
256
|
+
"with a clear brief. Poll on natural turns and report pending results and failures honestly. A capacity-wait " +
|
|
257
|
+
"item is rechecked by poll; do not redispatch it unless instructions change. Re-evaluate at review points. " +
|
|
258
|
+
"Accept only with verified evidence for each criterion and the real delivery location; otherwise leave it " +
|
|
259
|
+
"awaiting_review. Keep the user informed of outcomes and waiting reasons. If a decision is needed, use the " +
|
|
260
|
+
"decision tool when available and record the answer with update or continue. stop_all cancels non-terminal " +
|
|
261
|
+
"items and persistently cancels classified intents. Main session only; /tasks shows work items.",
|
|
262
|
+
parameters: {
|
|
263
|
+
type: "object",
|
|
264
|
+
properties: {
|
|
265
|
+
action: {
|
|
266
|
+
type: "string",
|
|
267
|
+
enum: [
|
|
268
|
+
"create",
|
|
269
|
+
"list",
|
|
270
|
+
"inspect",
|
|
271
|
+
"update",
|
|
272
|
+
"dispatch",
|
|
273
|
+
"poll",
|
|
274
|
+
"accept",
|
|
275
|
+
"cancel",
|
|
276
|
+
"pause",
|
|
277
|
+
"continue",
|
|
278
|
+
"rework",
|
|
279
|
+
"extend_lease",
|
|
280
|
+
"review",
|
|
281
|
+
"fence",
|
|
282
|
+
"stop_all",
|
|
283
|
+
],
|
|
284
|
+
description: "Work-item control action.",
|
|
285
|
+
},
|
|
286
|
+
intentId: {
|
|
287
|
+
type: "string",
|
|
288
|
+
description: "Caller-generated idempotency key for create (one settled user intent).",
|
|
289
|
+
},
|
|
290
|
+
title: { type: "string", description: "Short work-item title (create)." },
|
|
291
|
+
goal: { type: "string", description: "Outcome statement (create)." },
|
|
292
|
+
acceptanceCriteria: {
|
|
293
|
+
type: "array",
|
|
294
|
+
items: { type: "string" },
|
|
295
|
+
description: "Judgeable acceptance criteria from the user's own words (create/update).",
|
|
296
|
+
},
|
|
297
|
+
deliverable: { type: "string", description: "Deliverable shape and location (create/update)." },
|
|
298
|
+
cwd: { type: "string", description: "Work-item workspace (create)." },
|
|
299
|
+
workItemId: { type: "string", description: "Target work item (all actions except create/list)." },
|
|
300
|
+
changes: {
|
|
301
|
+
type: "array",
|
|
302
|
+
items: { type: "string" },
|
|
303
|
+
description: "Material requirement changes (update).",
|
|
304
|
+
},
|
|
305
|
+
expectedRecordRevision: {
|
|
306
|
+
type: "number",
|
|
307
|
+
description: "CAS guard: current recordRevision of the item (update/dispatch/accept/cancel/pause/continue/rework).",
|
|
308
|
+
},
|
|
309
|
+
checks: {
|
|
310
|
+
type: "array",
|
|
311
|
+
description: "Per-criterion acceptance checks (accept).",
|
|
312
|
+
items: {
|
|
313
|
+
type: "object",
|
|
314
|
+
properties: {
|
|
315
|
+
criterion: { type: "string" },
|
|
316
|
+
outcome: { type: "string", enum: ["pass", "fail", "not_verified"] },
|
|
317
|
+
evidence: { type: "string" },
|
|
318
|
+
},
|
|
319
|
+
required: ["criterion", "outcome"],
|
|
320
|
+
},
|
|
321
|
+
},
|
|
322
|
+
artifactFingerprint: { type: "string", description: "Stable artifact version or hash (accept)." },
|
|
323
|
+
deliverableLocation: {
|
|
324
|
+
type: "string",
|
|
325
|
+
description: "Real delivery location: file, commit, or published target (accept).",
|
|
326
|
+
},
|
|
327
|
+
reason: { type: "string", description: "Reason note (cancel/pause/continue/rework)." },
|
|
328
|
+
summary: {
|
|
329
|
+
type: "string",
|
|
330
|
+
description: "Butler review conclusion (review): evidence, remaining AC, keep or replace worker/method, next action and checkpoint (§6.4). Do not fabricate pending results.",
|
|
331
|
+
},
|
|
332
|
+
workerInstructions: {
|
|
333
|
+
type: "string",
|
|
334
|
+
description: "Brief for the dispatched worker: goal, constraints, ruled-out approaches and relevant file pointers (dispatch).",
|
|
335
|
+
},
|
|
336
|
+
deadlineAt: {
|
|
337
|
+
type: "number",
|
|
338
|
+
description: "User hard deadline in epoch ms (dispatch, §6.4): the attempt is stopped at this time even if the lease is longer; renewals cannot push past it.",
|
|
339
|
+
},
|
|
340
|
+
dependsOn: {
|
|
341
|
+
type: "array",
|
|
342
|
+
items: { type: "string" },
|
|
343
|
+
description: "Upstream work item ids this item consumes after their completion (create/update, AC-37): dispatch is blocked until every dependency is completed; cycles are refused.",
|
|
344
|
+
},
|
|
345
|
+
cancelIntentIds: {
|
|
346
|
+
type: "array",
|
|
347
|
+
items: { type: "string" },
|
|
348
|
+
description: "Intent ids of classified-but-not-yet-created intents to persistently cancel (stop_all, AC-36): create refuses these after the stop, including after a crash replay.",
|
|
349
|
+
},
|
|
350
|
+
},
|
|
351
|
+
required: ["action"],
|
|
352
|
+
},
|
|
353
|
+
// 宿主 ToolDefinition 契约是 (toolCallId, params, signal, onUpdate, ctx);
|
|
354
|
+
// 公共 invokeTool 面是 (input)。objectInput 兼容两种调用形状(与
|
|
355
|
+
// subagent-delegate 的注册面同一纪律)。宿主经第 5 参注入会话工作目录
|
|
356
|
+
//(CapabilityToolContext.cwd)——hash 钉的相对路径按它解析,serve/web
|
|
357
|
+
// 宿主进程 cwd ≠ 会话工作区时不再钉错位置。
|
|
358
|
+
async execute(first, second, _third, _fourth, fifth) {
|
|
359
|
+
try {
|
|
360
|
+
const ctx = isPlainRecord(fifth) ? fifth : undefined;
|
|
361
|
+
const ctxCwd = typeof ctx?.cwd === "string" && ctx.cwd !== "" ? ctx.cwd : undefined;
|
|
362
|
+
self.toolContextCwd = ctxCwd;
|
|
363
|
+
const primary = isPlainRecord(first) ? first : second;
|
|
364
|
+
if (!isPlainRecord(primary)) {
|
|
365
|
+
throw new LedgerError("ledger_invalid_input", "assistant_task input must be an object");
|
|
366
|
+
}
|
|
367
|
+
return { ok: true, ...(await self.dispatchAction(primary)) };
|
|
368
|
+
}
|
|
369
|
+
catch (error) {
|
|
370
|
+
if (error instanceof LedgerError) {
|
|
371
|
+
return { ok: false, error: error.message, code: error.code };
|
|
372
|
+
}
|
|
373
|
+
return {
|
|
374
|
+
ok: false,
|
|
375
|
+
error: error instanceof Error ? error.message : String(error),
|
|
376
|
+
code: "task_manager_unexpected",
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
},
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
/** Action 分发(execute 的主体;独立导出便于测试直调)。 */
|
|
383
|
+
async dispatchAction(input) {
|
|
384
|
+
const record = input;
|
|
385
|
+
const action = typeof record.action === "string" ? record.action : "";
|
|
386
|
+
switch (action) {
|
|
387
|
+
case "create":
|
|
388
|
+
return { item: this.create(record) };
|
|
389
|
+
case "list":
|
|
390
|
+
return { items: [...this.view().items.values()] };
|
|
391
|
+
case "inspect":
|
|
392
|
+
return { item: this.inspect(record) };
|
|
393
|
+
case "update":
|
|
394
|
+
return { item: this.update(record) };
|
|
395
|
+
case "dispatch":
|
|
396
|
+
return { item: await this.dispatch(record) };
|
|
397
|
+
case "poll":
|
|
398
|
+
return { item: await this.poll(record) };
|
|
399
|
+
case "accept":
|
|
400
|
+
return { item: this.accept(record) };
|
|
401
|
+
case "cancel":
|
|
402
|
+
return { item: this.control("cancel", record) };
|
|
403
|
+
case "pause":
|
|
404
|
+
return { item: this.control("pause", record) };
|
|
405
|
+
case "continue":
|
|
406
|
+
return { item: this.control("continue", record) };
|
|
407
|
+
case "rework":
|
|
408
|
+
return { item: this.control("rework", record) };
|
|
409
|
+
case "extend_lease":
|
|
410
|
+
return { item: this.extendLease(record) };
|
|
411
|
+
case "review":
|
|
412
|
+
return { item: this.review(record) };
|
|
413
|
+
case "fence":
|
|
414
|
+
return { item: this.control("fence", record) };
|
|
415
|
+
case "stop_all":
|
|
416
|
+
return { items: await this.stopAll(record) };
|
|
417
|
+
default:
|
|
418
|
+
throw new LedgerError("ledger_invalid_input", `assistant_task action must be one of create/list/inspect/update/dispatch/poll/accept/cancel/pause/continue/rework/extend_lease/review/fence/stop_all, got ${JSON.stringify(record.action)}`);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
/** 接单(AC-01):intentId 幂等;同键异内容冲突;墓碑意图结构化拒绝(AC-36)。 */
|
|
422
|
+
create(input) {
|
|
423
|
+
const intentId = requiredString(input.intentId, "intentId");
|
|
424
|
+
const title = requiredString(input.title, "title");
|
|
425
|
+
const goal = requiredString(input.goal, "goal");
|
|
426
|
+
const acceptanceCriteria = requiredStringArray(input.acceptanceCriteria, "acceptanceCriteria");
|
|
427
|
+
const view = this.view();
|
|
428
|
+
if (view.cancelledIntents.has(intentId)) {
|
|
429
|
+
throw new LedgerError("ledger_invalid_input", `intentId ${intentId} was cancelled by stop_all; register it again with a new intentId`);
|
|
430
|
+
}
|
|
431
|
+
const existing = view.byIntent.get(intentId);
|
|
432
|
+
if (existing !== undefined) {
|
|
433
|
+
const item = view.items.get(existing);
|
|
434
|
+
// 同键同内容(标题+目标+AC 全等)返回既有事项;异内容按冲突拒绝——不合并、不重置。
|
|
435
|
+
const same = item.title === title &&
|
|
436
|
+
item.goal === goal &&
|
|
437
|
+
item.acceptanceCriteria.length === acceptanceCriteria.length &&
|
|
438
|
+
item.acceptanceCriteria.every((criterion, index) => criterion === acceptanceCriteria[index]);
|
|
439
|
+
if (!same) {
|
|
440
|
+
throw new LedgerError("ledger_duplicate_intent", `intentId ${intentId} already mapped to ${existing} with different content; revise it via update instead`);
|
|
441
|
+
}
|
|
442
|
+
return item;
|
|
443
|
+
}
|
|
444
|
+
const now = this.now().toISOString();
|
|
445
|
+
// workItemId 同一唯一性纪律:跨重启序号归零可能与既有事项碰撞(会合并成
|
|
446
|
+
// 一个事项桶并按 duplicate create 拒绝)——碰撞时前进重新生成。
|
|
447
|
+
let workItemId = newWorkItemId(this.now(), () => this.random(), this.workItemSeq++);
|
|
448
|
+
while (view.items.has(workItemId)) {
|
|
449
|
+
workItemId = newWorkItemId(this.now(), () => this.random(), this.workItemSeq++);
|
|
450
|
+
}
|
|
451
|
+
const dependsOn = this.validateDependsOn(input.dependsOn, workItemId);
|
|
452
|
+
this.append(workItemId, "create", {
|
|
453
|
+
kind: "create",
|
|
454
|
+
create: {
|
|
455
|
+
intentId,
|
|
456
|
+
title,
|
|
457
|
+
goal,
|
|
458
|
+
acceptanceCriteria,
|
|
459
|
+
...(typeof input.deliverable === "string" ? { deliverable: input.deliverable } : {}),
|
|
460
|
+
...(typeof input.cwd === "string" ? { cwd: input.cwd } : {}),
|
|
461
|
+
...(typeof input.sourceMessageId === "string" ? { sourceMessageId: input.sourceMessageId } : {}),
|
|
462
|
+
...(Array.isArray(input.userLimits)
|
|
463
|
+
? { userLimits: input.userLimits.filter((entry) => typeof entry === "string") }
|
|
464
|
+
: {}),
|
|
465
|
+
...(dependsOn === undefined ? {} : { dependsOn }),
|
|
466
|
+
},
|
|
467
|
+
});
|
|
468
|
+
return this.replay(workItemId, now);
|
|
469
|
+
}
|
|
470
|
+
/** 只读投影(查询不等待执行)。 */
|
|
471
|
+
inspect(input) {
|
|
472
|
+
return this.replay(this.workItemId(input));
|
|
473
|
+
}
|
|
474
|
+
/** 要求变更(AC-05/AC-29):CAS;实质变化递增要求版本。 */
|
|
475
|
+
update(input) {
|
|
476
|
+
const workItemId = this.workItemId(input);
|
|
477
|
+
const expected = requiredRevision(input.expectedRecordRevision);
|
|
478
|
+
const changes = requiredStringArray(input.changes, "changes");
|
|
479
|
+
const acceptanceCriteria = input.acceptanceCriteria === undefined
|
|
480
|
+
? undefined
|
|
481
|
+
: requiredStringArray(input.acceptanceCriteria, "acceptanceCriteria");
|
|
482
|
+
const dependsOn = this.validateDependsOn(input.dependsOn, workItemId);
|
|
483
|
+
this.append(workItemId, "requirements_update", {
|
|
484
|
+
kind: "requirements_update",
|
|
485
|
+
update: {
|
|
486
|
+
expectedRecordRevision: expected,
|
|
487
|
+
changes,
|
|
488
|
+
...(acceptanceCriteria === undefined ? {} : { acceptanceCriteria }),
|
|
489
|
+
...(typeof input.deliverable === "string" ? { deliverable: input.deliverable } : {}),
|
|
490
|
+
...(dependsOn === undefined ? {} : { dependsOn }),
|
|
491
|
+
},
|
|
492
|
+
});
|
|
493
|
+
return this.replay(workItemId);
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* 派发负责人(草案 §5.3):requestId 绑定要求版本,调度器幂等吸收同版本重放;
|
|
497
|
+
* dispatchScope(owner/workItem)随 metadata 过线,后代沿用。
|
|
498
|
+
*/
|
|
499
|
+
async dispatch(input) {
|
|
500
|
+
const workItemId = this.workItemId(input);
|
|
501
|
+
const expected = requiredRevision(input.expectedRecordRevision);
|
|
502
|
+
const item = this.replay(workItemId);
|
|
503
|
+
const workerInstructions = requiredString(input.workerInstructions, "workerInstructions");
|
|
504
|
+
// requestId 绑定 attempt 身份:要求版本 + 账本已受理的 attempt 数。崩溃窗口
|
|
505
|
+
// (submit 成功、dispatch 记录未落账)重算出的序号不变 → 调度器同键同内容
|
|
506
|
+
// 回放原 taskId(逃逸提交收编)或同键异内容结构化冲突;结算后的重派/返工
|
|
507
|
+
// 重派序号前进 → 全新 attempt(AC-05"纯补信息不变版本"下允许换指令重试)。
|
|
508
|
+
const requestId = `${workItemId}:r${item.requirementsRevision}#${item.usage.acceptedRuns}`;
|
|
509
|
+
// §6.4 用户硬截止优先:dispatch 显式 deadlineAt(或装配注入)早于默认租期时,
|
|
510
|
+
// 有效期限取二者较早;晚于租期时仍受租期约束。
|
|
511
|
+
const userDeadlineAt = typeof input.deadlineAt === "number" && Number.isSafeInteger(input.deadlineAt) && input.deadlineAt > 0
|
|
512
|
+
? input.deadlineAt
|
|
513
|
+
: this.options.dispatchDeadlineAt?.(workItemId);
|
|
514
|
+
if (userDeadlineAt !== undefined && userDeadlineAt <= this.now().getTime()) {
|
|
515
|
+
throw new LedgerError("ledger_invalid_input", `deadlineAt ${new Date(userDeadlineAt).toISOString()} is already in the past`);
|
|
516
|
+
}
|
|
517
|
+
// AC-37 依赖登记门:登记的上游事项未全部 completed 时拒绝派发——跨事项
|
|
518
|
+
// 采纳先登记依赖(草案 §6.5),完成顺序由账本事实承载。
|
|
519
|
+
if (item.dependsOn !== undefined) {
|
|
520
|
+
// 单次重放:依赖门只读投影,循环内不得重复重放整本账本。
|
|
521
|
+
const view = this.view();
|
|
522
|
+
const unresolved = item.dependsOn.filter((depId) => {
|
|
523
|
+
const dep = view.items.get(depId);
|
|
524
|
+
return dep === undefined || dep.status !== "completed";
|
|
525
|
+
});
|
|
526
|
+
if (unresolved.length > 0) {
|
|
527
|
+
throw new LedgerError("ledger_invalid_transition", `dispatch blocked by unresolved dependencies (register via update, complete or remove them): ${unresolved.join(", ")}`);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
// 转移预检先于调度器调用(§5.3 单 attempt):running 已有在途 attempt、
|
|
531
|
+
// stopping 已 fence 封死——被拒的控制动作不产生调度器流量,报错直指状态。
|
|
532
|
+
if (item.dispatch !== undefined ||
|
|
533
|
+
item.fence !== undefined ||
|
|
534
|
+
!(item.status === "queued" ||
|
|
535
|
+
item.status === "clarifying" ||
|
|
536
|
+
item.status === "replanning" ||
|
|
537
|
+
item.status === "blocked")) {
|
|
538
|
+
throw new LedgerError("ledger_invalid_transition", `dispatch is not allowed from status ${item.status}${item.dispatch === undefined ? "" : " (an attempt is already active)"}`);
|
|
539
|
+
}
|
|
540
|
+
const request = {
|
|
541
|
+
version: 2,
|
|
542
|
+
action: "submit",
|
|
543
|
+
request: {
|
|
544
|
+
version: 2,
|
|
545
|
+
prompt: workerInstructions,
|
|
546
|
+
profile: this.options.workerProfile ?? { version: 1, roleId: "worker" },
|
|
547
|
+
...(userDeadlineAt === undefined ? {} : { deadlineAt: userDeadlineAt }),
|
|
548
|
+
requestId,
|
|
549
|
+
metadata: {
|
|
550
|
+
ownerSessionId: this.options.session.getSessionId(),
|
|
551
|
+
workItemId,
|
|
552
|
+
[AGENT_TASK_PARENT_SESSION_KEY]: this.options.session.getSessionId(),
|
|
553
|
+
[AGENT_TASK_CHILD_PROFILE_KEY]: this.options.workerProfile ?? { version: 1, roleId: "worker" },
|
|
554
|
+
},
|
|
555
|
+
},
|
|
556
|
+
};
|
|
557
|
+
// AC-35 submit-落账窗口的崩溃对账由调度器 requestId 幂等承担:submit 成功后
|
|
558
|
+
// 崩溃留下的逃逸提交,在同要求重派时按同键同内容回放原 taskId(duplicate),
|
|
559
|
+
// 账本据此绑定原 attempt;同键异内容则由调度器结构化冲突显式拒绝——attempt
|
|
560
|
+
// 身份与内容一致性归调度器,账本不提前判收(复审裁决 2026-11-15)。
|
|
561
|
+
let response;
|
|
562
|
+
try {
|
|
563
|
+
response = await this.scheduler().call(request);
|
|
564
|
+
}
|
|
565
|
+
catch (error) {
|
|
566
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
567
|
+
// §12 AC-04:槽满不静默丢弃——事项带 capacity-wait 备注留在队列,poll
|
|
568
|
+
// 自动复查重派(同一 requestId 幂等安全:失败提交没有受理回执)。
|
|
569
|
+
if (/queue depth|queue full|capacity/i.test(message)) {
|
|
570
|
+
this.append(workItemId, "note", {
|
|
571
|
+
kind: "note",
|
|
572
|
+
control: { expectedRecordRevision: item.recordRevision, reason: `capacity-wait: ${message}` },
|
|
573
|
+
});
|
|
574
|
+
this.pendingDispatch.set(workItemId, { input, requirementsRevision: item.requirementsRevision });
|
|
575
|
+
return this.replay(workItemId);
|
|
576
|
+
}
|
|
577
|
+
throw new LedgerError("ledger_invalid_transition", `scheduler submit failed: ${message}`);
|
|
578
|
+
}
|
|
579
|
+
const taskId = extractTaskId(response);
|
|
580
|
+
if (taskId === undefined) {
|
|
581
|
+
throw new LedgerError("ledger_invalid_transition", "scheduler submit returned a malformed envelope");
|
|
582
|
+
}
|
|
583
|
+
this.append(workItemId, "dispatch", {
|
|
584
|
+
kind: "dispatch",
|
|
585
|
+
dispatch: {
|
|
586
|
+
expectedRecordRevision: expected,
|
|
587
|
+
dispatch: {
|
|
588
|
+
taskId,
|
|
589
|
+
requestId,
|
|
590
|
+
requirementsRevisionAtSubmit: item.requirementsRevision,
|
|
591
|
+
ownerSessionId: this.options.session.getSessionId(),
|
|
592
|
+
generation: item.executionGeneration + 1,
|
|
593
|
+
expiresAt: this.now().getTime() + (this.options.leaseMs ?? DEFAULT_LEASE_MS),
|
|
594
|
+
...(userDeadlineAt === undefined ? {} : { deadlineAt: userDeadlineAt }),
|
|
595
|
+
deadlineRevision: 1,
|
|
596
|
+
dispatchedAt: this.now().toISOString(),
|
|
597
|
+
},
|
|
598
|
+
},
|
|
599
|
+
});
|
|
600
|
+
return this.replay(workItemId);
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* 非阻塞结果回填(草案 §6.1 查询不等待):对在途 taskId peek,终态才写
|
|
604
|
+
* dispatch_result;在途/未知原样返回当前投影。poll 同时承担租期 timer 检查
|
|
605
|
+
* (§6.3:到期先对账,证停后 timed_out/cancelled)、语义进展提示(§6.2)与
|
|
606
|
+
* runner probe 健康判定(§6.2:15s/5s/3 strikes,超限自动进入停止协议)。
|
|
607
|
+
*/
|
|
608
|
+
async poll(input) {
|
|
609
|
+
const workItemId = this.workItemId(input);
|
|
610
|
+
let item = this.replay(workItemId);
|
|
611
|
+
// §6.4 复评点:run/退回计数到达冻结阈值 → 提示管家复评(不自动改账,管家经
|
|
612
|
+
// action=review 落结论)。在 dispatch 早退之前覆盖 queued/awaiting_review 事项。
|
|
613
|
+
this.maybeNotifyReviewPoint(item);
|
|
614
|
+
if (item.dispatch === undefined) {
|
|
615
|
+
this.healthStates.delete(workItemId);
|
|
616
|
+
// §12 AC-04 capacity 队列复查:槽满的事项在下一轮 poll 自动重派。
|
|
617
|
+
await this.retryCapacityWait(workItemId, item);
|
|
618
|
+
return this.replay(workItemId);
|
|
619
|
+
}
|
|
620
|
+
// §6.2 runner probe 健康判定:连续超时达到上限时由 poll 串行执行停止协议
|
|
621
|
+
// (fence → 调度器 cancel → 证停),不再走后续租期/结算路径。
|
|
622
|
+
const unresponsive = this.probeHealth(item);
|
|
623
|
+
if (unresponsive !== undefined) {
|
|
624
|
+
this.healthStates.delete(workItemId);
|
|
625
|
+
// §5.2 健康词汇:通讯无响应先落账(health:unresponsive),再进停止协议。
|
|
626
|
+
this.recordHealthIf(workItemId, "unresponsive", unresponsive);
|
|
627
|
+
await this.stopUnresponsive(workItemId, unresponsive);
|
|
628
|
+
return this.replay(workItemId);
|
|
629
|
+
}
|
|
630
|
+
// §6.2 语义进展:running 且距上次可核对进展超 15 分钟 → 提示一次,不杀不重派。
|
|
631
|
+
this.maybeNotifyStall(item);
|
|
632
|
+
// §6.3 租期 timer:到期先对账耐久终态——peek 已 settled 则按回执收敛,否则
|
|
633
|
+
// fence + 调度器 cancel + 证停(AC-08:CAS 冲突重读仍到期则继续停止)。
|
|
634
|
+
const effectiveDeadline = (dispatch) => dispatch.deadlineAt === undefined ? dispatch.expiresAt : Math.min(dispatch.expiresAt, dispatch.deadlineAt);
|
|
635
|
+
while (item.status === "running" &&
|
|
636
|
+
item.dispatch !== undefined &&
|
|
637
|
+
this.now().getTime() >= effectiveDeadline(item.dispatch)) {
|
|
638
|
+
const settled = await this.peekSettled(item.dispatch.taskId);
|
|
639
|
+
if (settled !== undefined) {
|
|
640
|
+
item = await this.settleDispatch(workItemId, settled.taskId, settled.outcome, settled.sessionId);
|
|
641
|
+
break;
|
|
642
|
+
}
|
|
643
|
+
const deadlineExceeded = `deadline_exceeded at ${new Date(effectiveDeadline(item.dispatch)).toISOString()}`;
|
|
644
|
+
try {
|
|
645
|
+
this.append(workItemId, "fence", {
|
|
646
|
+
kind: "fence",
|
|
647
|
+
control: { expectedRecordRevision: item.recordRevision, reason: deadlineExceeded },
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
catch (error) {
|
|
651
|
+
if (error instanceof LedgerError && error.code === "ledger_cas_mismatch") {
|
|
652
|
+
// CAS 冲突:重读有效期限与状态,仍到期则继续停止(AC-08)。
|
|
653
|
+
const reread = this.replay(workItemId);
|
|
654
|
+
if (reread.status === "running" &&
|
|
655
|
+
reread.dispatch !== undefined &&
|
|
656
|
+
this.now().getTime() >= reread.dispatch.expiresAt) {
|
|
657
|
+
item = reread;
|
|
658
|
+
continue;
|
|
659
|
+
}
|
|
660
|
+
return reread;
|
|
661
|
+
}
|
|
662
|
+
throw error;
|
|
663
|
+
}
|
|
664
|
+
await this.scheduler().call({
|
|
665
|
+
version: 2,
|
|
666
|
+
action: "cancel",
|
|
667
|
+
taskId: item.dispatch.taskId,
|
|
668
|
+
reason: deadlineExceeded,
|
|
669
|
+
});
|
|
670
|
+
item = await this.confirmStop(workItemId, item.dispatch.taskId);
|
|
671
|
+
break;
|
|
672
|
+
}
|
|
673
|
+
if (item.dispatch === undefined)
|
|
674
|
+
return item;
|
|
675
|
+
let response;
|
|
676
|
+
try {
|
|
677
|
+
response = await this.scheduler().call({ version: 2, action: "peek", taskId: item.dispatch.taskId });
|
|
678
|
+
}
|
|
679
|
+
catch {
|
|
680
|
+
return item; // 调度器故障时保守返回当前投影,不伪造结果。
|
|
681
|
+
}
|
|
682
|
+
if (!isPeekEnvelope(response))
|
|
683
|
+
return item;
|
|
684
|
+
if (!response.settled)
|
|
685
|
+
return item;
|
|
686
|
+
const outcome = response.status;
|
|
687
|
+
if (outcome !== "succeeded" && outcome !== "failed" && outcome !== "cancelled" && outcome !== "timed_out") {
|
|
688
|
+
return item; // unknown/意外词汇:不写账本,保守返回当前投影。
|
|
689
|
+
}
|
|
690
|
+
return this.settleDispatch(workItemId, item.dispatch.taskId, outcome);
|
|
691
|
+
}
|
|
692
|
+
/** 验收(AC-16):CAS + 逐条 AC + 证据齐备。 */
|
|
693
|
+
accept(input) {
|
|
694
|
+
const workItemId = this.workItemId(input);
|
|
695
|
+
const expected = requiredRevision(input.expectedRecordRevision);
|
|
696
|
+
const checks = input.checks;
|
|
697
|
+
if (!Array.isArray(checks))
|
|
698
|
+
throw new LedgerError("ledger_invalid_input", "accept requires a checks array");
|
|
699
|
+
const parsed = checks.map((raw) => {
|
|
700
|
+
const entry = raw;
|
|
701
|
+
const criterion = typeof entry.criterion === "string" ? entry.criterion : "";
|
|
702
|
+
const outcome = entry.outcome;
|
|
703
|
+
if (criterion === "" || (outcome !== "pass" && outcome !== "fail" && outcome !== "not_verified")) {
|
|
704
|
+
throw new LedgerError("ledger_invalid_input", "accept checks entries need criterion and outcome(pass|fail|not_verified)");
|
|
705
|
+
}
|
|
706
|
+
return {
|
|
707
|
+
criterion,
|
|
708
|
+
outcome,
|
|
709
|
+
...(typeof entry.evidence === "string" ? { evidence: entry.evidence } : {}),
|
|
710
|
+
};
|
|
711
|
+
});
|
|
712
|
+
const deliverableLocation = typeof input.deliverableLocation === "string" ? input.deliverableLocation : undefined;
|
|
713
|
+
this.append(workItemId, "accept", {
|
|
714
|
+
kind: "accept",
|
|
715
|
+
accept: {
|
|
716
|
+
expectedRecordRevision: expected,
|
|
717
|
+
checks: parsed,
|
|
718
|
+
...(typeof input.artifactFingerprint === "string"
|
|
719
|
+
? { artifactFingerprint: input.artifactFingerprint }
|
|
720
|
+
: {}),
|
|
721
|
+
...(deliverableLocation === undefined ? {} : { deliverableLocation }),
|
|
722
|
+
...(deliverableLocation === undefined
|
|
723
|
+
? {}
|
|
724
|
+
: { deliverableHash: hashDeliverableFile(deliverableLocation, this.toolContextCwd) }),
|
|
725
|
+
},
|
|
726
|
+
});
|
|
727
|
+
return this.replay(workItemId);
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* 执行租期续租(§6.3 extendLease):绑定事项/attempt/expectedDeadlineRevision,
|
|
731
|
+
* 仅 now < expiresAt 且无 stop/终态时原子延长,单次 ≤30 分钟;续租原因与新
|
|
732
|
+
* expiresAt 持久记账。stop 先提交或已到期限则拒绝(AC-08)。
|
|
733
|
+
*/
|
|
734
|
+
extendLease(input) {
|
|
735
|
+
const workItemId = this.workItemId(input);
|
|
736
|
+
const expected = requiredRevision(input.expectedRecordRevision);
|
|
737
|
+
const item = this.replay(workItemId);
|
|
738
|
+
if (item.dispatch === undefined) {
|
|
739
|
+
throw new LedgerError("ledger_invalid_input", `extend_lease requires an active dispatch on ${workItemId}`);
|
|
740
|
+
}
|
|
741
|
+
const extensionMs = typeof input.extensionMs === "number" && Number.isSafeInteger(input.extensionMs) && input.extensionMs > 0
|
|
742
|
+
? input.extensionMs
|
|
743
|
+
: MAX_LEASE_EXTENSION_MS;
|
|
744
|
+
if (extensionMs > MAX_LEASE_EXTENSION_MS) {
|
|
745
|
+
throw new LedgerError("ledger_invalid_input", `extend_lease extensionMs exceeds the ${MAX_LEASE_EXTENSION_MS}ms single-extension cap (§6.3)`);
|
|
746
|
+
}
|
|
747
|
+
const now = this.now().getTime();
|
|
748
|
+
if (now >= item.dispatch.expiresAt) {
|
|
749
|
+
throw new LedgerError("ledger_invalid_transition", `extend_lease refused: lease already expired at ${new Date(item.dispatch.expiresAt).toISOString()}`);
|
|
750
|
+
}
|
|
751
|
+
// 在现有到期基础上延长(extensionMs ≤ 30 分钟上限已校验),不缩短原租期;
|
|
752
|
+
// 用户硬截止优先——续租不得越过 deadlineAt(§6.4)。
|
|
753
|
+
const newExpiresAt = item.dispatch.deadlineAt === undefined
|
|
754
|
+
? item.dispatch.expiresAt + extensionMs
|
|
755
|
+
: Math.min(item.dispatch.expiresAt + extensionMs, item.dispatch.deadlineAt);
|
|
756
|
+
if (newExpiresAt <= now) {
|
|
757
|
+
throw new LedgerError("ledger_invalid_transition", `extend_lease refused: user hard deadline at ${new Date(item.dispatch.deadlineAt ?? 0).toISOString()} leaves no lease to extend`);
|
|
758
|
+
}
|
|
759
|
+
this.append(workItemId, "extend_lease", {
|
|
760
|
+
kind: "extend_lease",
|
|
761
|
+
extend: {
|
|
762
|
+
expectedRecordRevision: expected,
|
|
763
|
+
taskId: item.dispatch.taskId,
|
|
764
|
+
expectedDeadlineRevision: item.dispatch.deadlineRevision,
|
|
765
|
+
newExpiresAt,
|
|
766
|
+
reason: typeof input.reason === "string" ? input.reason : "lease extended",
|
|
767
|
+
},
|
|
768
|
+
});
|
|
769
|
+
return this.replay(workItemId);
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* §6.4 软复评:CAS + planRevision+1 + 用量锚快照;结论摘要落 note。不关闭
|
|
773
|
+
* executionGeneration、不改授权——复评不中断在途执行。
|
|
774
|
+
*/
|
|
775
|
+
review(input) {
|
|
776
|
+
const workItemId = this.workItemId(input);
|
|
777
|
+
const expected = requiredRevision(input.expectedRecordRevision);
|
|
778
|
+
const summary = requiredString(input.summary, "summary");
|
|
779
|
+
this.append(workItemId, "review", {
|
|
780
|
+
kind: "review",
|
|
781
|
+
review: { expectedRecordRevision: expected, summary },
|
|
782
|
+
});
|
|
783
|
+
return this.replay(workItemId);
|
|
784
|
+
}
|
|
785
|
+
/** 通用控制动作(cancel/pause/continue/rework/fence)。 */
|
|
786
|
+
control(op, input) {
|
|
787
|
+
const workItemId = this.workItemId(input);
|
|
788
|
+
const expected = requiredRevision(input.expectedRecordRevision);
|
|
789
|
+
this.append(workItemId, op, {
|
|
790
|
+
kind: op,
|
|
791
|
+
control: {
|
|
792
|
+
expectedRecordRevision: expected,
|
|
793
|
+
...(typeof input.reason === "string" ? { reason: input.reason } : {}),
|
|
794
|
+
},
|
|
795
|
+
});
|
|
796
|
+
return this.replay(workItemId);
|
|
797
|
+
}
|
|
798
|
+
/** peek 查询:settled 时返回终态词汇;在途/未知返回 undefined。 */
|
|
799
|
+
async peekSettled(taskId) {
|
|
800
|
+
try {
|
|
801
|
+
const response = await this.scheduler().call({ version: 2, action: "peek", taskId });
|
|
802
|
+
if (!isPeekEnvelope(response) || !response.settled)
|
|
803
|
+
return undefined;
|
|
804
|
+
const outcome = response.status;
|
|
805
|
+
if (outcome !== "succeeded" && outcome !== "failed" && outcome !== "cancelled" && outcome !== "timed_out")
|
|
806
|
+
return undefined;
|
|
807
|
+
return { taskId, outcome };
|
|
808
|
+
}
|
|
809
|
+
catch {
|
|
810
|
+
return undefined; // 调度器故障:保守视为未证停。
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* 回填终态(poll/证停共用):终态词汇落 dispatch_result。未 fence 时成功与失败
|
|
815
|
+
* 都回读 result——成功取报告/会话,失败取结构化错误码(`subagent_runner_lost`
|
|
816
|
+
* 是 health:exited 落账的依据,§5.2 记录维度分离)。
|
|
817
|
+
*/
|
|
818
|
+
async settleDispatch(workItemId, taskId, outcome, sessionId) {
|
|
819
|
+
const item = this.replay(workItemId);
|
|
820
|
+
let report;
|
|
821
|
+
let error;
|
|
822
|
+
let errorCode;
|
|
823
|
+
if (item.fence === undefined) {
|
|
824
|
+
const resultEnvelope = await this.scheduler().call({ version: 2, action: "result", taskId });
|
|
825
|
+
const result = extractResult(resultEnvelope);
|
|
826
|
+
if (result !== undefined) {
|
|
827
|
+
sessionId = result.sessionId ?? sessionId;
|
|
828
|
+
if (outcome === "succeeded") {
|
|
829
|
+
report = result.checks;
|
|
830
|
+
}
|
|
831
|
+
else {
|
|
832
|
+
error = outcome;
|
|
833
|
+
errorCode = result.errorCode;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
else if (outcome !== "succeeded") {
|
|
837
|
+
error = outcome;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
else {
|
|
841
|
+
// fenced(stopping):只有"已证停"cancelled 收敛;旧代成果留证不回读。
|
|
842
|
+
error = outcome;
|
|
843
|
+
}
|
|
844
|
+
this.append(workItemId, "dispatch_result", {
|
|
845
|
+
kind: "dispatch_result",
|
|
846
|
+
result: {
|
|
847
|
+
expectedRecordRevision: item.recordRevision,
|
|
848
|
+
taskId,
|
|
849
|
+
outcome,
|
|
850
|
+
...(report === undefined ? {} : { report }),
|
|
851
|
+
...(error === undefined ? {} : { error }),
|
|
852
|
+
...(errorCode === undefined ? {} : { errorCode }),
|
|
853
|
+
...(sessionId === undefined ? {} : { sessionId }),
|
|
854
|
+
},
|
|
855
|
+
});
|
|
856
|
+
// §5.2 记录维度分离:runner_lost(runner 进程退出)→ health:exited 落账
|
|
857
|
+
//(§15.1 裁决:task-manager 侧捕获 error.code,不动调度器公共契约)。
|
|
858
|
+
if (errorCode === "subagent_runner_lost") {
|
|
859
|
+
this.recordHealthIf(workItemId, "exited", "runner_lost: the runner carrying this attempt exited");
|
|
860
|
+
}
|
|
861
|
+
// 进展锚:结果回填是可核对进展(§6.2 重置点)。
|
|
862
|
+
this.lastSemanticProgressAt.set(workItemId, this.now().getTime());
|
|
863
|
+
this.stalledNotified.delete(workItemId);
|
|
864
|
+
this.healthStates.delete(workItemId); // 派发已终态:probe 健康判定随之结束。
|
|
865
|
+
return this.replay(workItemId);
|
|
866
|
+
}
|
|
867
|
+
/**
|
|
868
|
+
* 证停:fence 后对在途 taskId 查询调度器回执,cancelled 落 dispatch_result
|
|
869
|
+
* 收敛 cancelled;无法证停保持 stopping(blocked 语义的账本层,草案 §8.2 40 秒
|
|
870
|
+
* 等待与升级终止由宿主 runner 协议承担,账本只记事实)。
|
|
871
|
+
*/
|
|
872
|
+
async confirmStop(workItemId, taskId) {
|
|
873
|
+
const settled = await this.peekSettled(taskId);
|
|
874
|
+
if (settled !== undefined && settled.outcome === "cancelled") {
|
|
875
|
+
return this.settleDispatch(workItemId, taskId, "cancelled", settled.sessionId);
|
|
876
|
+
}
|
|
877
|
+
return this.replay(workItemId); // 仍未证停:stopping 保持,写域占用、不再派发。
|
|
878
|
+
}
|
|
879
|
+
/** §6.2 停滞提示:连续 15 分钟无可核对进展 → 提示一次(不杀、不重派)。 */
|
|
880
|
+
maybeNotifyStall(item) {
|
|
881
|
+
const notify = this.options.notify;
|
|
882
|
+
if (notify === undefined || item.dispatch === undefined)
|
|
883
|
+
return;
|
|
884
|
+
const now = this.now().getTime();
|
|
885
|
+
const last = this.lastSemanticProgressAt.get(item.workItemId) ??
|
|
886
|
+
item.dispatch.expiresAt - (this.options.leaseMs ?? DEFAULT_LEASE_MS);
|
|
887
|
+
if (now - last < SEMANTIC_STALL_MS || this.stalledNotified.has(item.workItemId))
|
|
888
|
+
return;
|
|
889
|
+
this.stalledNotified.add(item.workItemId);
|
|
890
|
+
notify({
|
|
891
|
+
eventId: `${item.workItemId}:stall:${Math.floor(now / SEMANTIC_STALL_MS)}`,
|
|
892
|
+
workItemId: item.workItemId,
|
|
893
|
+
title: item.title,
|
|
894
|
+
status: item.status,
|
|
895
|
+
detail: `no verifiable progress for ${SEMANTIC_STALL_MS / 60_000} minutes; check the runner (no automatic kill, AC-07)`,
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
/** §6.4 复评点提示:用量到达冻结阈值即提示一次(复评后锚点推进 → 新阈值)。 */
|
|
899
|
+
maybeNotifyReviewPoint(item) {
|
|
900
|
+
const notify = this.options.notify;
|
|
901
|
+
if (notify === undefined)
|
|
902
|
+
return;
|
|
903
|
+
const anchor = item.lastReview;
|
|
904
|
+
const first = anchor === undefined;
|
|
905
|
+
const runsThreshold = first ? REVIEW_FIRST_RUNS : anchor.runs + REVIEW_NEXT_RUNS;
|
|
906
|
+
const reworkThreshold = first ? REVIEW_FIRST_REWORKS : anchor.reworks + REVIEW_NEXT_REWORKS;
|
|
907
|
+
const runsHit = item.usage.acceptedRuns >= runsThreshold;
|
|
908
|
+
const reworksHit = item.usage.reworkCount >= reworkThreshold;
|
|
909
|
+
if (!runsHit && !reworksHit)
|
|
910
|
+
return;
|
|
911
|
+
const key = `${item.workItemId}:${item.planRevision}:${item.usage.acceptedRuns}:${item.usage.reworkCount}`;
|
|
912
|
+
if (this.reviewNotifiedKeys.has(key))
|
|
913
|
+
return;
|
|
914
|
+
this.reviewNotifiedKeys.add(key);
|
|
915
|
+
notify({
|
|
916
|
+
eventId: `${item.workItemId}:review:${item.planRevision}:${item.usage.acceptedRuns}:${item.usage.reworkCount}`,
|
|
917
|
+
workItemId: item.workItemId,
|
|
918
|
+
title: item.title,
|
|
919
|
+
status: item.status,
|
|
920
|
+
detail: `review point reached (§6.4): ${item.usage.acceptedRuns} accepted runs / ${item.usage.reworkCount} reworks since the last review anchor. Perform a butler review via assistant_task action=review: evidence, remaining AC, keep or replace worker/method, next action and checkpoint.`,
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* §6.2 runner probe 健康判定(poll 携带的在途派发检查):无在途且距上次发送
|
|
925
|
+
* ≥15s 发新 probe(专用轻量通道,同一 runner 至多一个在途);在途 probe 超过
|
|
926
|
+
* 5s 回执期限计一次连续超时,连续 3 次返回通讯无响应原因(由 poll 串行执行
|
|
927
|
+
* 停止协议,避免与 poll 自身结算路径并发竞态)。任一有效新回执清零计数;
|
|
928
|
+
* probe 调度间隔超 45s(宿主暂停)清除计数并重新探测。发送失败不计超时。
|
|
929
|
+
*/
|
|
930
|
+
probeHealth(item) {
|
|
931
|
+
if (item.dispatch === undefined || item.status !== "running") {
|
|
932
|
+
this.healthStates.delete(item.workItemId);
|
|
933
|
+
return undefined;
|
|
934
|
+
}
|
|
935
|
+
const workItemId = item.workItemId;
|
|
936
|
+
const now = this.now().getTime();
|
|
937
|
+
let state = this.healthStates.get(workItemId);
|
|
938
|
+
if (state === undefined) {
|
|
939
|
+
state = { strikes: 0 };
|
|
940
|
+
this.healthStates.set(workItemId, state);
|
|
941
|
+
}
|
|
942
|
+
if (state.lastTickAt !== undefined && now - state.lastTickAt > PROBE_SCHEDULE_RESET_MS) {
|
|
943
|
+
// 宿主调度暂停:清零计数并重新探测(在途 probe 作废)。
|
|
944
|
+
state.strikes = 0;
|
|
945
|
+
state.pendingSince = undefined;
|
|
946
|
+
state.lastSentAt = undefined;
|
|
947
|
+
}
|
|
948
|
+
state.lastTickAt = now;
|
|
949
|
+
if (state.pendingSince !== undefined && now - state.pendingSince >= PROBE_DEADLINE_MS) {
|
|
950
|
+
state.pendingSince = undefined;
|
|
951
|
+
state.strikes += 1;
|
|
952
|
+
}
|
|
953
|
+
if (state.strikes >= PROBE_MAX_STRIKES) {
|
|
954
|
+
this.healthStates.delete(workItemId);
|
|
955
|
+
return `probe_unresponsive: ${PROBE_MAX_STRIKES} consecutive probes unanswered for over ${PROBE_DEADLINE_MS}ms each`;
|
|
956
|
+
}
|
|
957
|
+
// §5.2 健康词汇落账本:1-2 次连续超时 → suspect(词汇变化才记录)。
|
|
958
|
+
if (state.strikes > 0 && item.health !== "suspect") {
|
|
959
|
+
this.recordHealthIf(workItemId, "suspect", `${state.strikes} consecutive probe timeout(s) over ${PROBE_DEADLINE_MS}ms each`);
|
|
960
|
+
}
|
|
961
|
+
if (state.pendingSince === undefined &&
|
|
962
|
+
(state.lastSentAt === undefined || now - state.lastSentAt >= PROBE_INTERVAL_MS)) {
|
|
963
|
+
state.lastSentAt = now;
|
|
964
|
+
state.pendingSince = now;
|
|
965
|
+
void this.scheduler()
|
|
966
|
+
.call({ version: 2, action: "probe" })
|
|
967
|
+
.then(() => {
|
|
968
|
+
const fresh = this.healthStates.get(workItemId);
|
|
969
|
+
if (fresh === undefined)
|
|
970
|
+
return;
|
|
971
|
+
fresh.pendingSince = undefined;
|
|
972
|
+
fresh.strikes = 0; // 任一有效新回执清零(§6.2)。
|
|
973
|
+
// 健康恢复:回执期限内到达 → responsive(词汇变化才记录)。
|
|
974
|
+
this.recordHealthIf(workItemId, "responsive", "probe receipt within the deadline");
|
|
975
|
+
})
|
|
976
|
+
.catch(() => {
|
|
977
|
+
const fresh = this.healthStates.get(workItemId);
|
|
978
|
+
if (fresh === undefined)
|
|
979
|
+
return;
|
|
980
|
+
fresh.pendingSince = undefined; // 发送失败 ≠ 超时:不计数,按节奏重试。
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
return undefined;
|
|
984
|
+
}
|
|
985
|
+
/**
|
|
986
|
+
* §5.2 健康词汇落账本(health op):观察到的词汇与当前投影不同才写(写入方
|
|
987
|
+
* 去重纪律);终态事项不再记录。不改工作状态,只增账本版本。
|
|
988
|
+
*/
|
|
989
|
+
recordHealthIf(workItemId, word, detail) {
|
|
990
|
+
try {
|
|
991
|
+
const item = this.replay(workItemId);
|
|
992
|
+
if (item.status === "completed" || item.status === "cancelled")
|
|
993
|
+
return;
|
|
994
|
+
if (item.health === word)
|
|
995
|
+
return;
|
|
996
|
+
this.append(workItemId, "health", {
|
|
997
|
+
kind: "health",
|
|
998
|
+
health: { word, ...(detail === undefined ? {} : { detail }) },
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
catch (error) {
|
|
1002
|
+
if (error instanceof LedgerError)
|
|
1003
|
+
return; // 并发控制竞态:健康记录不与控制动作争抢。
|
|
1004
|
+
throw error;
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
/**
|
|
1008
|
+
* §12 AC-04 capacity 队列复查:槽满等待中的事项在 poll 里自动重派(每次 poll
|
|
1009
|
+
* 至多一次尝试)。要求版本已变更的等待作废(旧 requestId 绑定旧要求,模型按
|
|
1010
|
+
* 新要求重新派发);重派仍槽满则保持等待,原样返回当前投影。
|
|
1011
|
+
*/
|
|
1012
|
+
async retryCapacityWait(workItemId, item) {
|
|
1013
|
+
if (item.status !== "queued" || item.note?.startsWith("capacity-wait") !== true)
|
|
1014
|
+
return;
|
|
1015
|
+
const pending = this.pendingDispatch.get(workItemId);
|
|
1016
|
+
if (pending === undefined)
|
|
1017
|
+
return;
|
|
1018
|
+
if (pending.requirementsRevision !== item.requirementsRevision) {
|
|
1019
|
+
this.pendingDispatch.delete(workItemId); // 要求已变更:旧重试作废,模型重新派发。
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
const fresh = this.replay(workItemId);
|
|
1023
|
+
try {
|
|
1024
|
+
const after = await this.dispatch({ ...pending.input, expectedRecordRevision: fresh.recordRevision });
|
|
1025
|
+
// 只在派发记录真正落地时清除登记:dispatch 对"仍槽满"不抛错(写备注后
|
|
1026
|
+
// 正常返回 queued),无条件 delete 会把刚重挂的重试抹掉——复查只跑一次
|
|
1027
|
+
// 就永久搁浅(真实压测 butler-capacity 取证的 AC-04 缺陷,2026-11-15)。
|
|
1028
|
+
if (after.dispatch !== undefined)
|
|
1029
|
+
this.pendingDispatch.delete(workItemId);
|
|
1030
|
+
}
|
|
1031
|
+
catch {
|
|
1032
|
+
// 抛错路径(非容量故障):保持 capacity-wait,下一轮 poll 再复查。
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
/**
|
|
1036
|
+
* §12 AC-36 owner 级全停:取消本账本全部未终结事项(task-manager 只在主会话
|
|
1037
|
+
* 注册,账本即本 owner 的完整事项面);cancelIntentIds 为"已分类未建"的接单
|
|
1038
|
+
* 意图落持久墓碑(AC-36:崩溃重放后 create 对墓碑意图结构化拒绝,不重新接单
|
|
1039
|
+
* 派发)。终态事项与已有墓碑幂等跳过;stopping(已 fence 待证停)保持原状——
|
|
1040
|
+
* 停止协议进行中,不重复提交。单项 CAS 竞态不阻塞全停清单(best-effort)。
|
|
1041
|
+
*/
|
|
1042
|
+
async stopAll(input) {
|
|
1043
|
+
const reason = typeof input.reason === "string" && input.reason.trim() !== "" ? input.reason : "stop_all";
|
|
1044
|
+
const view = this.view();
|
|
1045
|
+
for (const intentId of Array.isArray(input.cancelIntentIds)
|
|
1046
|
+
? input.cancelIntentIds.filter((entry) => typeof entry === "string" && entry.trim() !== "")
|
|
1047
|
+
: []) {
|
|
1048
|
+
if (view.cancelledIntents.has(intentId))
|
|
1049
|
+
continue;
|
|
1050
|
+
this.options.session.appendEntry(INTENT_CANCEL_ENTRY_TYPE, { intentId, at: this.now().toISOString(), reason });
|
|
1051
|
+
}
|
|
1052
|
+
const affected = [];
|
|
1053
|
+
for (const [workItemId, item] of view.items) {
|
|
1054
|
+
if (item.status === "completed" || item.status === "cancelled" || item.status === "stopping")
|
|
1055
|
+
continue;
|
|
1056
|
+
try {
|
|
1057
|
+
if (item.status === "running" && item.dispatch !== undefined) {
|
|
1058
|
+
affected.push(await this.stopUnresponsive(workItemId, reason));
|
|
1059
|
+
}
|
|
1060
|
+
else {
|
|
1061
|
+
const latest = this.replay(workItemId);
|
|
1062
|
+
affected.push(this.control("cancel", { workItemId, expectedRecordRevision: latest.recordRevision, reason }));
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
catch (error) {
|
|
1066
|
+
if (error instanceof LedgerError)
|
|
1067
|
+
continue; // 并发控制竞态:单项失败不阻塞全停。
|
|
1068
|
+
throw error;
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
return affected;
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* §6.2 通讯无响应的自动停止协议入口:fence(不可撤销)→ 调度器 cancel → 证停
|
|
1075
|
+
* 收敛 cancelled;无法证停保持 stopping(与租期到期同一停止语义,草案 §8.2)。
|
|
1076
|
+
*/
|
|
1077
|
+
async stopUnresponsive(workItemId, reason) {
|
|
1078
|
+
const item = this.replay(workItemId);
|
|
1079
|
+
if (item.status !== "running" || item.dispatch === undefined)
|
|
1080
|
+
return item;
|
|
1081
|
+
try {
|
|
1082
|
+
this.append(workItemId, "fence", {
|
|
1083
|
+
kind: "fence",
|
|
1084
|
+
control: { expectedRecordRevision: item.recordRevision, reason },
|
|
1085
|
+
});
|
|
1086
|
+
}
|
|
1087
|
+
catch (error) {
|
|
1088
|
+
if (error instanceof LedgerError) {
|
|
1089
|
+
// CAS 冲突或已 fence:并发控制者已处理停止,交还原路径收敛。
|
|
1090
|
+
return this.replay(workItemId);
|
|
1091
|
+
}
|
|
1092
|
+
throw error;
|
|
1093
|
+
}
|
|
1094
|
+
await this.scheduler().call({ version: 2, action: "cancel", taskId: item.dispatch.taskId, reason });
|
|
1095
|
+
return this.confirmStop(workItemId, item.dispatch.taskId);
|
|
1096
|
+
}
|
|
1097
|
+
workItemId(input) {
|
|
1098
|
+
const value = input.workItemId;
|
|
1099
|
+
if (typeof value !== "string" || !ITEM_ID_PATTERN.test(value)) {
|
|
1100
|
+
throw new LedgerError("ledger_invalid_input", `workItemId must match ${ITEM_ID_PATTERN.source}, got ${JSON.stringify(value)}`);
|
|
1101
|
+
}
|
|
1102
|
+
return value;
|
|
1103
|
+
}
|
|
1104
|
+
/**
|
|
1105
|
+
* AC-37 依赖登记校验:目标存在、不含自身、无环(沿 dependsOn 图走不得回到
|
|
1106
|
+
* self)。返回去重后的规范化副本;未提供返回 undefined。
|
|
1107
|
+
*/
|
|
1108
|
+
validateDependsOn(raw, selfWorkItemId) {
|
|
1109
|
+
if (raw === undefined)
|
|
1110
|
+
return undefined;
|
|
1111
|
+
if (!Array.isArray(raw) || raw.some((entry) => typeof entry !== "string" || entry.trim() === "")) {
|
|
1112
|
+
throw new LedgerError("ledger_invalid_input", "dependsOn must be an array of non-empty workItemId strings");
|
|
1113
|
+
}
|
|
1114
|
+
const dependsOn = [...new Set(raw)];
|
|
1115
|
+
if (selfWorkItemId === undefined)
|
|
1116
|
+
return dependsOn;
|
|
1117
|
+
if (dependsOn.includes(selfWorkItemId)) {
|
|
1118
|
+
throw new LedgerError("ledger_invalid_input", "dependsOn cannot include the work item itself");
|
|
1119
|
+
}
|
|
1120
|
+
// 单次重放:存在性校验与环检测共用同一投影,循环内不重放账本。
|
|
1121
|
+
const view = this.view();
|
|
1122
|
+
for (const depId of dependsOn) {
|
|
1123
|
+
if (view.items.get(depId) === undefined) {
|
|
1124
|
+
throw new LedgerError("ledger_invalid_input", `dependsOn references unknown work item ${depId}`);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
const visited = new Set();
|
|
1128
|
+
const stack = [...dependsOn];
|
|
1129
|
+
while (stack.length > 0) {
|
|
1130
|
+
const current = stack.pop();
|
|
1131
|
+
if (current === selfWorkItemId) {
|
|
1132
|
+
throw new LedgerError("ledger_invalid_input", "dependsOn registration would create a dependency cycle");
|
|
1133
|
+
}
|
|
1134
|
+
if (visited.has(current))
|
|
1135
|
+
continue;
|
|
1136
|
+
visited.add(current);
|
|
1137
|
+
const deps = view.items.get(current)?.dependsOn;
|
|
1138
|
+
if (deps !== undefined)
|
|
1139
|
+
stack.push(...deps);
|
|
1140
|
+
}
|
|
1141
|
+
return dependsOn;
|
|
1142
|
+
}
|
|
1143
|
+
replay(workItemId, _at) {
|
|
1144
|
+
const view = this.view();
|
|
1145
|
+
const item = view.items.get(workItemId);
|
|
1146
|
+
if (item === undefined) {
|
|
1147
|
+
throw new LedgerError("ledger_invalid_input", `unknown work item ${workItemId}`);
|
|
1148
|
+
}
|
|
1149
|
+
return item;
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
function requiredString(value, field) {
|
|
1153
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
1154
|
+
throw new LedgerError("ledger_invalid_input", `${field} must be a non-empty string`);
|
|
1155
|
+
}
|
|
1156
|
+
return value;
|
|
1157
|
+
}
|
|
1158
|
+
function requiredRevision(value) {
|
|
1159
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
|
|
1160
|
+
throw new LedgerError("ledger_invalid_input", "expectedRecordRevision must be a non-negative integer");
|
|
1161
|
+
}
|
|
1162
|
+
return value;
|
|
1163
|
+
}
|
|
1164
|
+
function requiredStringArray(value, field) {
|
|
1165
|
+
if (!Array.isArray(value) ||
|
|
1166
|
+
value.length === 0 ||
|
|
1167
|
+
value.some((entry) => typeof entry !== "string" || entry.trim() === "")) {
|
|
1168
|
+
throw new LedgerError("ledger_invalid_input", `${field} must be a non-empty array of non-empty strings`);
|
|
1169
|
+
}
|
|
1170
|
+
return [...value];
|
|
1171
|
+
}
|
|
1172
|
+
function isPlainRecord(value) {
|
|
1173
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1174
|
+
}
|
|
1175
|
+
/**
|
|
1176
|
+
* AC-15/23 证据钉:deliverableLocation 指向真实存在的普通文件时计算 sha256(hex),
|
|
1177
|
+
* 相对路径按进程 cwd 解析;带 URI scheme 的落点(ledger://、git: 等)与非文件
|
|
1178
|
+
* 落点(提交/发布/口头答复)返回 undefined——不伪造 hash,也不因无法 hash 拒绝
|
|
1179
|
+
* 验收(hash 是证据增强,不是验收门)。
|
|
1180
|
+
*/
|
|
1181
|
+
/** hash 钉的单文件上限:超过即不钉(readFileSync 会整载入内存并阻塞事件循环)。 */
|
|
1182
|
+
const DELIVERABLE_HASH_MAX_BYTES = 64 * 1024 * 1024;
|
|
1183
|
+
export function hashDeliverableFile(deliverableLocation, baseCwd) {
|
|
1184
|
+
// URI scheme 至少 2 个字符(RFC 3986 惯例);单字母前缀可能是 Windows 盘符(`C:\...`),不得当 scheme。
|
|
1185
|
+
if (/^[a-z][a-z0-9+.-]+:/i.test(deliverableLocation))
|
|
1186
|
+
return undefined;
|
|
1187
|
+
const path = isAbsolute(deliverableLocation)
|
|
1188
|
+
? deliverableLocation
|
|
1189
|
+
: resolve(baseCwd ?? process.cwd(), deliverableLocation);
|
|
1190
|
+
if (!existsSync(path))
|
|
1191
|
+
return undefined;
|
|
1192
|
+
try {
|
|
1193
|
+
const stats = statSync(path);
|
|
1194
|
+
if (!stats.isFile() || stats.size > DELIVERABLE_HASH_MAX_BYTES)
|
|
1195
|
+
return undefined;
|
|
1196
|
+
return createHash("sha256").update(readFileSync(path)).digest("hex");
|
|
1197
|
+
}
|
|
1198
|
+
catch {
|
|
1199
|
+
return undefined; // 读取竞态:无 hash 不伪造。
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
/** 提交响应 → taskId。 */
|
|
1203
|
+
function extractTaskId(response) {
|
|
1204
|
+
if (response === null || typeof response !== "object")
|
|
1205
|
+
return undefined;
|
|
1206
|
+
const view = response;
|
|
1207
|
+
if (view.action !== "submit" && view.action !== "resume")
|
|
1208
|
+
return undefined;
|
|
1209
|
+
if (typeof view.taskId !== "string" || view.taskId === "")
|
|
1210
|
+
return undefined;
|
|
1211
|
+
return view.taskId;
|
|
1212
|
+
}
|
|
1213
|
+
function isPeekEnvelope(response) {
|
|
1214
|
+
if (response === null || typeof response !== "object")
|
|
1215
|
+
return false;
|
|
1216
|
+
const view = response;
|
|
1217
|
+
return view.action === "peek" && typeof view.settled === "boolean" && typeof view.status === "string";
|
|
1218
|
+
}
|
|
1219
|
+
/** result 投影 → 报告(AC 结论数组按调度器 details 约定携带;无则缺省)。 */
|
|
1220
|
+
function extractResult(response) {
|
|
1221
|
+
if (response === null || typeof response !== "object")
|
|
1222
|
+
return undefined;
|
|
1223
|
+
const view = response;
|
|
1224
|
+
if (view.action !== "result" || view.result === undefined || typeof view.result !== "object")
|
|
1225
|
+
return undefined;
|
|
1226
|
+
const details = view.result.details;
|
|
1227
|
+
const checks = details !== null &&
|
|
1228
|
+
typeof details === "object" &&
|
|
1229
|
+
Array.isArray(details.acceptanceChecks)
|
|
1230
|
+
? details.acceptanceChecks
|
|
1231
|
+
: undefined;
|
|
1232
|
+
const errorCode = view.result.error !== null &&
|
|
1233
|
+
typeof view.result.error === "object" &&
|
|
1234
|
+
typeof view.result.error.code === "string"
|
|
1235
|
+
? view.result.error.code
|
|
1236
|
+
: undefined;
|
|
1237
|
+
return {
|
|
1238
|
+
...(typeof view.result.sessionId === "string" ? { sessionId: view.result.sessionId } : {}),
|
|
1239
|
+
...(checks === undefined ? {} : { checks }),
|
|
1240
|
+
...(errorCode === undefined ? {} : { errorCode }),
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
//# sourceMappingURL=index.js.map
|