dsh-background-task-engine 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/LICENSE +21 -0
  3. package/README.md +263 -2
  4. package/README.zh.md +179 -0
  5. package/cordis.patch.yml +20 -0
  6. package/dist/config.d.ts +86 -0
  7. package/dist/config.js +106 -0
  8. package/dist/domain/records.d.ts +543 -0
  9. package/dist/domain/records.js +135 -0
  10. package/dist/domain/state.d.ts +61 -0
  11. package/dist/domain/state.js +128 -0
  12. package/dist/errors.d.ts +38 -0
  13. package/dist/errors.js +99 -0
  14. package/dist/host.d.ts +165 -0
  15. package/dist/host.js +56 -0
  16. package/dist/index.d.ts +60 -0
  17. package/dist/index.js +78 -0
  18. package/dist/prompt/guidance.d.ts +30 -0
  19. package/dist/prompt/guidance.js +62 -0
  20. package/dist/services/audit.d.ts +39 -0
  21. package/dist/services/audit.js +48 -0
  22. package/dist/services/engine.d.ts +435 -0
  23. package/dist/services/engine.js +150 -0
  24. package/dist/services/run-service.d.ts +145 -0
  25. package/dist/services/run-service.js +569 -0
  26. package/dist/services/schedule-adapter.d.ts +92 -0
  27. package/dist/services/schedule-adapter.js +220 -0
  28. package/dist/services/task-service.d.ts +146 -0
  29. package/dist/services/task-service.js +490 -0
  30. package/dist/storage/repository.d.ts +65 -0
  31. package/dist/storage/repository.js +194 -0
  32. package/dist/storage/spec.d.ts +97 -0
  33. package/dist/storage/spec.js +149 -0
  34. package/dist/tools/run-tools.d.ts +14 -0
  35. package/dist/tools/run-tools.js +402 -0
  36. package/dist/tools/schedule-tool.d.ts +11 -0
  37. package/dist/tools/schedule-tool.js +238 -0
  38. package/dist/tools/shared.d.ts +108 -0
  39. package/dist/tools/shared.js +278 -0
  40. package/dist/tools/task-tools.d.ts +7 -0
  41. package/dist/tools/task-tools.js +321 -0
  42. package/dist/utils/id.d.ts +8 -0
  43. package/dist/utils/id.js +29 -0
  44. package/dist/utils/page.d.ts +36 -0
  45. package/dist/utils/page.js +71 -0
  46. package/dist/utils/text.d.ts +20 -0
  47. package/dist/utils/text.js +46 -0
  48. package/dist/utils/time.d.ts +7 -0
  49. package/dist/utils/time.js +38 -0
  50. package/docs/API-COMPATIBILITY-AUDIT.md +203 -0
  51. package/docs/DETAIL.md +1 -0
  52. package/docs/DETAIL.zh.md +1 -0
  53. package/docs/TEST-REPORT.md +232 -0
  54. package/docs/preview.svg +68 -0
  55. package/icon.svg +23 -0
  56. package/locale/en.json +7 -0
  57. package/locale/zh.json +7 -0
  58. package/package.json +71 -4
@@ -0,0 +1,569 @@
1
+ /**
2
+ * Run service: manual/schedule execution lifecycle (PRD 5.2, 5.3, FR-005..FR-008,
3
+ * chapter 9.1, acceptance 14.2 / 14.4).
4
+ *
5
+ * Invariants enforced here:
6
+ * - a TaskRun is created only after ownership, task status, concurrency and
7
+ * idempotency checks pass;
8
+ * - the step template is snapshotted into the run, so later task edits cannot
9
+ * change an in-flight run;
10
+ * - steps advance strictly by `order`; a step cannot be reported before its
11
+ * predecessors settled;
12
+ * - `succeeded` requires every required step to be completed;
13
+ * - a failed step is never replayed silently: recovery needs a confirmation.
14
+ */
15
+ import { TaskEngineError } from '../errors.js';
16
+ import { SCHEMA_VERSION, } from '../domain/records.js';
17
+ import { ACTIVE_RUN_STATUSES, RESUMABLE_RUN_STATUSES, assertLinearStart, assertRunTransition, assertStepTransition, computeProgress, firstPendingStep, isActiveRun, isTerminalRun, requiredStepsSettled, } from '../domain/state.js';
18
+ import { newRunId } from '../utils/id.js';
19
+ import { daysAgoIso, isOlderThanMinutes, nowIso } from '../utils/time.js';
20
+ import { truncateText } from '../utils/text.js';
21
+ import { compareDesc, paginate } from '../utils/page.js';
22
+ import { parseTriggerMessage } from '../prompt/guidance.js';
23
+ function normaliseError(input, fallbackCode, maxChars) {
24
+ if (input === undefined || input === null)
25
+ return undefined;
26
+ if (typeof input === 'string') {
27
+ const message = truncateText(input.trim(), maxChars) ?? '';
28
+ if (!message)
29
+ return undefined;
30
+ return { code: fallbackCode, message };
31
+ }
32
+ const message = truncateText(String(input.message ?? '').trim(), maxChars) ?? '';
33
+ if (!message)
34
+ return undefined;
35
+ return { code: (input.code ?? fallbackCode).slice(0, 64), message };
36
+ }
37
+ export class RunService {
38
+ repo;
39
+ config;
40
+ audit;
41
+ now;
42
+ constructor(repo, config, audit, now = nowIso) {
43
+ this.repo = repo;
44
+ this.config = config;
45
+ this.audit = audit;
46
+ this.now = now;
47
+ }
48
+ // -------------------------------------------------------------- start run
49
+ async start(input) {
50
+ const trigger = parseTriggerMessage(input.triggerPayload);
51
+ const taskId = input.taskId ?? trigger.taskId;
52
+ if (!taskId) {
53
+ throw new TaskEngineError('TASK_INVALID_ARGUMENTS', '未提供 taskId,也无法从 triggerPayload 中识别任务标识(缺少 task_id_json)');
54
+ }
55
+ const task = this.repo.requireOwnedTask(taskId, input.sessionId);
56
+ const scheduleId = input.scheduleId ?? trigger.scheduleId;
57
+ const occurrenceKey = input.occurrenceKey ?? trigger.occurrenceKey;
58
+ const idempotencyKey = input.idempotencyKey ??
59
+ (scheduleId && occurrenceKey
60
+ ? `schedule:${scheduleId}:${occurrenceKey}`
61
+ : input.manualRunId
62
+ ? `manual:${input.manualRunId}`
63
+ : undefined);
64
+ // Idempotent replay: the same key always maps to the same TaskRun, so a
65
+ // duplicated schedule delivery can never start a second execution.
66
+ if (idempotencyKey) {
67
+ const existing = this.repo.findRunByIdempotencyKey(task.taskId, idempotencyKey);
68
+ if (existing) {
69
+ return {
70
+ run: existing,
71
+ steps: this.repo.listSteps(existing.runId),
72
+ deduplicated: true,
73
+ };
74
+ }
75
+ }
76
+ if (task.status === 'archived') {
77
+ throw new TaskEngineError('TASK_PERMISSION_DENIED', '任务已归档,不能执行;请创建新的任务');
78
+ }
79
+ if (task.status === 'paused') {
80
+ throw new TaskEngineError('TASK_PERMISSION_DENIED', '任务处于暂停状态,不会执行;请先用 task_update 将 status 设为 active');
81
+ }
82
+ const activeForTask = this.repo.listActiveRunsByTask(task.taskId);
83
+ if (activeForTask.length >= this.config.maxParallelRunsPerTask) {
84
+ throw new TaskEngineError('TASK_ALREADY_RUNNING', `任务 ${task.taskId} 已有运行 ${activeForTask[0].runId} 处于 ${activeForTask[0].status},暂不能启动新的运行`, { relatedRunId: activeForTask[0].runId });
85
+ }
86
+ const activeForOwner = this.repo.listActiveRunsByOwner(task.ownerSessionId);
87
+ if (activeForOwner.length >= this.config.maxActiveRunsPerOwner) {
88
+ throw new TaskEngineError('TASK_MAX_CONCURRENCY', `当前会话活动运行数已达上限 ${this.config.maxActiveRunsPerOwner},请等待已有运行结束`);
89
+ }
90
+ const stamp = this.now();
91
+ const runId = newRunId();
92
+ const snapshot = {
93
+ revision: task.revision,
94
+ title: task.title,
95
+ steps: task.steps.map((step) => ({ ...step })),
96
+ };
97
+ const status = input.defer ? 'queued' : 'running';
98
+ const run = {
99
+ runId,
100
+ taskId: task.taskId,
101
+ taskRevision: task.revision,
102
+ taskOwnerSessionId: task.ownerSessionId,
103
+ sessionId: input.sessionId,
104
+ status,
105
+ triggerType: input.triggerType ?? (trigger.taskId ? 'schedule' : 'manual'),
106
+ progress: 0,
107
+ requiredTotal: snapshot.steps.filter((step) => step.required).length,
108
+ requiredCompleted: 0,
109
+ totalSteps: snapshot.steps.length,
110
+ startedAt: stamp,
111
+ updatedAt: stamp,
112
+ templateSnapshot: snapshot,
113
+ schemaVersion: SCHEMA_VERSION,
114
+ };
115
+ if (scheduleId)
116
+ run.scheduleId = scheduleId;
117
+ if (occurrenceKey)
118
+ run.occurrenceKey = occurrenceKey;
119
+ if (idempotencyKey)
120
+ run.idempotencyKey = idempotencyKey;
121
+ const first = firstPendingStep(snapshot.steps.map((step) => ({ ...step, status: 'pending' })));
122
+ if (first)
123
+ run.currentStepId = first;
124
+ const steps = this.buildFreshSteps(run, snapshot.steps, stamp);
125
+ // Steps first, then the run: a crash in between leaves no run pointing at
126
+ // half-written progress.
127
+ await this.repo.putSteps(steps);
128
+ const stored = await this.repo.insertRun(run);
129
+ this.audit.record({
130
+ name: 'task.run.started',
131
+ taskId: stored.taskId,
132
+ runId: stored.runId,
133
+ to: stored.status,
134
+ sessionId: input.sessionId,
135
+ source: input.source,
136
+ detail: `trigger=${stored.triggerType}`,
137
+ });
138
+ return { run: stored, steps, deduplicated: false };
139
+ }
140
+ /** Two-phase start: transition an existing `queued` run to `running`. */
141
+ async begin(input) {
142
+ const run = this.repo.requireOwnedRun(input.runId, input.sessionId);
143
+ const steps = this.repo.listSteps(run.runId);
144
+ if (run.status === 'running') {
145
+ return { run, steps, deduplicated: true };
146
+ }
147
+ if (isTerminalRun(run.status)) {
148
+ throw new TaskEngineError('TASK_RUN_ALREADY_FINISHED', `运行 ${run.runId} 已结束(${run.status}),不能再开始;如需继续请 task_resume`);
149
+ }
150
+ assertRunTransition(run.status, 'running', 'task_run_begin');
151
+ const updated = await this.repo.mutateRun(run.runId, (current) => ({
152
+ ...current,
153
+ status: 'running',
154
+ currentStepId: current.currentStepId ?? firstPendingStep(steps),
155
+ }));
156
+ this.audit.record({
157
+ name: 'task.run.started',
158
+ taskId: updated.taskId,
159
+ runId: updated.runId,
160
+ from: run.status,
161
+ to: 'running',
162
+ sessionId: input.sessionId,
163
+ source: input.source,
164
+ });
165
+ return { run: updated, steps, deduplicated: false };
166
+ }
167
+ buildFreshSteps(run, definitions, stamp) {
168
+ return definitions.map((definition) => ({
169
+ runId: run.runId,
170
+ stepId: definition.stepId,
171
+ taskId: run.taskId,
172
+ order: definition.order,
173
+ title: definition.title,
174
+ required: definition.required,
175
+ status: 'pending',
176
+ attempt: 0,
177
+ updatedAt: stamp,
178
+ }));
179
+ }
180
+ // ------------------------------------------------------------ step report
181
+ async reportStep(input) {
182
+ const run = this.repo.requireOwnedRun(input.runId, input.sessionId);
183
+ if (isTerminalRun(run.status)) {
184
+ throw new TaskEngineError('TASK_RUN_ALREADY_FINISHED', `运行 ${run.runId} 已结束(${run.status}),不能继续报告步骤`);
185
+ }
186
+ if (run.status !== 'running') {
187
+ throw new TaskEngineError('TASK_RUN_INTERRUPTED', run.status === 'queued'
188
+ ? `运行 ${run.runId} 尚未开始(queued),请先调用 task_run_begin`
189
+ : `运行 ${run.runId} 处于 ${run.status},不能继续报告步骤;请先 task_run_finish 或 task_resume`);
190
+ }
191
+ const steps = this.repo.listSteps(run.runId);
192
+ const step = steps.find((candidate) => candidate.stepId === input.stepId);
193
+ if (!step) {
194
+ throw new TaskEngineError('TASK_STEP_ORDER_INVALID', `步骤 ${input.stepId} 不属于运行 ${run.runId};只能报告快照内的 stepId`);
195
+ }
196
+ const target = input.action === 'started' ? 'running' : input.action;
197
+ // Retrying `started` is harmless and idempotent; repeating a terminal
198
+ // report is a real ordering error and must be surfaced (PRD 14.2).
199
+ if (input.action === 'started' && step.status === 'running') {
200
+ return { run, step, deduplicated: true };
201
+ }
202
+ const stamp = this.now();
203
+ const summary = truncateText(input.summary?.trim(), this.config.maxSummaryChars);
204
+ const error = input.action === 'failed'
205
+ ? normaliseError(input.error, 'TASK_STEP_FAILED', this.config.maxSummaryChars)
206
+ : undefined;
207
+ if (input.action === 'started') {
208
+ assertLinearStart(steps, input.stepId);
209
+ }
210
+ assertStepTransition(step.status, target, input.stepId);
211
+ const updatedStep = await this.repo.mutateStep(run.runId, input.stepId, (current) => {
212
+ const next = {
213
+ ...current,
214
+ status: target,
215
+ attempt: input.action === 'started' ? current.attempt + 1 : current.attempt,
216
+ updatedAt: stamp,
217
+ };
218
+ if (input.action === 'started') {
219
+ next.startedAt = current.startedAt ?? stamp;
220
+ delete next.finishedAt;
221
+ }
222
+ else {
223
+ next.finishedAt = stamp;
224
+ if (summary)
225
+ next.summary = summary;
226
+ if (error)
227
+ next.error = error;
228
+ }
229
+ return next;
230
+ });
231
+ const refreshed = this.repo.listSteps(run.runId).map((candidate) => candidate.stepId === updatedStep.stepId ? updatedStep : candidate);
232
+ const { progress, requiredTotal, requiredCompleted } = computeProgress(refreshed);
233
+ const updatedRun = await this.repo.mutateRun(run.runId, (current) => {
234
+ const next = {
235
+ ...current,
236
+ progress,
237
+ requiredTotal,
238
+ requiredCompleted,
239
+ currentStepId: firstPendingStep(refreshed),
240
+ };
241
+ if (input.action === 'started')
242
+ next.currentStepId = input.stepId;
243
+ if (input.action === 'failed' && error && !current.error)
244
+ next.error = error;
245
+ if (next.currentStepId === undefined)
246
+ delete next.currentStepId;
247
+ return next;
248
+ });
249
+ this.audit.record({
250
+ name: 'task.step.changed',
251
+ taskId: updatedRun.taskId,
252
+ runId: run.runId,
253
+ stepId: updatedStep.stepId,
254
+ from: step.status,
255
+ to: updatedStep.status,
256
+ sessionId: input.sessionId,
257
+ source: 'task_step_report',
258
+ detail: `progress=${progress}`,
259
+ });
260
+ return { run: updatedRun, step: updatedStep, deduplicated: false };
261
+ }
262
+ // ------------------------------------------------------------- finish run
263
+ async finish(input) {
264
+ const run = this.repo.requireOwnedRun(input.runId, input.sessionId);
265
+ if (isTerminalRun(run.status)) {
266
+ throw new TaskEngineError('TASK_RUN_ALREADY_FINISHED', `运行 ${run.runId} 已结束(${run.status}),不能重复结束`);
267
+ }
268
+ const steps = this.repo.listSteps(run.runId);
269
+ const summary = truncateText(input.summary?.trim(), this.config.maxSummaryChars);
270
+ const error = normaliseError(input.error, input.status === 'succeeded' ? 'TASK_RUN_SUCCEEDED' : 'TASK_RUN_FAILED', this.config.maxSummaryChars);
271
+ if (input.status === 'succeeded') {
272
+ const settled = requiredStepsSettled(steps);
273
+ if (!settled.ok) {
274
+ throw new TaskEngineError('TASK_STEP_ORDER_INVALID', `尚有必需步骤未完成,不能标记 succeeded:${settled.blockers.join('; ')}`);
275
+ }
276
+ }
277
+ if (input.status === 'failed') {
278
+ const failedStep = steps.find((step) => step.status === 'failed');
279
+ if (!failedStep && !error) {
280
+ throw new TaskEngineError('TASK_STEP_ORDER_INVALID', '标记 failed 前必须先 task_step_report(action="failed") 或提供 error 摘要(PRD 9.1 第 7 步)');
281
+ }
282
+ }
283
+ if (input.status === 'blocked' && !summary) {
284
+ throw new TaskEngineError('TASK_INVALID_ARGUMENTS', '标记 blocked 时必须在 summary 中说明缺少什么输入/权限或外部条件');
285
+ }
286
+ assertRunTransition(run.status, input.status, 'task_run_finish');
287
+ const stamp = this.now();
288
+ const { progress, requiredTotal, requiredCompleted } = computeProgress(steps);
289
+ const terminal = input.status !== 'blocked';
290
+ const finishedAt = terminal ? stamp : undefined;
291
+ const updated = await this.repo.mutateRun(run.runId, (current) => {
292
+ const next = {
293
+ ...current,
294
+ status: input.status,
295
+ progress,
296
+ requiredTotal,
297
+ requiredCompleted,
298
+ updatedAt: stamp,
299
+ };
300
+ if (terminal)
301
+ next.finishedAt = stamp;
302
+ if (summary)
303
+ next.summary = summary;
304
+ if (error)
305
+ next.error = error;
306
+ else if (input.status === 'succeeded')
307
+ delete next.error;
308
+ if (terminal)
309
+ delete next.currentStepId;
310
+ return next;
311
+ });
312
+ this.audit.record({
313
+ name: 'task.run.finished',
314
+ taskId: updated.taskId,
315
+ runId: updated.runId,
316
+ from: run.status,
317
+ to: input.status,
318
+ sessionId: input.sessionId,
319
+ source: 'task_run_finish',
320
+ detail: `progress=${progress}${finishedAt ? ` elapsed=${run.startedAt}->${finishedAt}` : ''}`,
321
+ });
322
+ return updated;
323
+ }
324
+ // ---------------------------------------------------------------- resume
325
+ async resume(input) {
326
+ const source = this.repo.requireOwnedRun(input.runId, input.sessionId);
327
+ if (isActiveRun(source.status)) {
328
+ throw new TaskEngineError('TASK_ALREADY_RUNNING', `无法确认运行 ${source.runId} 已终止(当前 ${source.status}),禁止并行启动恢复`, { relatedRunId: source.runId });
329
+ }
330
+ if (!RESUMABLE_RUN_STATUSES.includes(source.status)) {
331
+ throw new TaskEngineError('TASK_RUN_ALREADY_FINISHED', `运行 ${source.runId} 以 ${source.status} 结束,无需恢复;如需重新执行请用 task_run`, { relatedRunId: source.runId });
332
+ }
333
+ const sourceSteps = this.repo.listSteps(source.runId);
334
+ const failedSteps = sourceSteps.filter((step) => step.status === 'failed');
335
+ if (failedSteps.length > 0) {
336
+ const confirmation = input.confirmation?.trim();
337
+ if (!confirmation) {
338
+ throw new TaskEngineError('TASK_PERMISSION_DENIED', `运行 ${source.runId} 在步骤 ${failedSteps.map((step) => step.stepId).join(', ')} 失败,可能已产生外部副作用。` +
339
+ '必须由用户确认后才能恢复:请确认旧执行已终止且重复执行的副作用可接受,然后在 confirmation 中写下该确认', { relatedRunId: source.runId });
340
+ }
341
+ }
342
+ const task = this.repo.requireTask(source.taskId);
343
+ if (task.status === 'archived') {
344
+ throw new TaskEngineError('TASK_PERMISSION_DENIED', '任务已归档,不能恢复运行');
345
+ }
346
+ const activeForTask = this.repo.listActiveRunsByTask(source.taskId);
347
+ if (activeForTask.length >= this.config.maxParallelRunsPerTask) {
348
+ throw new TaskEngineError('TASK_ALREADY_RUNNING', `任务 ${source.taskId} 已有活动运行 ${activeForTask[0].runId},不能同时启动恢复`, { relatedRunId: activeForTask[0].runId });
349
+ }
350
+ const activeForOwner = this.repo.listActiveRunsByOwner(source.taskOwnerSessionId);
351
+ if (activeForOwner.length >= this.config.maxActiveRunsPerOwner) {
352
+ throw new TaskEngineError('TASK_MAX_CONCURRENCY', `当前会话活动运行数已达上限 ${this.config.maxActiveRunsPerOwner}`);
353
+ }
354
+ const stamp = this.now();
355
+ const runId = newRunId();
356
+ const snapshot = {
357
+ revision: source.templateSnapshot.revision,
358
+ title: source.templateSnapshot.title,
359
+ steps: source.templateSnapshot.steps.map((step) => ({ ...step })),
360
+ };
361
+ const carried = sourceSteps
362
+ .slice()
363
+ .sort((a, b) => a.order - b.order)
364
+ .map((step) => {
365
+ const base = {
366
+ runId,
367
+ stepId: step.stepId,
368
+ taskId: source.taskId,
369
+ order: step.order,
370
+ title: step.title,
371
+ required: step.required,
372
+ status: 'pending',
373
+ attempt: 0,
374
+ updatedAt: stamp,
375
+ };
376
+ if (step.status === 'completed' || step.status === 'skipped') {
377
+ base.status = step.status;
378
+ base.carryOverFromRunId = source.runId;
379
+ base.attempt = 1;
380
+ if (step.startedAt)
381
+ base.startedAt = step.startedAt;
382
+ if (step.finishedAt)
383
+ base.finishedAt = step.finishedAt;
384
+ if (step.summary)
385
+ base.summary = step.summary;
386
+ }
387
+ return base;
388
+ });
389
+ const { progress, requiredTotal, requiredCompleted } = computeProgress(carried);
390
+ const run = {
391
+ runId,
392
+ taskId: source.taskId,
393
+ taskRevision: source.taskRevision,
394
+ taskOwnerSessionId: source.taskOwnerSessionId,
395
+ sessionId: input.sessionId,
396
+ status: 'running',
397
+ triggerType: source.triggerType,
398
+ progress,
399
+ requiredTotal,
400
+ requiredCompleted,
401
+ totalSteps: carried.length,
402
+ startedAt: stamp,
403
+ updatedAt: stamp,
404
+ resumesRunId: source.runId,
405
+ templateSnapshot: snapshot,
406
+ schemaVersion: SCHEMA_VERSION,
407
+ };
408
+ if (source.scheduleId)
409
+ run.scheduleId = source.scheduleId;
410
+ const next = firstPendingStep(carried);
411
+ if (next)
412
+ run.currentStepId = next;
413
+ await this.repo.putSteps(carried);
414
+ const stored = await this.repo.insertRun(run);
415
+ this.audit.record({
416
+ name: 'task.run.resumed',
417
+ taskId: stored.taskId,
418
+ runId: stored.runId,
419
+ from: source.runId,
420
+ to: 'running',
421
+ sessionId: input.sessionId,
422
+ source: 'task_resume',
423
+ detail: `carriedCompleted=${requiredCompleted}/${requiredTotal}`,
424
+ });
425
+ return { run: stored, steps: carried, deduplicated: false };
426
+ }
427
+ // --------------------------------------------------------------- history
428
+ history(input) {
429
+ const task = this.repo.requireOwnedTask(input.taskId, input.sessionId);
430
+ const cutoff = daysAgoIso(this.config.historyRetentionDays);
431
+ const runs = this.repo
432
+ .listRunsByTask(task.taskId)
433
+ .filter((run) => run.startedAt >= cutoff)
434
+ .filter((run) => (input.status ? run.status === input.status : true));
435
+ const page = paginate(runs, {
436
+ limit: input.limit ?? 20,
437
+ cursor: decodeCursorSafe(input.cursor),
438
+ tsOf: (run) => run.startedAt,
439
+ idOf: (run) => run.runId,
440
+ });
441
+ const items = page.items.map((run) => this.toHistoryRow(run));
442
+ return page.nextCursor ? { items, nextCursor: page.nextCursor } : { items };
443
+ }
444
+ toHistoryRow(run) {
445
+ const steps = this.repo.listSteps(run.runId);
446
+ const row = {
447
+ runId: run.runId,
448
+ status: run.status,
449
+ triggerType: run.triggerType,
450
+ taskRevision: run.taskRevision,
451
+ progress: run.progress,
452
+ requiredCompleted: run.requiredCompleted,
453
+ requiredTotal: run.requiredTotal,
454
+ startedAt: run.startedAt,
455
+ steps: steps.map((step) => ({ stepId: step.stepId, order: step.order, title: step.title, status: step.status })),
456
+ };
457
+ if (run.finishedAt)
458
+ row.finishedAt = run.finishedAt;
459
+ if (run.currentStepId)
460
+ row.currentStepId = run.currentStepId;
461
+ if (run.resumesRunId)
462
+ row.resumesRunId = run.resumesRunId;
463
+ if (run.summary)
464
+ row.summary = truncateText(run.summary, 300);
465
+ if (run.error)
466
+ row.error = run.error;
467
+ return row;
468
+ }
469
+ // ------------------------------------------------------- startup recovery
470
+ /**
471
+ * Startup scan (PRD FR-007, 14.4): a run that was `queued`/`running` and has
472
+ * not been touched for `staleRunAfterMinutes` cannot be verified, so it is
473
+ * marked `interrupted`. Nothing is restarted automatically.
474
+ */
475
+ async recoverStale() {
476
+ const runs = this.repo.listRuns().filter((run) => ACTIVE_RUN_STATUSES.includes(run.status));
477
+ const interrupted = [];
478
+ const stamp = this.now();
479
+ for (const run of runs) {
480
+ if (!isOlderThanMinutes(run.updatedAt, this.config.staleRunAfterMinutes))
481
+ continue;
482
+ const steps = this.repo.listSteps(run.runId);
483
+ for (const step of steps) {
484
+ if (step.status !== 'running')
485
+ continue;
486
+ await this.repo.mutateStep(run.runId, step.stepId, (current) => {
487
+ const next = {
488
+ ...current,
489
+ status: 'failed',
490
+ finishedAt: stamp,
491
+ error: {
492
+ code: 'TASK_RUN_INTERRUPTED',
493
+ message: '宿主进程重启或执行中断,无法核验该步骤是否产生副作用',
494
+ },
495
+ };
496
+ return next;
497
+ });
498
+ }
499
+ const refreshed = this.repo.listSteps(run.runId).map((step) => ({ ...step }));
500
+ const { progress, requiredTotal, requiredCompleted } = computeProgress(refreshed);
501
+ await this.repo.mutateRun(run.runId, (current) => ({
502
+ ...current,
503
+ status: 'interrupted',
504
+ progress,
505
+ requiredTotal,
506
+ requiredCompleted,
507
+ finishedAt: stamp,
508
+ error: {
509
+ code: 'TASK_RUN_INTERRUPTED',
510
+ message: `运行在 ${run.status} 状态超过 ${this.config.staleRunAfterMinutes} 分钟未更新,已标记 interrupted`,
511
+ },
512
+ currentStepId: undefined,
513
+ }));
514
+ interrupted.push(run.runId);
515
+ this.audit.record({
516
+ name: 'task.run.finished',
517
+ taskId: run.taskId,
518
+ runId: run.runId,
519
+ from: run.status,
520
+ to: 'interrupted',
521
+ sessionId: run.sessionId,
522
+ source: 'startup-recovery',
523
+ });
524
+ }
525
+ return { scanned: runs.length, interrupted };
526
+ }
527
+ // ----------------------------------------------------------------- prune
528
+ /**
529
+ * Retention pruning (PRD 7.4 / FR-010): only terminal runs older than
530
+ * `historyRetentionDays` and their step rows are removed. Templates, audit
531
+ * information and every active run are preserved.
532
+ */
533
+ async prune() {
534
+ const cutoff = daysAgoIso(this.config.historyRetentionDays);
535
+ let runs = 0;
536
+ let steps = 0;
537
+ for (const run of this.repo.listRuns()) {
538
+ if (!isTerminalRun(run.status))
539
+ continue;
540
+ const reference = run.finishedAt ?? run.updatedAt;
541
+ if (reference >= cutoff)
542
+ continue;
543
+ const result = await this.repo.deleteRunCascade(run.runId);
544
+ if (result.runDeleted)
545
+ runs += 1;
546
+ steps += result.stepsDeleted;
547
+ }
548
+ return { runs, steps };
549
+ }
550
+ // --------------------------------------------------------------- helpers
551
+ /** Persisted step rows of one run, ordered. */
552
+ stepsOf(runId) {
553
+ return this.repo.listSteps(runId);
554
+ }
555
+ countActiveRuns(ownerSessionId) {
556
+ return this.repo.listActiveRunsByOwner(ownerSessionId).length;
557
+ }
558
+ }
559
+ function decodeCursorSafe(cursor) {
560
+ if (!cursor)
561
+ return undefined;
562
+ try {
563
+ return JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
564
+ }
565
+ catch {
566
+ return undefined;
567
+ }
568
+ }
569
+ export const RUN_HISTORY_ORDER = compareDesc;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * DSH Schedule adapter (PRD 4.5, 8.3, FR-002, FR-008; acceptance 14.3).
3
+ *
4
+ * The plugin never implements its own scheduler: occurrences, catch-up and
5
+ * delivery are owned by `ctx.schedule`. This adapter only
6
+ * - translates the plugin's timing input into a documented host timing,
7
+ * - stores the returned scheduleId on the task (`scheduleRef`),
8
+ * - maps host failures onto TASK_SCHEDULE_* codes so a failed rule update is
9
+ * never reported as success.
10
+ *
11
+ * When `ctx.schedule` is not mounted every method throws
12
+ * TASK_SCHEDULE_UNAVAILABLE and manual task execution keeps working
13
+ * (PRD FR-012).
14
+ */
15
+ import type { ScheduleRecordLike, ScheduleServiceLike } from '../host.js';
16
+ export type TimingInput = {
17
+ kind: 'at';
18
+ at: string;
19
+ } | {
20
+ kind: 'every';
21
+ everySeconds: number;
22
+ } | {
23
+ kind: 'rrule';
24
+ rrule: string;
25
+ } | {
26
+ kind: 'cron';
27
+ expression: string;
28
+ timeZone?: string;
29
+ } | {
30
+ kind: 'daily';
31
+ hour: number;
32
+ minute: number;
33
+ timeZone?: string;
34
+ } | {
35
+ kind: 'weekly';
36
+ dayOfWeek: number;
37
+ hour: number;
38
+ minute: number;
39
+ timeZone?: string;
40
+ };
41
+ export interface HostTiming {
42
+ kind: string;
43
+ [key: string]: unknown;
44
+ }
45
+ /**
46
+ * Translate validated timing input into the host's documented timing shapes.
47
+ * Only `at`, `every`, `rrule` and `cron` are passed through; daily/weekly are
48
+ * expressed as an equivalent RRULE so the plugin depends on one less host shape.
49
+ */
50
+ export declare function toHostTiming(input: TimingInput): HostTiming;
51
+ export declare function describeTiming(timing: TimingInput | HostTiming): string;
52
+ export interface CreateScheduleResult {
53
+ scheduleId: string;
54
+ entry: ScheduleRecordLike;
55
+ }
56
+ export declare class ScheduleAdapter {
57
+ private readonly schedule;
58
+ private readonly log?;
59
+ constructor(schedule: ScheduleServiceLike | undefined, log?: {
60
+ warn(...args: unknown[]): void;
61
+ } | undefined);
62
+ get available(): boolean;
63
+ private require;
64
+ create(input: {
65
+ taskId: string;
66
+ taskTitle: string;
67
+ timing: TimingInput;
68
+ sessionId: string;
69
+ }): Promise<CreateScheduleResult>;
70
+ update(input: {
71
+ scheduleId: string;
72
+ patch: {
73
+ timing?: TimingInput;
74
+ title?: string;
75
+ prompt?: string;
76
+ active?: boolean;
77
+ };
78
+ sessionId: string;
79
+ }): Promise<ScheduleRecordLike>;
80
+ remove(scheduleId: string, sessionId: string): Promise<{
81
+ deleted: boolean;
82
+ alreadyGone: boolean;
83
+ }>;
84
+ view(scheduleId: string): Promise<ScheduleRecordLike | undefined>;
85
+ runNow(scheduleId: string): Promise<{
86
+ pending: boolean;
87
+ entry?: ScheduleRecordLike;
88
+ }>;
89
+ private wrap;
90
+ }
91
+ /** Loose staleness helper used by diagnostics (kept here to avoid cycles). */
92
+ export declare function scheduleLooksStale(scheduledAt: string | undefined, minutes: number): boolean;