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,490 @@
1
+ /**
2
+ * Task template service: create / list / get / update / archive and the
3
+ * Schedule linkage (PRD 4.2, 5.1, FR-001, FR-002, FR-003).
4
+ *
5
+ * All persistence goes through Repository; all state changes are audited; every
6
+ * entry point takes the caller SessionId and verifies ownership first.
7
+ */
8
+ import { z } from 'zod';
9
+ import { TaskEngineError } from '../errors.js';
10
+ import { SCHEMA_VERSION, } from '../domain/records.js';
11
+ import { newStepId, newTaskId } from '../utils/id.js';
12
+ import { nowIso } from '../utils/time.js';
13
+ import { truncateText } from '../utils/text.js';
14
+ import { compareDesc, paginate } from '../utils/page.js';
15
+ import { describeTiming, toHostTiming } from './schedule-adapter.js';
16
+ const stepInputSchema = z.object({
17
+ title: z.string().trim().min(1, '步骤标题不能为空').max(120),
18
+ instruction: z.string().trim().min(1, '步骤 instruction 不能为空').max(8000),
19
+ completionCriteria: z.string().trim().max(2000).optional(),
20
+ required: z.boolean().optional(),
21
+ });
22
+ export class TaskService {
23
+ repo;
24
+ config;
25
+ audit;
26
+ schedules;
27
+ now;
28
+ constructor(repo, config, audit, schedules, now = nowIso) {
29
+ this.repo = repo;
30
+ this.config = config;
31
+ this.audit = audit;
32
+ this.schedules = schedules;
33
+ this.now = now;
34
+ }
35
+ // ---------------------------------------------------------------- create
36
+ async create(input) {
37
+ const owner = input.sessionId;
38
+ let source;
39
+ if (input.copyFromTaskId) {
40
+ source = this.repo.requireOwnedTask(input.copyFromTaskId, owner);
41
+ }
42
+ const rawSteps = input.steps && input.steps.length > 0 ? input.steps : source?.steps;
43
+ if (!rawSteps || rawSteps.length === 0) {
44
+ throw new TaskEngineError('TASK_INVALID_STEPS', '任务至少需要 1 个步骤');
45
+ }
46
+ const steps = this.normaliseSteps(rawSteps);
47
+ const title = (input.title ?? (source ? `${source.title} (副本)` : '')).trim();
48
+ if (title.length < 2 || title.length > 80) {
49
+ throw new TaskEngineError('TASK_INVALID_ARGUMENTS', '任务标题长度必须为 2–80 个字符');
50
+ }
51
+ const description = truncateText((input.description ?? source?.description ?? '').trim(), 2000) || undefined;
52
+ const existing = this.repo.countUnarchivedTasks(owner);
53
+ if (existing >= this.config.maxTasksPerOwner) {
54
+ throw new TaskEngineError('TASK_PERMISSION_DENIED', `当前会话可保留的未归档任务已达上限 ${this.config.maxTasksPerOwner},请先归档不再使用的任务`);
55
+ }
56
+ const stamp = this.now();
57
+ const record = {
58
+ taskId: newTaskId(),
59
+ title,
60
+ status: 'active',
61
+ revision: 1,
62
+ ownerSessionId: owner,
63
+ steps,
64
+ createdAt: stamp,
65
+ updatedAt: stamp,
66
+ schemaVersion: SCHEMA_VERSION,
67
+ };
68
+ if (description)
69
+ record.description = description;
70
+ const stored = await this.repo.insertTask(record);
71
+ this.audit.record({
72
+ name: 'task.created',
73
+ taskId: stored.taskId,
74
+ to: stored.status,
75
+ sessionId: owner,
76
+ source: source ? `copy:${source.taskId}` : 'task_create',
77
+ detail: `steps=${stored.steps.length}`,
78
+ });
79
+ return stored;
80
+ }
81
+ normaliseSteps(rawSteps) {
82
+ if (!Array.isArray(rawSteps)) {
83
+ throw new TaskEngineError('TASK_INVALID_STEPS', 'steps 必须是数组');
84
+ }
85
+ if (rawSteps.length > this.config.maxStepsPerTask) {
86
+ throw new TaskEngineError('TASK_INVALID_STEPS', `步骤数量 ${rawSteps.length} 超过上限 ${this.config.maxStepsPerTask}(V1.0 为线性任务,最多 10 步)`);
87
+ }
88
+ const parsed = [];
89
+ for (const [index, candidate] of rawSteps.entries()) {
90
+ const result = stepInputSchema.safeParse(candidate);
91
+ if (!result.success) {
92
+ const issue = result.error.issues[0];
93
+ throw new TaskEngineError('TASK_INVALID_STEPS', `第 ${index + 1} 个步骤无效:${issue?.path.join('.') || 'step'} ${issue?.message ?? ''}`.trim());
94
+ }
95
+ parsed.push(result.data);
96
+ }
97
+ const seen = new Set();
98
+ const steps = parsed.map((step, index) => {
99
+ let stepId = newStepId();
100
+ while (seen.has(stepId))
101
+ stepId = newStepId();
102
+ seen.add(stepId);
103
+ const definition = {
104
+ stepId,
105
+ title: step.title,
106
+ instruction: step.instruction,
107
+ order: index + 1,
108
+ required: step.required !== false,
109
+ };
110
+ if (step.completionCriteria)
111
+ definition.completionCriteria = step.completionCriteria;
112
+ return definition;
113
+ });
114
+ if (steps.length === 0) {
115
+ throw new TaskEngineError('TASK_INVALID_STEPS', '任务至少需要 1 个步骤');
116
+ }
117
+ return steps;
118
+ }
119
+ // ------------------------------------------------------------------ list
120
+ list(input) {
121
+ const owner = input.sessionId;
122
+ const query = input.query?.trim().toLowerCase();
123
+ const runs = this.repo.listRuns();
124
+ const lastRunByTask = new Map();
125
+ for (const run of runs) {
126
+ if (run.taskOwnerSessionId !== owner)
127
+ continue;
128
+ const current = lastRunByTask.get(run.taskId);
129
+ if (!current || run.startedAt > current.startedAt)
130
+ lastRunByTask.set(run.taskId, run);
131
+ }
132
+ const filtered = this.repo
133
+ .listTasksByOwner(owner)
134
+ .filter((task) => (input.status ? task.status === input.status : true))
135
+ .filter((task) => {
136
+ if (!query)
137
+ return true;
138
+ return (task.title.toLowerCase().includes(query) ||
139
+ (task.description ?? '').toLowerCase().includes(query) ||
140
+ task.taskId === input.query?.trim());
141
+ })
142
+ .sort((a, b) => compareDesc(a.updatedAt, a.taskId, b.updatedAt, b.taskId));
143
+ const page = paginate(filtered, {
144
+ limit: input.limit ?? 20,
145
+ cursor: decodeCursorSafe(input.cursor),
146
+ tsOf: (task) => task.updatedAt,
147
+ idOf: (task) => task.taskId,
148
+ });
149
+ const items = page.items.map((task) => this.toSummaryRow(task, lastRunByTask.get(task.taskId)));
150
+ return page.nextCursor ? { items, nextCursor: page.nextCursor } : { items };
151
+ }
152
+ toSummaryRow(task, run) {
153
+ return {
154
+ taskId: task.taskId,
155
+ title: task.title,
156
+ status: task.status,
157
+ revision: task.revision,
158
+ stepCount: task.steps.length,
159
+ updatedAt: task.updatedAt,
160
+ schedule: task.scheduleRef
161
+ ? {
162
+ scheduleId: task.scheduleRef.scheduleId,
163
+ state: task.scheduleRef.state,
164
+ timing: describeTiming(task.scheduleRef.timing),
165
+ }
166
+ : null,
167
+ lastRun: run ? { runId: run.runId, status: run.status, startedAt: run.startedAt } : null,
168
+ };
169
+ }
170
+ // ------------------------------------------------------------------- get
171
+ get(owner, taskId, options = {}) {
172
+ const task = this.repo.requireOwnedTask(taskId, owner);
173
+ const recentRuns = options.includeRuns === false ? [] : this.repo.listRunsByTask(taskId).slice(0, 5);
174
+ return { task, recentRuns };
175
+ }
176
+ // ---------------------------------------------------------------- update
177
+ async update(input) {
178
+ const task = this.repo.requireOwnedTask(input.taskId, input.sessionId);
179
+ if (task.status === 'archived') {
180
+ throw new TaskEngineError('TASK_PERMISSION_DENIED', '任务已归档,只能查看历史,不能修改');
181
+ }
182
+ if (task.revision !== input.expectedRevision) {
183
+ throw new TaskEngineError('TASK_REVISION_CONFLICT', `revision 冲突:期望 ${input.expectedRevision},当前 ${task.revision};请先 task_get 获取最新 revision`, { details: { expectedRevision: input.expectedRevision, actualRevision: task.revision } });
184
+ }
185
+ let steps;
186
+ if (input.steps)
187
+ steps = this.normaliseSteps(input.steps);
188
+ const title = input.title?.trim();
189
+ if (title !== undefined && (title.length < 2 || title.length > 80)) {
190
+ throw new TaskEngineError('TASK_INVALID_ARGUMENTS', '任务标题长度必须为 2–80 个字符');
191
+ }
192
+ const description = input.description !== undefined ? truncateText(input.description.trim(), 2000) : undefined;
193
+ if (input.status && input.status !== task.status) {
194
+ // Schedule first: a failed host update must leave the task status untouched.
195
+ await this.applyStatusWithSchedule(task, input.status, input.sessionId);
196
+ }
197
+ const updated = await this.repo.mutateTask(input.taskId, input.expectedRevision, (current) => {
198
+ const next = {
199
+ ...current,
200
+ revision: current.revision + 1,
201
+ updatedAt: this.now(),
202
+ };
203
+ if (title !== undefined)
204
+ next.title = title;
205
+ if (description !== undefined) {
206
+ if (description)
207
+ next.description = description;
208
+ else
209
+ delete next.description;
210
+ }
211
+ if (steps)
212
+ next.steps = steps;
213
+ if (input.status)
214
+ next.status = input.status;
215
+ return next;
216
+ });
217
+ this.audit.record({
218
+ name: 'task.updated',
219
+ taskId: updated.taskId,
220
+ from: String(task.revision),
221
+ to: String(updated.revision),
222
+ sessionId: input.sessionId,
223
+ source: 'task_update',
224
+ detail: [title !== undefined ? 'title' : '', steps ? 'steps' : '', input.status ? `status=${input.status}` : '']
225
+ .filter(Boolean)
226
+ .join(','),
227
+ });
228
+ return updated;
229
+ }
230
+ async applyStatusWithSchedule(task, target, sessionId) {
231
+ const ref = task.scheduleRef;
232
+ if (!ref || ref.state === 'unlinked')
233
+ return;
234
+ if (target === 'paused' && ref.state === 'active') {
235
+ await this.schedules.update({ scheduleId: ref.scheduleId, patch: { active: false }, sessionId });
236
+ await this.patchScheduleRef(task.taskId, (current) => ({ ...current, state: 'paused', updatedAt: this.now() }));
237
+ this.audit.record({
238
+ name: 'task.schedule.changed',
239
+ taskId: task.taskId,
240
+ from: 'active',
241
+ to: 'paused',
242
+ sessionId,
243
+ source: 'task_update',
244
+ });
245
+ return;
246
+ }
247
+ if (target === 'active' && ref.state === 'paused') {
248
+ await this.schedules.update({ scheduleId: ref.scheduleId, patch: { active: true }, sessionId });
249
+ await this.patchScheduleRef(task.taskId, (current) => ({ ...current, state: 'active', updatedAt: this.now() }));
250
+ this.audit.record({
251
+ name: 'task.schedule.changed',
252
+ taskId: task.taskId,
253
+ from: 'paused',
254
+ to: 'active',
255
+ sessionId,
256
+ source: 'task_update',
257
+ });
258
+ }
259
+ }
260
+ async patchScheduleRef(taskId, mutate) {
261
+ try {
262
+ await this.repo.mutateTask(taskId, undefined, (current) => {
263
+ if (!current.scheduleRef)
264
+ return current;
265
+ return { ...current, scheduleRef: mutate({ ...current.scheduleRef }), revision: current.revision };
266
+ });
267
+ }
268
+ catch {
269
+ /* diagnostics-only patch: never mask the original operation result */
270
+ }
271
+ }
272
+ // --------------------------------------------------------------- archive
273
+ async archive(input) {
274
+ const task = this.repo.requireOwnedTask(input.taskId, input.sessionId);
275
+ if (task.status === 'archived')
276
+ return task;
277
+ if (task.revision !== input.expectedRevision) {
278
+ throw new TaskEngineError('TASK_REVISION_CONFLICT', `revision 冲突:期望 ${input.expectedRevision},当前 ${task.revision}`, { details: { expectedRevision: input.expectedRevision, actualRevision: task.revision } });
279
+ }
280
+ const active = this.repo.listActiveRunsByTask(task.taskId);
281
+ if (active.length > 0) {
282
+ throw new TaskEngineError('TASK_ALREADY_RUNNING', `任务仍有活动运行 ${active[0].runId},请先结束运行再归档`, { relatedRunId: active[0].runId });
283
+ }
284
+ // Unlink the host schedule first: archiving must not leave a live rule that
285
+ // can still fire for an archived task.
286
+ let unlinkedId;
287
+ if (task.scheduleRef) {
288
+ const removed = await this.schedules.remove(task.scheduleRef.scheduleId, input.sessionId);
289
+ unlinkedId = task.scheduleRef.scheduleId;
290
+ this.audit.record({
291
+ name: 'task.schedule.changed',
292
+ taskId: task.taskId,
293
+ from: task.scheduleRef.state,
294
+ to: 'deleted',
295
+ sessionId: input.sessionId,
296
+ source: 'task_archive',
297
+ detail: removed.alreadyGone ? 'already-gone' : undefined,
298
+ });
299
+ }
300
+ const archived = await this.repo.mutateTask(input.taskId, input.expectedRevision, (current) => {
301
+ const next = { ...current, status: 'archived', revision: current.revision + 1, updatedAt: this.now() };
302
+ delete next.scheduleRef;
303
+ return next;
304
+ });
305
+ this.audit.record({
306
+ name: 'task.archived',
307
+ taskId: archived.taskId,
308
+ from: task.status,
309
+ to: 'archived',
310
+ sessionId: input.sessionId,
311
+ source: 'task_archive',
312
+ detail: unlinkedId ? `unlinked=${unlinkedId}` : undefined,
313
+ });
314
+ return archived;
315
+ }
316
+ // ------------------------------------------------------- schedule linkage
317
+ async scheduleCreate(input) {
318
+ const task = this.repo.requireOwnedTask(input.taskId, input.sessionId);
319
+ if (task.status === 'archived') {
320
+ throw new TaskEngineError('TASK_PERMISSION_DENIED', '任务已归档,不能创建定时规则');
321
+ }
322
+ if (task.scheduleRef) {
323
+ throw new TaskEngineError('TASK_SCHEDULE_FAILED', `任务已有定时规则 ${task.scheduleRef.scheduleId};请使用 action="update" 修改或 action="delete" 后重建`);
324
+ }
325
+ const created = await this.schedules.create({
326
+ taskId: task.taskId,
327
+ taskTitle: task.title,
328
+ timing: input.timing,
329
+ sessionId: input.sessionId,
330
+ });
331
+ const stamp = this.now();
332
+ const ref = {
333
+ scheduleId: created.scheduleId,
334
+ timingKind: input.timing.kind,
335
+ timing: toHostTiming(input.timing),
336
+ state: 'active',
337
+ title: `后台任务 · ${task.title}`.slice(0, 120),
338
+ createdAt: stamp,
339
+ updatedAt: stamp,
340
+ };
341
+ const updated = await this.repo.mutateTask(task.taskId, undefined, (current) => ({
342
+ ...current,
343
+ scheduleRef: ref,
344
+ revision: current.revision + 1,
345
+ updatedAt: stamp,
346
+ }));
347
+ this.audit.record({
348
+ name: 'task.schedule.changed',
349
+ taskId: task.taskId,
350
+ from: 'none',
351
+ to: 'active',
352
+ sessionId: input.sessionId,
353
+ source: 'task_schedule:create',
354
+ detail: `scheduleId=${created.scheduleId}`,
355
+ });
356
+ return { ...updated, scheduleId: created.scheduleId };
357
+ }
358
+ async scheduleUpdate(input) {
359
+ const task = this.repo.requireOwnedTask(input.taskId, input.sessionId);
360
+ const ref = task.scheduleRef;
361
+ if (!ref)
362
+ throw new TaskEngineError('TASK_SCHEDULE_FAILED', '任务尚未关联定时规则,请先 action="create"');
363
+ if (task.status === 'archived')
364
+ throw new TaskEngineError('TASK_PERMISSION_DENIED', '任务已归档,不能修改定时规则');
365
+ try {
366
+ await this.schedules.update({ scheduleId: ref.scheduleId, patch: { timing: input.timing }, sessionId: input.sessionId });
367
+ }
368
+ catch (error) {
369
+ // Persist the failure for diagnostics but keep the old rule untouched and
370
+ // never report success (acceptance 14.3).
371
+ const message = error instanceof Error ? error.message : String(error);
372
+ await this.patchScheduleRef(task.taskId, (current) => ({
373
+ ...current,
374
+ updatedAt: this.now(),
375
+ lastError: { code: 'TASK_SCHEDULE_FAILED', message: message.slice(0, 500) },
376
+ }));
377
+ throw error;
378
+ }
379
+ const updated = await this.repo.mutateTask(task.taskId, undefined, (current) => {
380
+ const nextRef = {
381
+ ...(current.scheduleRef ?? ref),
382
+ timingKind: input.timing.kind,
383
+ timing: toHostTiming(input.timing),
384
+ updatedAt: this.now(),
385
+ };
386
+ delete nextRef.lastError;
387
+ return { ...current, scheduleRef: nextRef, revision: current.revision + 1, updatedAt: this.now() };
388
+ });
389
+ this.audit.record({
390
+ name: 'task.schedule.changed',
391
+ taskId: task.taskId,
392
+ from: ref.timingKind,
393
+ to: input.timing.kind,
394
+ sessionId: input.sessionId,
395
+ source: 'task_schedule:update',
396
+ detail: `scheduleId=${ref.scheduleId}`,
397
+ });
398
+ return updated;
399
+ }
400
+ async scheduleSetActive(input) {
401
+ const task = this.repo.requireOwnedTask(input.taskId, input.sessionId);
402
+ const ref = task.scheduleRef;
403
+ if (!ref)
404
+ throw new TaskEngineError('TASK_SCHEDULE_FAILED', '任务尚未关联定时规则');
405
+ const targetState = input.active ? 'active' : 'paused';
406
+ if (ref.state === targetState)
407
+ return { task, changed: false };
408
+ await this.schedules.update({ scheduleId: ref.scheduleId, patch: { active: input.active }, sessionId: input.sessionId });
409
+ const updated = await this.repo.mutateTask(task.taskId, undefined, (current) => ({
410
+ ...current,
411
+ scheduleRef: current.scheduleRef
412
+ ? { ...current.scheduleRef, state: targetState, updatedAt: this.now() }
413
+ : undefined,
414
+ revision: current.revision + 1,
415
+ updatedAt: this.now(),
416
+ }));
417
+ this.audit.record({
418
+ name: 'task.schedule.changed',
419
+ taskId: task.taskId,
420
+ from: ref.state,
421
+ to: targetState,
422
+ sessionId: input.sessionId,
423
+ source: 'task_schedule:setActive',
424
+ detail: `scheduleId=${ref.scheduleId}`,
425
+ });
426
+ return { task: updated, changed: true };
427
+ }
428
+ async scheduleDelete(input) {
429
+ const task = this.repo.requireOwnedTask(input.taskId, input.sessionId);
430
+ const ref = task.scheduleRef;
431
+ if (!ref)
432
+ throw new TaskEngineError('TASK_SCHEDULE_FAILED', '任务没有关联的定时规则');
433
+ const removed = await this.schedules.remove(ref.scheduleId, input.sessionId);
434
+ const updated = await this.repo.mutateTask(task.taskId, undefined, (current) => {
435
+ const next = { ...current, revision: current.revision + 1, updatedAt: this.now() };
436
+ delete next.scheduleRef;
437
+ return next;
438
+ });
439
+ this.audit.record({
440
+ name: 'task.schedule.changed',
441
+ taskId: task.taskId,
442
+ from: ref.state,
443
+ to: 'deleted',
444
+ sessionId: input.sessionId,
445
+ source: 'task_schedule:delete',
446
+ detail: `scheduleId=${ref.scheduleId}`,
447
+ });
448
+ return { task: updated, alreadyGone: removed.alreadyGone };
449
+ }
450
+ async scheduleStatus(input) {
451
+ const task = this.repo.requireOwnedTask(input.taskId, input.sessionId);
452
+ const ref = task.scheduleRef ?? null;
453
+ if (!ref || !this.schedules.available)
454
+ return { ref, live: null, available: this.schedules.available };
455
+ const entry = await this.schedules.view(ref.scheduleId).catch(() => undefined);
456
+ return {
457
+ ref,
458
+ live: entry
459
+ ? { status: entry.status, scheduledAt: entry.scheduledAt, title: entry.title }
460
+ : null,
461
+ available: true,
462
+ };
463
+ }
464
+ async scheduleRunNow(input) {
465
+ const task = this.repo.requireOwnedTask(input.taskId, input.sessionId);
466
+ const ref = task.scheduleRef;
467
+ if (!ref)
468
+ throw new TaskEngineError('TASK_SCHEDULE_FAILED', '任务没有关联的定时规则;可直接使用 task_run 手动执行');
469
+ const result = await this.schedules.runNow(ref.scheduleId);
470
+ this.audit.record({
471
+ name: 'task.schedule.changed',
472
+ taskId: task.taskId,
473
+ to: result.pending ? 'run-pending' : 'run-requested',
474
+ sessionId: input.sessionId,
475
+ source: 'task_schedule:run_now',
476
+ detail: `scheduleId=${ref.scheduleId}`,
477
+ });
478
+ return { pending: result.pending };
479
+ }
480
+ }
481
+ function decodeCursorSafe(cursor) {
482
+ if (!cursor)
483
+ return undefined;
484
+ try {
485
+ return JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
486
+ }
487
+ catch {
488
+ return undefined;
489
+ }
490
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Repository layer: the only place that talks to StorageDomain tables.
3
+ *
4
+ * Rules encoded here (PRD 7.3, 8.4):
5
+ * - records are immutable; every write produces a new validated object
6
+ * - read-modify-write goes through `table.update`, whose mutator runs inside
7
+ * the domain's per-key chain, so two concurrent calls cannot interleave
8
+ * - ownership is verified on read (`requireOwnedTask` / `requireOwnedRun`)
9
+ * - step records are keyed `runId/stepId`: one row per (runId, stepId)
10
+ */
11
+ import type { DomainLike, KvTableLike } from '../host.js';
12
+ import { type GlobalState, type RunRecord, type RunStepRecord, type TaskRecord } from '../domain/records.js';
13
+ export declare class Repository {
14
+ readonly domain: DomainLike;
15
+ private readonly now;
16
+ readonly tasks: KvTableLike<TaskRecord>;
17
+ readonly runs: KvTableLike<RunRecord>;
18
+ readonly steps: KvTableLike<RunStepRecord>;
19
+ readonly meta: KvTableLike<GlobalState>;
20
+ constructor(domain: DomainLike, now?: () => string);
21
+ getTask(taskId: string): TaskRecord | undefined;
22
+ requireTask(taskId: string): TaskRecord;
23
+ /**
24
+ * Ownership gate for every tool entry point (PRD 10.1). A record owned by a
25
+ * different Session is reported as "not found" so the error cannot be used to
26
+ * probe another Session's data.
27
+ */
28
+ requireOwnedTask(taskId: string, sessionId: string): TaskRecord;
29
+ listTasks(): TaskRecord[];
30
+ listTasksByOwner(ownerSessionId: string): TaskRecord[];
31
+ countUnarchivedTasks(ownerSessionId: string): number;
32
+ insertTask(record: TaskRecord): Promise<TaskRecord>;
33
+ /**
34
+ * Atomic task mutation with optimistic locking. The revision check runs inside
35
+ * the domain's update chain, so a stale `expectedRevision` can never win.
36
+ */
37
+ mutateTask(taskId: string, expectedRevision: number | undefined, mutate: (current: TaskRecord) => TaskRecord): Promise<TaskRecord>;
38
+ getRun(runId: string): RunRecord | undefined;
39
+ requireRun(runId: string): RunRecord;
40
+ requireOwnedRun(runId: string, sessionId: string): RunRecord;
41
+ listRuns(): RunRecord[];
42
+ listRunsByTask(taskId: string): RunRecord[];
43
+ listActiveRunsByOwner(ownerSessionId: string): RunRecord[];
44
+ listActiveRunsByTask(taskId: string): RunRecord[];
45
+ findRunByIdempotencyKey(taskId: string, idempotencyKey: string): RunRecord | undefined;
46
+ insertRun(record: RunRecord): Promise<RunRecord>;
47
+ mutateRun(runId: string, mutate: (current: RunRecord) => RunRecord): Promise<RunRecord>;
48
+ getStep(runId: string, stepId: string): RunStepRecord | undefined;
49
+ listSteps(runId: string): RunStepRecord[];
50
+ putStep(record: RunStepRecord): Promise<RunStepRecord>;
51
+ /**
52
+ * Steps are written before the run record on every transition, so a crash
53
+ * leaves the run short of its terminal write (recoverable: the startup scan
54
+ * marks it interrupted) rather than reporting progress that was never stored.
55
+ */
56
+ putSteps(records: RunStepRecord[]): Promise<void>;
57
+ mutateStep(runId: string, stepId: string, mutate: (current: RunStepRecord) => RunStepRecord): Promise<RunStepRecord>;
58
+ deleteRunCascade(runId: string): Promise<{
59
+ stepsDeleted: number;
60
+ runDeleted: boolean;
61
+ }>;
62
+ readMetaState(): GlobalState | undefined;
63
+ writeMetaState(state: GlobalState): Promise<void>;
64
+ private normaliseWriteError;
65
+ }