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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/LICENSE +21 -0
  3. package/README.md +255 -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 +200 -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,435 @@
1
+ /**
2
+ * TaskEngine: composition root for the plugin (PRD 8.2, 8.4, FR-012).
3
+ *
4
+ * Startup sequence (all failures are explicit, never silent):
5
+ * 1. open the StorageDomain declared in src/storage/spec.ts
6
+ * 2. run idempotent migrations from the persisted ledger
7
+ * 3. verify record integrity (runs reference tasks, steps belong to runs)
8
+ * 4. recover stale `queued`/`running` rows into `interrupted`
9
+ * 5. prune terminal runs older than `historyRetentionDays`
10
+ *
11
+ * If step 1 fails the `ready` promise rejects and every tool returns
12
+ * TASK_STORAGE_ERROR — the plugin does not fall back to in-memory storage
13
+ * (PRD 16.3).
14
+ */
15
+ import { type HostContextLike } from '../host.js';
16
+ import type { EngineConfig } from '../config.js';
17
+ import { type MigrationReport, type IntegrityReport } from '../storage/spec.js';
18
+ import { ScheduleAdapter } from './schedule-adapter.js';
19
+ import { TaskService } from './task-service.js';
20
+ import { RunService } from './run-service.js';
21
+ export interface EngineDiagnostics {
22
+ storageAvailable: boolean;
23
+ scheduleAvailable: boolean;
24
+ activeRunCount: number;
25
+ schemaVersion: number;
26
+ taskCount: number;
27
+ runCount: number;
28
+ lastRecoveryScanAt?: string;
29
+ lastPruneAt?: string;
30
+ staleRunsInterrupted: number;
31
+ integrity: IntegrityReport | null;
32
+ migrations: MigrationReport | null;
33
+ lastError?: string;
34
+ }
35
+ export declare class TaskEngine {
36
+ private readonly ctx;
37
+ private readonly now;
38
+ readonly config: EngineConfig;
39
+ readonly ready: Promise<void>;
40
+ private domain?;
41
+ private repo?;
42
+ private audit?;
43
+ private schedules?;
44
+ private tasks?;
45
+ private runs?;
46
+ private initError?;
47
+ private disposed;
48
+ private readonly diagnostics;
49
+ constructor(ctx: HostContextLike, config: EngineConfig, now?: () => string);
50
+ private init;
51
+ /** Wait for startup to finish; throws a TaskEngineError when storage is unavailable. */
52
+ waitReady(): Promise<void>;
53
+ get taskService(): TaskService;
54
+ get runService(): RunService;
55
+ /** TaskService may be used for schedule-only operations; storage must be ready. */
56
+ get scheduleAdapter(): ScheduleAdapter;
57
+ diagnosticsFor(sessionId: string): Promise<EngineDiagnostics>;
58
+ /** Release the domain handle. User data is never deleted. */
59
+ dispose(): Promise<void>;
60
+ }
61
+ /** Domain record schemas, re-exported for diagnostics and tests. */
62
+ export declare const domainSchemas: {
63
+ tasks: import("zod").ZodObject<{
64
+ taskId: import("zod").ZodString;
65
+ title: import("zod").ZodString;
66
+ description: import("zod").ZodOptional<import("zod").ZodString>;
67
+ status: import("zod").ZodEnum<["active", "paused", "archived"]>;
68
+ revision: import("zod").ZodNumber;
69
+ ownerSessionId: import("zod").ZodString;
70
+ steps: import("zod").ZodArray<import("zod").ZodObject<{
71
+ stepId: import("zod").ZodString;
72
+ title: import("zod").ZodString;
73
+ instruction: import("zod").ZodString;
74
+ completionCriteria: import("zod").ZodOptional<import("zod").ZodString>;
75
+ order: import("zod").ZodNumber;
76
+ required: import("zod").ZodBoolean;
77
+ }, "strip", import("zod").ZodTypeAny, {
78
+ title: string;
79
+ stepId: string;
80
+ instruction: string;
81
+ order: number;
82
+ required: boolean;
83
+ completionCriteria?: string | undefined;
84
+ }, {
85
+ title: string;
86
+ stepId: string;
87
+ instruction: string;
88
+ order: number;
89
+ required: boolean;
90
+ completionCriteria?: string | undefined;
91
+ }>, "many">;
92
+ scheduleRef: import("zod").ZodOptional<import("zod").ZodObject<{
93
+ scheduleId: import("zod").ZodString;
94
+ timingKind: import("zod").ZodString;
95
+ timing: import("zod").ZodRecord<import("zod").ZodString, import("zod").ZodUnknown>;
96
+ state: import("zod").ZodEnum<["active", "paused", "unlinked"]>;
97
+ title: import("zod").ZodString;
98
+ createdAt: import("zod").ZodString;
99
+ updatedAt: import("zod").ZodString;
100
+ lastError: import("zod").ZodOptional<import("zod").ZodObject<{
101
+ code: import("zod").ZodString;
102
+ message: import("zod").ZodString;
103
+ }, "strip", import("zod").ZodTypeAny, {
104
+ code: string;
105
+ message: string;
106
+ }, {
107
+ code: string;
108
+ message: string;
109
+ }>>;
110
+ }, "strip", import("zod").ZodTypeAny, {
111
+ title: string;
112
+ createdAt: string;
113
+ updatedAt: string;
114
+ scheduleId: string;
115
+ timingKind: string;
116
+ timing: Record<string, unknown>;
117
+ state: "active" | "paused" | "unlinked";
118
+ lastError?: {
119
+ code: string;
120
+ message: string;
121
+ } | undefined;
122
+ }, {
123
+ title: string;
124
+ createdAt: string;
125
+ updatedAt: string;
126
+ scheduleId: string;
127
+ timingKind: string;
128
+ timing: Record<string, unknown>;
129
+ state: "active" | "paused" | "unlinked";
130
+ lastError?: {
131
+ code: string;
132
+ message: string;
133
+ } | undefined;
134
+ }>>;
135
+ createdAt: import("zod").ZodString;
136
+ updatedAt: import("zod").ZodString;
137
+ schemaVersion: import("zod").ZodNumber;
138
+ }, "strip", import("zod").ZodTypeAny, {
139
+ title: string;
140
+ status: "active" | "paused" | "archived";
141
+ createdAt: string;
142
+ updatedAt: string;
143
+ taskId: string;
144
+ revision: number;
145
+ ownerSessionId: string;
146
+ steps: {
147
+ title: string;
148
+ stepId: string;
149
+ instruction: string;
150
+ order: number;
151
+ required: boolean;
152
+ completionCriteria?: string | undefined;
153
+ }[];
154
+ schemaVersion: number;
155
+ description?: string | undefined;
156
+ scheduleRef?: {
157
+ title: string;
158
+ createdAt: string;
159
+ updatedAt: string;
160
+ scheduleId: string;
161
+ timingKind: string;
162
+ timing: Record<string, unknown>;
163
+ state: "active" | "paused" | "unlinked";
164
+ lastError?: {
165
+ code: string;
166
+ message: string;
167
+ } | undefined;
168
+ } | undefined;
169
+ }, {
170
+ title: string;
171
+ status: "active" | "paused" | "archived";
172
+ createdAt: string;
173
+ updatedAt: string;
174
+ taskId: string;
175
+ revision: number;
176
+ ownerSessionId: string;
177
+ steps: {
178
+ title: string;
179
+ stepId: string;
180
+ instruction: string;
181
+ order: number;
182
+ required: boolean;
183
+ completionCriteria?: string | undefined;
184
+ }[];
185
+ schemaVersion: number;
186
+ description?: string | undefined;
187
+ scheduleRef?: {
188
+ title: string;
189
+ createdAt: string;
190
+ updatedAt: string;
191
+ scheduleId: string;
192
+ timingKind: string;
193
+ timing: Record<string, unknown>;
194
+ state: "active" | "paused" | "unlinked";
195
+ lastError?: {
196
+ code: string;
197
+ message: string;
198
+ } | undefined;
199
+ } | undefined;
200
+ }>;
201
+ runs: import("zod").ZodObject<{
202
+ runId: import("zod").ZodString;
203
+ taskId: import("zod").ZodString;
204
+ taskRevision: import("zod").ZodNumber;
205
+ taskOwnerSessionId: import("zod").ZodString;
206
+ sessionId: import("zod").ZodString;
207
+ status: import("zod").ZodEnum<["queued", "running", "blocked", "succeeded", "failed", "interrupted", "skipped"]>;
208
+ triggerType: import("zod").ZodEnum<["manual", "schedule"]>;
209
+ scheduleId: import("zod").ZodOptional<import("zod").ZodString>;
210
+ occurrenceKey: import("zod").ZodOptional<import("zod").ZodString>;
211
+ idempotencyKey: import("zod").ZodOptional<import("zod").ZodString>;
212
+ currentStepId: import("zod").ZodOptional<import("zod").ZodString>;
213
+ progress: import("zod").ZodNumber;
214
+ requiredTotal: import("zod").ZodNumber;
215
+ requiredCompleted: import("zod").ZodNumber;
216
+ totalSteps: import("zod").ZodNumber;
217
+ startedAt: import("zod").ZodString;
218
+ updatedAt: import("zod").ZodString;
219
+ finishedAt: import("zod").ZodOptional<import("zod").ZodString>;
220
+ summary: import("zod").ZodOptional<import("zod").ZodString>;
221
+ error: import("zod").ZodOptional<import("zod").ZodObject<{
222
+ code: import("zod").ZodString;
223
+ message: import("zod").ZodString;
224
+ }, "strip", import("zod").ZodTypeAny, {
225
+ code: string;
226
+ message: string;
227
+ }, {
228
+ code: string;
229
+ message: string;
230
+ }>>;
231
+ resumesRunId: import("zod").ZodOptional<import("zod").ZodString>;
232
+ templateSnapshot: import("zod").ZodObject<{
233
+ revision: import("zod").ZodNumber;
234
+ title: import("zod").ZodString;
235
+ steps: import("zod").ZodArray<import("zod").ZodObject<{
236
+ stepId: import("zod").ZodString;
237
+ title: import("zod").ZodString;
238
+ instruction: import("zod").ZodString;
239
+ completionCriteria: import("zod").ZodOptional<import("zod").ZodString>;
240
+ order: import("zod").ZodNumber;
241
+ required: import("zod").ZodBoolean;
242
+ }, "strip", import("zod").ZodTypeAny, {
243
+ title: string;
244
+ stepId: string;
245
+ instruction: string;
246
+ order: number;
247
+ required: boolean;
248
+ completionCriteria?: string | undefined;
249
+ }, {
250
+ title: string;
251
+ stepId: string;
252
+ instruction: string;
253
+ order: number;
254
+ required: boolean;
255
+ completionCriteria?: string | undefined;
256
+ }>, "many">;
257
+ }, "strip", import("zod").ZodTypeAny, {
258
+ title: string;
259
+ revision: number;
260
+ steps: {
261
+ title: string;
262
+ stepId: string;
263
+ instruction: string;
264
+ order: number;
265
+ required: boolean;
266
+ completionCriteria?: string | undefined;
267
+ }[];
268
+ }, {
269
+ title: string;
270
+ revision: number;
271
+ steps: {
272
+ title: string;
273
+ stepId: string;
274
+ instruction: string;
275
+ order: number;
276
+ required: boolean;
277
+ completionCriteria?: string | undefined;
278
+ }[];
279
+ }>;
280
+ schemaVersion: import("zod").ZodNumber;
281
+ }, "strip", import("zod").ZodTypeAny, {
282
+ status: "queued" | "running" | "blocked" | "succeeded" | "failed" | "interrupted" | "skipped";
283
+ updatedAt: string;
284
+ taskId: string;
285
+ schemaVersion: number;
286
+ runId: string;
287
+ taskRevision: number;
288
+ taskOwnerSessionId: string;
289
+ sessionId: string;
290
+ triggerType: "manual" | "schedule";
291
+ progress: number;
292
+ requiredTotal: number;
293
+ requiredCompleted: number;
294
+ totalSteps: number;
295
+ startedAt: string;
296
+ templateSnapshot: {
297
+ title: string;
298
+ revision: number;
299
+ steps: {
300
+ title: string;
301
+ stepId: string;
302
+ instruction: string;
303
+ order: number;
304
+ required: boolean;
305
+ completionCriteria?: string | undefined;
306
+ }[];
307
+ };
308
+ scheduleId?: string | undefined;
309
+ occurrenceKey?: string | undefined;
310
+ idempotencyKey?: string | undefined;
311
+ currentStepId?: string | undefined;
312
+ finishedAt?: string | undefined;
313
+ summary?: string | undefined;
314
+ error?: {
315
+ code: string;
316
+ message: string;
317
+ } | undefined;
318
+ resumesRunId?: string | undefined;
319
+ }, {
320
+ status: "queued" | "running" | "blocked" | "succeeded" | "failed" | "interrupted" | "skipped";
321
+ updatedAt: string;
322
+ taskId: string;
323
+ schemaVersion: number;
324
+ runId: string;
325
+ taskRevision: number;
326
+ taskOwnerSessionId: string;
327
+ sessionId: string;
328
+ triggerType: "manual" | "schedule";
329
+ progress: number;
330
+ requiredTotal: number;
331
+ requiredCompleted: number;
332
+ totalSteps: number;
333
+ startedAt: string;
334
+ templateSnapshot: {
335
+ title: string;
336
+ revision: number;
337
+ steps: {
338
+ title: string;
339
+ stepId: string;
340
+ instruction: string;
341
+ order: number;
342
+ required: boolean;
343
+ completionCriteria?: string | undefined;
344
+ }[];
345
+ };
346
+ scheduleId?: string | undefined;
347
+ occurrenceKey?: string | undefined;
348
+ idempotencyKey?: string | undefined;
349
+ currentStepId?: string | undefined;
350
+ finishedAt?: string | undefined;
351
+ summary?: string | undefined;
352
+ error?: {
353
+ code: string;
354
+ message: string;
355
+ } | undefined;
356
+ resumesRunId?: string | undefined;
357
+ }>;
358
+ steps: import("zod").ZodObject<{
359
+ runId: import("zod").ZodString;
360
+ stepId: import("zod").ZodString;
361
+ taskId: import("zod").ZodString;
362
+ order: import("zod").ZodNumber;
363
+ title: import("zod").ZodString;
364
+ required: import("zod").ZodBoolean;
365
+ status: import("zod").ZodEnum<["pending", "running", "completed", "failed", "skipped"]>;
366
+ attempt: import("zod").ZodNumber;
367
+ startedAt: import("zod").ZodOptional<import("zod").ZodString>;
368
+ finishedAt: import("zod").ZodOptional<import("zod").ZodString>;
369
+ summary: import("zod").ZodOptional<import("zod").ZodString>;
370
+ error: import("zod").ZodOptional<import("zod").ZodObject<{
371
+ code: import("zod").ZodString;
372
+ message: import("zod").ZodString;
373
+ }, "strip", import("zod").ZodTypeAny, {
374
+ code: string;
375
+ message: string;
376
+ }, {
377
+ code: string;
378
+ message: string;
379
+ }>>;
380
+ carryOverFromRunId: import("zod").ZodOptional<import("zod").ZodString>;
381
+ updatedAt: import("zod").ZodString;
382
+ }, "strip", import("zod").ZodTypeAny, {
383
+ title: string;
384
+ status: "running" | "failed" | "skipped" | "pending" | "completed";
385
+ updatedAt: string;
386
+ stepId: string;
387
+ order: number;
388
+ required: boolean;
389
+ taskId: string;
390
+ runId: string;
391
+ attempt: number;
392
+ startedAt?: string | undefined;
393
+ finishedAt?: string | undefined;
394
+ summary?: string | undefined;
395
+ error?: {
396
+ code: string;
397
+ message: string;
398
+ } | undefined;
399
+ carryOverFromRunId?: string | undefined;
400
+ }, {
401
+ title: string;
402
+ status: "running" | "failed" | "skipped" | "pending" | "completed";
403
+ updatedAt: string;
404
+ stepId: string;
405
+ order: number;
406
+ required: boolean;
407
+ taskId: string;
408
+ runId: string;
409
+ attempt: number;
410
+ startedAt?: string | undefined;
411
+ finishedAt?: string | undefined;
412
+ summary?: string | undefined;
413
+ error?: {
414
+ code: string;
415
+ message: string;
416
+ } | undefined;
417
+ carryOverFromRunId?: string | undefined;
418
+ }>;
419
+ meta: import("zod").ZodObject<{
420
+ schemaVersion: import("zod").ZodNumber;
421
+ appliedMigrations: import("zod").ZodRecord<import("zod").ZodString, import("zod").ZodString>;
422
+ lastRecoveryScanAt: import("zod").ZodOptional<import("zod").ZodString>;
423
+ lastPruneAt: import("zod").ZodOptional<import("zod").ZodString>;
424
+ }, "strip", import("zod").ZodTypeAny, {
425
+ schemaVersion: number;
426
+ appliedMigrations: Record<string, string>;
427
+ lastRecoveryScanAt?: string | undefined;
428
+ lastPruneAt?: string | undefined;
429
+ }, {
430
+ schemaVersion: number;
431
+ appliedMigrations: Record<string, string>;
432
+ lastRecoveryScanAt?: string | undefined;
433
+ lastPruneAt?: string | undefined;
434
+ }>;
435
+ };
@@ -0,0 +1,150 @@
1
+ /**
2
+ * TaskEngine: composition root for the plugin (PRD 8.2, 8.4, FR-012).
3
+ *
4
+ * Startup sequence (all failures are explicit, never silent):
5
+ * 1. open the StorageDomain declared in src/storage/spec.ts
6
+ * 2. run idempotent migrations from the persisted ledger
7
+ * 3. verify record integrity (runs reference tasks, steps belong to runs)
8
+ * 4. recover stale `queued`/`running` rows into `interrupted`
9
+ * 5. prune terminal runs older than `historyRetentionDays`
10
+ *
11
+ * If step 1 fails the `ready` promise rejects and every tool returns
12
+ * TASK_STORAGE_ERROR — the plugin does not fall back to in-memory storage
13
+ * (PRD 16.3).
14
+ */
15
+ import { optionalService } from '../host.js';
16
+ import { TaskEngineError } from '../errors.js';
17
+ import { SCHEMA_VERSION, globalStateSchema, runRecordSchema, runStepRecordSchema, taskRecordSchema } from '../domain/records.js';
18
+ import { Repository } from '../storage/repository.js';
19
+ import { MIGRATIONS, UNIT_NAME_PATTERN, createDomainSpec, runMigrations, verifyIntegrity, } from '../storage/spec.js';
20
+ import { AuditTrail } from './audit.js';
21
+ import { ScheduleAdapter } from './schedule-adapter.js';
22
+ import { TaskService } from './task-service.js';
23
+ import { RunService } from './run-service.js';
24
+ import { nowIso } from '../utils/time.js';
25
+ export class TaskEngine {
26
+ ctx;
27
+ now;
28
+ config;
29
+ ready;
30
+ domain;
31
+ repo;
32
+ audit;
33
+ schedules;
34
+ tasks;
35
+ runs;
36
+ initError;
37
+ disposed = false;
38
+ diagnostics = {
39
+ storageAvailable: false,
40
+ scheduleAvailable: false,
41
+ activeRunCount: 0,
42
+ schemaVersion: SCHEMA_VERSION,
43
+ taskCount: 0,
44
+ runCount: 0,
45
+ staleRunsInterrupted: 0,
46
+ integrity: null,
47
+ migrations: null,
48
+ };
49
+ constructor(ctx, config, now = nowIso) {
50
+ this.ctx = ctx;
51
+ this.now = now;
52
+ this.config = config;
53
+ const schedule = optionalService(ctx, 'schedule');
54
+ this.schedules = new ScheduleAdapter(schedule, { warn: (...args) => ctx.logger?.warn?.(...args) });
55
+ this.diagnostics.scheduleAvailable = this.schedules.available;
56
+ this.ready = this.init();
57
+ }
58
+ async init() {
59
+ const facility = this.ctx.storageDomain;
60
+ if (!facility || typeof facility.open !== 'function') {
61
+ throw new TaskEngineError('TASK_STORAGE_ERROR', '未挂载 ctx.storageDomain:dsh-background-task-engine 拒绝启动,也不会降级为内存存储。请确认宿主已启用 StorageDomain(base bundle 配置 storage-domain backend=json)。');
62
+ }
63
+ try {
64
+ const spec = createDomainSpec();
65
+ // Fail loudly before touching the backend if the declaration itself is
66
+ // invalid for this host version (cheap, and names the exact field).
67
+ for (const unitName of [spec.name, ...Object.keys(spec.tables)]) {
68
+ if (!UNIT_NAME_PATTERN.test(unitName)) {
69
+ throw new TaskEngineError('TASK_STORAGE_ERROR', `存储单元名 ${unitName} 不合法:宿主要求 /^[a-z][a-z0-9_]*$/(不允许连字符)`);
70
+ }
71
+ }
72
+ const domain = await facility.open(spec);
73
+ this.domain = domain;
74
+ this.repo = new Repository(domain, this.now);
75
+ this.audit = new AuditTrail(this.ctx, this.ctx.logger);
76
+ this.tasks = new TaskService(this.repo, this.config, this.audit, this.schedules, this.now);
77
+ this.runs = new RunService(this.repo, this.config, this.audit, this.now);
78
+ this.diagnostics.migrations = await runMigrations(domain, MIGRATIONS, this.now);
79
+ this.diagnostics.integrity = verifyIntegrity(domain);
80
+ this.diagnostics.storageAvailable = true;
81
+ this.diagnostics.taskCount = this.repo.listTasks().length;
82
+ this.diagnostics.runCount = this.repo.listRuns().length;
83
+ const recovery = await this.runs.recoverStale();
84
+ this.diagnostics.lastRecoveryScanAt = this.now();
85
+ this.diagnostics.staleRunsInterrupted = recovery.interrupted.length;
86
+ this.ctx.logger?.info?.(`[background-task-engine] startup scan: stale runs=${recovery.scanned} interrupted=${recovery.interrupted.length}`);
87
+ const pruned = await this.runs.prune();
88
+ this.diagnostics.lastPruneAt = this.now();
89
+ if (pruned.runs > 0 || pruned.steps > 0) {
90
+ this.ctx.logger?.info?.(`[background-task-engine] prune removed ${pruned.runs} runs / ${pruned.steps} step records`);
91
+ }
92
+ this.diagnostics.activeRunCount = this.repo.listActiveRunsByOwner('').length;
93
+ }
94
+ catch (error) {
95
+ const taskError = error instanceof TaskEngineError ? error : new TaskEngineError('TASK_STORAGE_ERROR', `存储初始化失败:${error instanceof Error ? error.message : String(error)}`);
96
+ this.initError = taskError;
97
+ this.diagnostics.lastError = taskError.message;
98
+ throw taskError;
99
+ }
100
+ }
101
+ /** Wait for startup to finish; throws a TaskEngineError when storage is unavailable. */
102
+ async waitReady() {
103
+ await this.ready;
104
+ }
105
+ get taskService() {
106
+ if (!this.tasks) {
107
+ throw new TaskEngineError('TASK_STORAGE_ERROR', '插件尚未完成存储初始化,无法执行任务操作');
108
+ }
109
+ return this.tasks;
110
+ }
111
+ get runService() {
112
+ if (!this.runs) {
113
+ throw new TaskEngineError('TASK_STORAGE_ERROR', '插件尚未完成存储初始化,无法执行运行操作');
114
+ }
115
+ return this.runs;
116
+ }
117
+ /** TaskService may be used for schedule-only operations; storage must be ready. */
118
+ get scheduleAdapter() {
119
+ if (!this.schedules)
120
+ throw new TaskEngineError('TASK_STORAGE_ERROR', '插件尚未初始化');
121
+ return this.schedules;
122
+ }
123
+ async diagnosticsFor(sessionId) {
124
+ const current = {
125
+ ...this.diagnostics,
126
+ activeRunCount: this.repo ? this.repo.listActiveRunsByOwner(sessionId).length : 0,
127
+ };
128
+ return current;
129
+ }
130
+ /** Release the domain handle. User data is never deleted. */
131
+ async dispose() {
132
+ if (this.disposed)
133
+ return;
134
+ this.disposed = true;
135
+ try {
136
+ await this.domain?.close();
137
+ }
138
+ catch (error) {
139
+ this.ctx.logger?.warn?.(`[background-task-engine] 关闭 StorageDomain 失败:${String(error)}`);
140
+ }
141
+ this.ctx.logger?.info?.('[background-task-engine] disposed (user data preserved)');
142
+ }
143
+ }
144
+ /** Domain record schemas, re-exported for diagnostics and tests. */
145
+ export const domainSchemas = {
146
+ tasks: taskRecordSchema,
147
+ runs: runRecordSchema,
148
+ steps: runStepRecordSchema,
149
+ meta: globalStateSchema,
150
+ };