@oyasmi/pipiclaw 0.8.8 → 0.8.9-beta.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 (38) hide show
  1. package/dist/memory/task-digest.js +1 -1
  2. package/dist/playbooks/task-closeout.md +11 -10
  3. package/dist/playbooks/task-delegation.md +1 -1
  4. package/dist/playbooks/task-driving.md +6 -7
  5. package/dist/playbooks/task-planning.md +7 -5
  6. package/dist/playbooks/task-recurring.md +7 -4
  7. package/dist/playbooks/task-repair.md +7 -7
  8. package/dist/runtime/bootstrap.js +5 -1
  9. package/dist/runtime/task-commands.js +29 -51
  10. package/dist/runtime/task-driver.d.ts +0 -8
  11. package/dist/runtime/task-driver.js +83 -82
  12. package/dist/runtime/task-migration.d.ts +11 -0
  13. package/dist/runtime/task-migration.js +70 -0
  14. package/dist/shared/task-events.d.ts +0 -26
  15. package/dist/shared/task-events.js +0 -15
  16. package/dist/shared/task-ledger.d.ts +23 -1
  17. package/dist/shared/task-ledger.js +65 -16
  18. package/dist/tasks/control.d.ts +4 -0
  19. package/dist/tasks/control.js +3 -0
  20. package/dist/tasks/store.d.ts +28 -1
  21. package/dist/tasks/store.js +63 -6
  22. package/dist/tasks/transitions.d.ts +40 -0
  23. package/dist/tasks/transitions.js +81 -0
  24. package/dist/tools/task-manage/create.d.ts +2 -0
  25. package/dist/tools/task-manage/create.js +34 -0
  26. package/dist/tools/task-manage/lifecycle.d.ts +6 -0
  27. package/dist/tools/task-manage/lifecycle.js +196 -0
  28. package/dist/tools/task-manage/schema.d.ts +43 -0
  29. package/dist/tools/task-manage/schema.js +89 -0
  30. package/dist/tools/task-manage/shared.d.ts +36 -0
  31. package/dist/tools/task-manage/shared.js +246 -0
  32. package/dist/tools/task-manage/types.d.ts +53 -0
  33. package/dist/tools/task-manage/types.js +1 -0
  34. package/dist/tools/task-manage/verification.d.ts +16 -0
  35. package/dist/tools/task-manage/verification.js +111 -0
  36. package/dist/tools/task-manage.d.ts +9 -89
  37. package/dist/tools/task-manage.js +8 -696
  38. package/package.json +1 -1
@@ -1,21 +1,20 @@
1
- import { existsSync } from "node:fs";
2
- import { readdir, readFile } from "node:fs/promises";
1
+ import { readdir } from "node:fs/promises";
3
2
  import { join } from "node:path";
4
3
  import * as log from "../log.js";
5
4
  import { PLAYBOOKS_DIR } from "../paths.js";
6
- import { isTaskScheduleEvent, taskScheduleEventFilename } from "../shared/task-events.js";
7
- import { readActiveTasks } from "../shared/task-ledger.js";
8
- import { nextTaskWake } from "../shared/task-schedule.js";
5
+ import { normalizeTaskFields, readActiveTasks } from "../shared/task-ledger.js";
9
6
  import { errorMessage } from "../shared/text-utils.js";
10
7
  import { taskBudgetViolation } from "../tasks/control.js";
11
- import { claimTaskAttempt, dependencyState, escalateTask, releaseTaskAttemptClaim, updateStoredTask, } from "../tasks/store.js";
12
- import { parseScheduledEventContent } from "./events.js";
8
+ import { claimTaskAttempt, dependencyState, escalateTask, openRecurringTaskCycle, releaseTaskAttemptClaim, updateStoredTask, } from "../tasks/store.js";
9
+ import { TERMINAL_TASK_STATUSES } from "../tasks/transitions.js";
13
10
  /** Short debounce so a burst of nudges collapses into a single rescan. */
14
11
  const NUDGE_DEBOUNCE_MS = 50;
15
12
  /** Never schedule a scan closer than this, so near-now horizons cannot spin the loop. */
16
13
  const MIN_SLEEP_MS = 250;
14
+ /** Consecutive no-progress wakes before the governor pauses a task (spec 029, D5). */
15
+ const FUTILE_WAKE_LIMIT = 3;
17
16
  const CHANNEL_ID_PATTERN = /^(dm|group)_[A-Za-z0-9._:-]+$/;
18
- const TERMINAL_STATUSES = new Set(["done", "cancelled", "escalated", "paused"]);
17
+ const TERMINAL_STATUSES = TERMINAL_TASK_STATUSES;
19
18
  function isChannelId(value) {
20
19
  return CHANNEL_ID_PATTERN.test(value);
21
20
  }
@@ -77,7 +76,7 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
77
76
  : ` Its frontmatter is unreadable: also read ${join(PLAYBOOKS_DIR, "task-repair.md")}.`;
78
77
  const control = entry.frontmatter.control;
79
78
  const capsule = [
80
- `Task capsule: title=${entry.title}; status=${entry.frontmatter.status ?? "open"};`,
79
+ `Task capsule: title=${entry.title}; status=${entry.frontmatter.status ?? "active"};`,
81
80
  entry.latestNote ? `latest=${entry.latestNote};` : "",
82
81
  control?.nextAction ? `next=${control.nextAction};` : "",
83
82
  control ? `budget=${control.usage.attempts}/${control.budget.maxAttempts} attempts;` : "",
@@ -99,27 +98,7 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
99
98
  conversationType: channelId.startsWith("group_") ? "2" : "1",
100
99
  };
101
100
  }
102
- /**
103
- * A done recurring task whose schedule has come due. This is the one place the driver
104
- * wakes a `done` task: to open its next cycle. It uses a `[TASK_CYCLE:...]` tag (not
105
- * `[TASK_DRIVER:...]`) so the turn is not charged an attempt — start-cycle resets usage
106
- * anyway, matching the retired periodic-event flow.
107
- */
108
- export function createCycleStartEvent(channelId, entry, nowMs) {
109
- return {
110
- type: channelId.startsWith("group_") ? "group" : "dm",
111
- channelId,
112
- user: "TASK_DRIVER",
113
- userName: "TASK_DRIVER",
114
- text: `[TASK_CYCLE:${entry.id}] Start a new cycle for task ${entry.id} (${entry.title}). ` +
115
- `Open tasks/${entry.id}.md and read ${join(PLAYBOOKS_DIR, "task-recurring.md")}, then use ` +
116
- "task_manage start-cycle with a stable cycleId to fold the previous cycle and begin work.",
117
- ts: String(nowMs),
118
- conversationId: "",
119
- conversationType: channelId.startsWith("group_") ? "2" : "1",
120
- };
121
- }
122
- /** status done + a schedule cadence + a valid wake that is due. */
101
+ /** status done + a schedule cadence + a valid wake that is due → time to open the next cycle. */
123
102
  function isCycleStartReady(entry, nowMs) {
124
103
  return (entry.frontmatter.status === "done" &&
125
104
  Boolean(entry.frontmatter.schedule) &&
@@ -147,7 +126,7 @@ function taskEscalationEvent(channelId, entry, reason, nowMs) {
147
126
  function terminalDependencyReason(reason) {
148
127
  return reason?.includes(" is missing") ||
149
128
  reason?.includes(" is cancelled") ||
150
- reason?.includes(" is escalated") ||
129
+ reason?.includes(" is paused by the governor") ||
151
130
  reason?.includes("dependency cycle")
152
131
  ? reason
153
132
  : undefined;
@@ -260,19 +239,6 @@ export class TaskDriver {
260
239
  }
261
240
  }
262
241
  }
263
- async hasLiveScheduleEvent(channelId, id) {
264
- const filename = taskScheduleEventFilename(channelId, id);
265
- const eventPath = join(this.options.workspaceDir, "events", filename);
266
- if (!existsSync(eventPath))
267
- return false;
268
- try {
269
- const type = parseScheduledEventContent(await readFile(eventPath, "utf-8"), filename).type;
270
- return isTaskScheduleEvent({ use: "schedule", event: { type } });
271
- }
272
- catch {
273
- return false;
274
- }
275
- }
276
242
  async runOnce(now = new Date()) {
277
243
  if (this.options.isEnabled?.() === false || this.running)
278
244
  return;
@@ -301,22 +267,23 @@ export class TaskDriver {
301
267
  this.collectHorizons(entries, nowMs);
302
268
  if (dispatched >= settings.maxDispatchesPerTick || this.options.isChannelActive(channelId))
303
269
  continue;
304
- // Zero-token self-heal: a done recurring task with a missing/unparseable wake gets
305
- // its next occurrence recomputed deterministically rather than fail-open into an
306
- // accidental cycle.
270
+ // Zero-token self-heal: a done recurring task with a missing/unparseable wake (usually a
271
+ // hand edit that bypassed the runtime) gets its next occurrence recomputed via the same
272
+ // `normalizeTaskFields` write-path invariant, rather than fail-open into an accidental cycle.
307
273
  for (const entry of entries) {
308
274
  if (!needsWakeHeal(entry))
309
275
  continue;
310
- const next = nextTaskWake(entry.frontmatter.schedule, now);
311
- if (!next) {
276
+ let healedWake;
277
+ await updateStoredTask(channelDir, entry.id, (task) => {
278
+ healedWake = normalizeTaskFields(task.fields).wake;
279
+ task.fields.wake = healedWake;
280
+ });
281
+ if (!healedWake) {
312
282
  log.logWarning(`[${channelId}] Task ${entry.id} has an unparseable schedule`, entry.frontmatter.schedule);
313
283
  continue;
314
284
  }
315
- await updateStoredTask(channelDir, entry.id, (task) => {
316
- task.fields.wake = next.toISOString();
317
- });
318
- this.noteHorizon(next.getTime(), nowMs);
319
- log.logInfo(`[${channelId}] Task driver healed wake for ${entry.id}`, next.toISOString());
285
+ this.noteHorizon(new Date(healedWake).getTime(), nowMs);
286
+ log.logInfo(`[${channelId}] Task driver healed wake for ${entry.id}`, healedWake);
320
287
  }
321
288
  let governanceHandled = false;
322
289
  for (const candidate of entries) {
@@ -342,7 +309,8 @@ export class TaskDriver {
342
309
  if (governanceHandled)
343
310
  continue;
344
311
  // Actionable tasks and cycle-start-ready recurring tasks share one per-channel slot
345
- // and the same round-robin fairness; only the dispatch text and attempt accounting differ.
312
+ // and the same round-robin fairness. A cycle-start-ready task is folded into its next
313
+ // cycle deterministically by the runtime (D2) and then dispatched as an ordinary wake.
346
314
  const candidates = entries.filter((candidate) => candidate.actionable || isCycleStartReady(candidate, nowMs));
347
315
  if (candidates.length === 0)
348
316
  continue;
@@ -352,54 +320,87 @@ export class TaskDriver {
352
320
  ? [...candidates.slice(lastIndex + 1), ...candidates.slice(0, lastIndex + 1)]
353
321
  : candidates;
354
322
  let entry;
355
- let isCycleStart = false;
356
323
  for (const candidate of rotatedCandidates) {
357
- if (candidate.actionable) {
358
- const control = candidate.frontmatter.control;
359
- if (control) {
360
- const dependencies = await dependencyState(channelDir, control.dependsOn, candidate.id);
361
- if (!dependencies.ready)
362
- continue;
363
- }
364
- entry = candidate;
365
- isCycleStart = false;
366
- break;
324
+ const control = candidate.frontmatter.control;
325
+ if (control) {
326
+ const dependencies = await dependencyState(channelDir, control.dependsOn, candidate.id);
327
+ if (!dependencies.ready)
328
+ continue;
367
329
  }
368
- // Migration compat: while a parseable legacy `.schedule` event still owns the
369
- // cadence, defer to it so the cycle is not opened twice.
370
- if (await this.hasLiveScheduleEvent(channelId, candidate.id))
371
- continue;
372
330
  entry = candidate;
373
- isCycleStart = true;
374
331
  break;
375
332
  }
376
333
  if (!entry || dispatched >= settings.maxDispatchesPerTick)
377
334
  continue;
335
+ // A cycle-start-ready recurring task is reopened in-process before dispatch: fold the
336
+ // previous cycle, reset per-cycle control, mark it active. If the write fails we skip
337
+ // this tick rather than dispatch a stale `done` capsule.
338
+ if (!entry.actionable && isCycleStartReady(entry, nowMs)) {
339
+ let opened;
340
+ try {
341
+ opened = await openRecurringTaskCycle(channelDir, entry.id, now);
342
+ }
343
+ catch (error) {
344
+ // A malformed recurring body (e.g. missing History) must not stall the whole tick.
345
+ log.logWarning(`[${channelId}] Task driver could not open next cycle for ${entry.id}`, errorMessage(error));
346
+ continue;
347
+ }
348
+ if (!opened) {
349
+ log.logWarning(`[${channelId}] Task driver could not open next cycle for ${entry.id}`);
350
+ continue;
351
+ }
352
+ entry = {
353
+ ...entry,
354
+ frontmatter: {
355
+ ...entry.frontmatter,
356
+ status: "active",
357
+ wake: undefined,
358
+ control: opened.document.fields.control,
359
+ },
360
+ wakeMs: undefined,
361
+ actionable: true,
362
+ };
363
+ log.logInfo(`[${channelId}] Task driver opened cycle ${opened.cycleId} for ${entry.id}`);
364
+ }
378
365
  const key = attemptKey(channelId, entry.id);
379
366
  let fingerprint = await taskFingerprint(channelDir, entry);
380
- if (!isEligible(this.attempts.get(key), fingerprint, nowMs, settings))
367
+ const previous = this.attempts.get(key);
368
+ if (!isEligible(previous, fingerprint, nowMs, settings))
369
+ continue;
370
+ // D5: a wake that was accepted and left the ledger fingerprint unchanged made no
371
+ // visible progress. Count consecutive such wakes (a changed fingerprint — including
372
+ // a progress note or a failure — resets the count); after the limit the governor
373
+ // pauses the task and notifies the user, so no silent loop burns tokens forever.
374
+ const futileCount = previous?.accepted && previous.fingerprint === fingerprint ? previous.futileCount + 1 : 0;
375
+ if (futileCount >= FUTILE_WAKE_LIMIT) {
376
+ const reason = `task made no visible progress in ${FUTILE_WAKE_LIMIT} consecutive wakes`;
377
+ const escalationEvent = taskEscalationEvent(channelId, entry, reason, nowMs);
378
+ const accepted = await this.options.dispatch(escalationEvent);
379
+ this.observeDispatch(escalationEvent, accepted);
380
+ if (accepted && (await escalateTask(channelDir, entry.id, reason))) {
381
+ this.attempts.delete(key);
382
+ this.lastDispatchedTaskId.set(channelId, entry.id);
383
+ dispatched++;
384
+ lastDispatchOffset = offset;
385
+ log.logWarning(`[${channelId}] Task driver paused ${entry.id} (governor)`, reason);
386
+ }
381
387
  continue;
382
- // Cycle-start does not claim an attempt: start-cycle clears the previous cycle's usage,
383
- // so a claim would be immediately erased. Normal driving claims as before.
384
- const claim = !isCycleStart && entry.frontmatter.control
385
- ? await claimTaskAttempt(channelDir, entry.id, now)
386
- : undefined;
388
+ }
389
+ const claim = entry.frontmatter.control ? await claimTaskAttempt(channelDir, entry.id, now) : undefined;
387
390
  if (claim) {
388
391
  fingerprint = await taskFingerprint(channelDir, entry);
389
392
  }
390
- const event = isCycleStart
391
- ? createCycleStartEvent(channelId, entry, nowMs)
392
- : createTaskDriverEvent(channelId, entry, nowMs);
393
+ const event = createTaskDriverEvent(channelId, entry, nowMs);
393
394
  const accepted = await this.options.dispatch(event);
394
395
  this.observeDispatch(event, accepted);
395
396
  if (!accepted && claim)
396
397
  await releaseTaskAttemptClaim(channelDir, entry.id, claim, now);
397
- this.attempts.set(key, { fingerprint, atMs: nowMs, accepted });
398
+ this.attempts.set(key, { fingerprint, atMs: nowMs, accepted, futileCount });
398
399
  this.lastDispatchedTaskId.set(channelId, entry.id);
399
400
  if (accepted) {
400
401
  dispatched++;
401
402
  lastDispatchOffset = offset;
402
- log.logInfo(`[${channelId}] Task driver enqueued ${entry.id}${isCycleStart ? " (cycle-start)" : ""}`);
403
+ log.logInfo(`[${channelId}] Task driver enqueued ${entry.id}`);
403
404
  }
404
405
  else {
405
406
  log.logWarning(`[${channelId}] Task driver could not enqueue ${entry.id}`, "channel queue unavailable");
@@ -0,0 +1,11 @@
1
+ /**
2
+ * One-time migration closing the 027 window (spec 029, D6).
3
+ *
4
+ * Recurrence cadence now lives solely in a task's `schedule` frontmatter; the driver no
5
+ * longer reads legacy canonical `.schedule` periodic events. On daemon start we fold any
6
+ * residual `task.<channelId>.<id>.schedule.json` cron into the owning task's frontmatter
7
+ * (frontmatter wins if it already has a schedule) and delete the event, so there is never
8
+ * "two sources of truth" for a cadence again. Missing/archived tasks simply have their
9
+ * orphaned event removed. Failures are logged and skipped — this must never block startup.
10
+ */
11
+ export declare function migrateLegacyTaskScheduleEvents(workspaceDir: string): Promise<void>;
@@ -0,0 +1,70 @@
1
+ import { readdir, readFile, unlink } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import * as log from "../log.js";
4
+ import { parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
5
+ import { errorMessage } from "../shared/text-utils.js";
6
+ import { updateStoredTask } from "../tasks/store.js";
7
+ import { parseScheduledEventContent } from "./events.js";
8
+ import { discoverTaskChannels } from "./task-driver.js";
9
+ /**
10
+ * One-time migration closing the 027 window (spec 029, D6).
11
+ *
12
+ * Recurrence cadence now lives solely in a task's `schedule` frontmatter; the driver no
13
+ * longer reads legacy canonical `.schedule` periodic events. On daemon start we fold any
14
+ * residual `task.<channelId>.<id>.schedule.json` cron into the owning task's frontmatter
15
+ * (frontmatter wins if it already has a schedule) and delete the event, so there is never
16
+ * "two sources of truth" for a cadence again. Missing/archived tasks simply have their
17
+ * orphaned event removed. Failures are logged and skipped — this must never block startup.
18
+ */
19
+ export async function migrateLegacyTaskScheduleEvents(workspaceDir) {
20
+ const eventsDir = join(workspaceDir, "events");
21
+ let filenames;
22
+ try {
23
+ filenames = (await readdir(eventsDir)).filter((name) => name.endsWith(".json"));
24
+ }
25
+ catch {
26
+ return; // no events directory ⇒ nothing to migrate
27
+ }
28
+ if (filenames.length === 0)
29
+ return;
30
+ const channels = await discoverTaskChannels(workspaceDir);
31
+ for (const filename of filenames) {
32
+ const name = filename.slice(0, -".json".length);
33
+ const channelId = channels.find((id) => name.startsWith(taskEventPrefix(id)));
34
+ if (!channelId)
35
+ continue;
36
+ const parsed = parseTaskEventName(name, channelId);
37
+ if (!parsed || parsed.use !== "schedule")
38
+ continue;
39
+ const eventPath = join(eventsDir, filename);
40
+ let cron;
41
+ try {
42
+ const event = parseScheduledEventContent(await readFile(eventPath, "utf-8"), filename);
43
+ if (event.type !== "periodic")
44
+ continue; // not a cadence event; leave it for /events
45
+ cron = event.schedule;
46
+ }
47
+ catch {
48
+ continue; // unparseable ⇒ let /tasks doctor / the user handle it
49
+ }
50
+ try {
51
+ let folded = false;
52
+ const document = await updateStoredTask(join(workspaceDir, channelId), parsed.id, (task) => {
53
+ if (!task.fields.schedule) {
54
+ task.fields.schedule = cron;
55
+ folded = true;
56
+ }
57
+ });
58
+ await unlink(eventPath).catch(() => { });
59
+ if (folded) {
60
+ log.logInfo(`Migrated legacy schedule event ${name} into tasks/${parsed.id}.md`, cron);
61
+ }
62
+ else {
63
+ log.logInfo(`Removed legacy schedule event ${name}`, document ? "task frontmatter already owns a schedule" : "no active task");
64
+ }
65
+ }
66
+ catch (error) {
67
+ log.logWarning(`Could not migrate legacy schedule event ${name}`, errorMessage(error));
68
+ }
69
+ }
70
+ }
@@ -2,31 +2,5 @@ export interface ParsedTaskEventName {
2
2
  id: string;
3
3
  use: string;
4
4
  }
5
- export interface TaskEventLike {
6
- id?: string;
7
- use?: string;
8
- event?: {
9
- type: string;
10
- };
11
- }
12
- type EventOf<T> = T extends {
13
- event?: infer E;
14
- } ? E : never;
15
5
  export declare function taskEventPrefix(channelId: string, id?: string): string;
16
- export declare function taskEventName(channelId: string, id: string, use: string): string;
17
- export declare function taskScheduleEventName(channelId: string, id: string): string;
18
- export declare function taskScheduleEventFilename(channelId: string, id: string): string;
19
6
  export declare function parseTaskEventName(name: string, channelId: string): ParsedTaskEventName | undefined;
20
- export declare function isTaskScheduleEvent<T extends TaskEventLike>(info: T): info is T & {
21
- use: "schedule";
22
- event: Extract<EventOf<T>, {
23
- type: "periodic";
24
- }>;
25
- };
26
- export declare function isTaskCheckinEvent<T extends TaskEventLike>(info: T): info is T & {
27
- use: "checkin";
28
- event: Extract<EventOf<T>, {
29
- type: "one-shot";
30
- }>;
31
- };
32
- export {};
@@ -1,15 +1,6 @@
1
1
  export function taskEventPrefix(channelId, id) {
2
2
  return id ? `task.${channelId}.${id}.` : `task.${channelId}.`;
3
3
  }
4
- export function taskEventName(channelId, id, use) {
5
- return `${taskEventPrefix(channelId, id)}${use}`;
6
- }
7
- export function taskScheduleEventName(channelId, id) {
8
- return taskEventName(channelId, id, "schedule");
9
- }
10
- export function taskScheduleEventFilename(channelId, id) {
11
- return `${taskScheduleEventName(channelId, id)}.json`;
12
- }
13
4
  export function parseTaskEventName(name, channelId) {
14
5
  const normalized = name.endsWith(".json") ? name.slice(0, -".json".length) : name;
15
6
  const prefix = taskEventPrefix(channelId);
@@ -21,9 +12,3 @@ export function parseTaskEventName(name, channelId) {
21
12
  return undefined;
22
13
  return { id: rest.slice(0, lastDot), use: rest.slice(lastDot + 1) };
23
14
  }
24
- export function isTaskScheduleEvent(info) {
25
- return info.use === "schedule" && info.event?.type === "periodic";
26
- }
27
- export function isTaskCheckinEvent(info) {
28
- return info.use === "checkin" && info.event?.type === "one-shot";
29
- }
@@ -66,6 +66,16 @@ export declare const STANDARD_TASK_SECTIONS: readonly [{
66
66
  export declare function normalizeTaskId(id: string): string;
67
67
  /** The document body after the leading frontmatter block, or the whole content when there is none. */
68
68
  export declare function taskBody(content: string): string;
69
+ /**
70
+ * The task's *contract* segment: the body up to (excluding) the "Current Cycle" heading —
71
+ * i.e. the H1 title, Goal, DoD (with its checkbox state), Manual and Verification (spec 029, D4).
72
+ *
73
+ * Verification PASS and external approval bind to this segment, not the whole body, so routine
74
+ * `progress` notes (Current Cycle) and appended History/Completion Evidence never invalidate a
75
+ * PASS or approval — only a change to what the task promises to do and how it is checked does.
76
+ * A body without a Current Cycle heading (non-standard) falls back to the whole body.
77
+ */
78
+ export declare function taskContractSegment(body: string): string;
69
79
  /** Parse the leading `---` frontmatter block into the three known fields. */
70
80
  export declare function parseTaskFrontmatter(content: string): TaskFrontmatter;
71
81
  /**
@@ -96,7 +106,19 @@ export interface TaskDocumentFields {
96
106
  recurrence?: string;
97
107
  control?: TaskControl;
98
108
  }
99
- export declare function renderTaskDocument(fields: TaskDocumentFields, body: string): string;
109
+ /**
110
+ * The single time rule, enforced on the write path (spec 029, D1).
111
+ *
112
+ * The rule "a done recurring task's next wake is its cron next occurrence" becomes a
113
+ * construction-time invariant: every `done + schedule` document has its `wake` set to the
114
+ * next occurrence on the write path, regardless of any prior/stale/unparseable value. Once
115
+ * the cycle comes due the runtime reopens it (status leaves `done`, so this no longer fires).
116
+ * Every other field combination is left verbatim — `create`'s first-cycle seed (status
117
+ * `active`) and an explicit `wake` on a non-recurring task are honoured. When the cron cannot
118
+ * be parsed the existing value is kept so the corruption surfaces rather than being erased.
119
+ */
120
+ export declare function normalizeTaskFields(fields: TaskDocumentFields): TaskDocumentFields;
121
+ export declare function renderTaskDocument(fields: TaskDocumentFields, rawBody: string): string;
100
122
  /** Append one progress bullet to the standard Current Cycle section. */
101
123
  export declare function appendCurrentCycleNote(content: string, note: string): string;
102
124
  /**
@@ -1,6 +1,8 @@
1
1
  import { readdir, readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { parseTaskControl, taskPriorityRank } from "../tasks/control.js";
4
+ import { normalizeStoredStatus, TERMINAL_TASK_STATUSES, wasLegacyEscalated } from "../tasks/transitions.js";
5
+ import { nextTaskWake } from "./task-schedule.js";
4
6
  const FRONTMATTER_FIELDS = ["status", "wake", "schedule", "recurrence", "control"];
5
7
  const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
6
8
  export const DEFAULT_TASK_MANUAL = "- Follow the DoD, keep the current cycle log updated, and schedule check-ins when waiting.";
@@ -31,6 +33,25 @@ export function taskBody(content) {
31
33
  const after = content.indexOf("\n", end + 1);
32
34
  return after === -1 ? "" : content.slice(after + 1);
33
35
  }
36
+ /**
37
+ * The task's *contract* segment: the body up to (excluding) the "Current Cycle" heading —
38
+ * i.e. the H1 title, Goal, DoD (with its checkbox state), Manual and Verification (spec 029, D4).
39
+ *
40
+ * Verification PASS and external approval bind to this segment, not the whole body, so routine
41
+ * `progress` notes (Current Cycle) and appended History/Completion Evidence never invalidate a
42
+ * PASS or approval — only a change to what the task promises to do and how it is checked does.
43
+ * A body without a Current Cycle heading (non-standard) falls back to the whole body.
44
+ */
45
+ export function taskContractSegment(body) {
46
+ const lines = body.split("\n");
47
+ for (let index = 0; index < lines.length; index++) {
48
+ const match = /^#{1,6}\s+(.+?)\s*$/.exec(lines[index] ?? "");
49
+ if (match && matchesTaskSectionTitle(match[1] ?? "", ["Current Cycle", "当前周期"])) {
50
+ return lines.slice(0, index).join("\n").replace(/\s+$/, "");
51
+ }
52
+ }
53
+ return body;
54
+ }
34
55
  /** Parse the leading `---` frontmatter block into the three known fields. */
35
56
  export function parseTaskFrontmatter(content) {
36
57
  if (!content.startsWith("---"))
@@ -66,6 +87,16 @@ export function parseTaskFrontmatter(content) {
66
87
  }
67
88
  }
68
89
  }
90
+ // Canonicalise the (possibly legacy) status on read. A legacy `escalated` file is read as
91
+ // `paused` by the deterministic governor; the nuance is preserved in control.pausedBy so
92
+ // nothing downstream has to know the old name.
93
+ const rawStatus = frontmatter.status;
94
+ if (frontmatter.readable) {
95
+ frontmatter.status = normalizeStoredStatus(rawStatus);
96
+ if (wasLegacyEscalated(rawStatus) && frontmatter.control && frontmatter.control.pausedBy === undefined) {
97
+ frontmatter.control.pausedBy = "governor";
98
+ }
99
+ }
69
100
  return frontmatter;
70
101
  }
71
102
  /**
@@ -78,12 +109,9 @@ export function isTaskActionable(frontmatter, now) {
78
109
  return true;
79
110
  if (frontmatter.controlReadable === false)
80
111
  return true;
81
- if (frontmatter.status === "done" ||
82
- frontmatter.status === "cancelled" ||
83
- frontmatter.status === "escalated" ||
84
- frontmatter.status === "paused") {
112
+ // status is already canonicalised by parseTaskFrontmatter.
113
+ if (TERMINAL_TASK_STATUSES.has(frontmatter.status ?? ""))
85
114
  return false;
86
- }
87
115
  const wakeAt = parseWakeMs(frontmatter);
88
116
  if (wakeAt !== undefined && wakeAt > now)
89
117
  return false;
@@ -194,18 +222,39 @@ export function renderStandardTaskBody(input) {
194
222
  "",
195
223
  ].join("\n");
196
224
  }
197
- export function renderTaskDocument(fields, body) {
198
- const lines = ["---", `status: ${fields.status}`];
199
- if (fields.wake)
200
- lines.push(`wake: ${fields.wake}`);
201
- if (fields.schedule)
202
- lines.push(`schedule: ${fields.schedule}`);
203
- if (fields.recurrence)
204
- lines.push(`recurrence: ${fields.recurrence}`);
205
- if (fields.control)
206
- lines.push(`control: ${JSON.stringify(fields.control)}`);
225
+ /**
226
+ * The single time rule, enforced on the write path (spec 029, D1).
227
+ *
228
+ * The rule "a done recurring task's next wake is its cron next occurrence" becomes a
229
+ * construction-time invariant: every `done + schedule` document has its `wake` set to the
230
+ * next occurrence on the write path, regardless of any prior/stale/unparseable value. Once
231
+ * the cycle comes due the runtime reopens it (status leaves `done`, so this no longer fires).
232
+ * Every other field combination is left verbatim — `create`'s first-cycle seed (status
233
+ * `active`) and an explicit `wake` on a non-recurring task are honoured. When the cron cannot
234
+ * be parsed the existing value is kept so the corruption surfaces rather than being erased.
235
+ */
236
+ export function normalizeTaskFields(fields) {
237
+ if (fields.status !== "done" || !fields.schedule)
238
+ return fields;
239
+ const next = nextTaskWake(fields.schedule);
240
+ if (!next)
241
+ return fields;
242
+ const wake = next.toISOString();
243
+ return wake === fields.wake ? fields : { ...fields, wake };
244
+ }
245
+ export function renderTaskDocument(fields, rawBody) {
246
+ const document = normalizeTaskFields(fields);
247
+ const lines = ["---", `status: ${document.status}`];
248
+ if (document.wake)
249
+ lines.push(`wake: ${document.wake}`);
250
+ if (document.schedule)
251
+ lines.push(`schedule: ${document.schedule}`);
252
+ if (document.recurrence)
253
+ lines.push(`recurrence: ${document.recurrence}`);
254
+ if (document.control)
255
+ lines.push(`control: ${JSON.stringify(document.control)}`);
207
256
  lines.push("---");
208
- return `${lines.join("\n")}\n${body}`;
257
+ return `${lines.join("\n")}\n${rawBody}`;
209
258
  }
210
259
  /** Append one progress bullet to the standard Current Cycle section. */
211
260
  export function appendCurrentCycleNote(content, note) {
@@ -4,6 +4,8 @@ export type TaskSideEffects = "read-only" | "workspace" | "external";
4
4
  export type TaskVerificationMode = "evidence" | "independent";
5
5
  export type TaskVerificationStatus = "pending" | "passed" | "failed";
6
6
  export type TaskOutcome = "pending" | "running" | "progress" | "blocked" | "failed" | "verified";
7
+ /** Who paused a task: a user via /tasks pause, or the deterministic governor (ex-`escalated`). */
8
+ export type TaskPausedBy = "user" | "governor";
7
9
  export interface TaskBudget {
8
10
  maxAttempts: number;
9
11
  maxTokens?: number;
@@ -52,6 +54,8 @@ export interface TaskControl {
52
54
  lastFinishedAt?: string;
53
55
  /** Identifier of the currently open recurring-task cycle, when applicable. */
54
56
  cycleId?: string;
57
+ /** Present only while status is `paused`; distinguishes a user pause from a governor pause. */
58
+ pausedBy?: TaskPausedBy;
55
59
  }
56
60
  export interface TaskControlPatch {
57
61
  priority?: TaskPriority;
@@ -5,6 +5,7 @@ const SIDE_EFFECTS = ["read-only", "workspace", "external"];
5
5
  const VERIFICATION_MODES = ["evidence", "independent"];
6
6
  const VERIFICATION_STATUSES = ["pending", "passed", "failed"];
7
7
  const OUTCOMES = ["pending", "running", "progress", "blocked", "failed", "verified"];
8
+ const PAUSED_BY = ["user", "governor"];
8
9
  const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
9
10
  function isRecord(value) {
10
11
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -154,6 +155,7 @@ export function parseTaskControl(raw) {
154
155
  lastStartedAt: optionalString(value.lastStartedAt),
155
156
  lastFinishedAt: optionalString(value.lastFinishedAt),
156
157
  cycleId: optionalString(value.cycleId),
158
+ pausedBy: value.pausedBy === undefined ? undefined : enumValue(value.pausedBy, PAUSED_BY, "user"),
157
159
  };
158
160
  }
159
161
  /** Reset state which is meaningful only within one recurring task cycle. */
@@ -180,6 +182,7 @@ export function resetTaskControlForCycle(control, cycleId) {
180
182
  lastStartedAt: undefined,
181
183
  lastFinishedAt: undefined,
182
184
  cycleId: normalizedCycleId,
185
+ pausedBy: undefined,
183
186
  };
184
187
  }
185
188
  function patchOptionalString(current, value) {
@@ -1,11 +1,18 @@
1
1
  import { type TaskDocumentFields } from "../shared/task-ledger.js";
2
- import type { TaskControl, TaskOutcome } from "./control.js";
2
+ import { type TaskControl, type TaskOutcome } from "./control.js";
3
3
  export interface StoredTaskDocument {
4
4
  id: string;
5
5
  path: string;
6
6
  fields: TaskDocumentFields;
7
7
  body: string;
8
8
  }
9
+ /**
10
+ * Hash the task's *contract* segment (Goal/DoD/Manual/Verification), not the whole body, so
11
+ * verification PASS and external approval survive routine Current Cycle / History logging and
12
+ * only break when the contract itself changes (spec 029, D4). Old attestations that hashed the
13
+ * whole body naturally fail this check after upgrade and are re-verified — verification should
14
+ * always reflect current content, so there is no compatibility burden.
15
+ */
9
16
  export declare function taskBodyHash(body: string): string;
10
17
  export declare function readStoredTask(channelDir: string, idInput: string, includeArchive?: boolean, allowInvalidControl?: boolean): Promise<StoredTaskDocument | undefined>;
11
18
  export declare function writeStoredTask(document: StoredTaskDocument): Promise<void>;
@@ -26,7 +33,27 @@ export declare function finishTaskAttempt(channelDir: string, id: string, result
26
33
  silent?: boolean;
27
34
  finishedAt: Date;
28
35
  }): Promise<void>;
36
+ /**
37
+ * A governor stop: the deterministic task governor pauses the task (spec 029, D3 — this is
38
+ * the former `escalated` status, now `paused` + `pausedBy: "governor"`), records the reason,
39
+ * and clears the wake so no automatic dispatch resumes it until a human intervenes.
40
+ */
29
41
  export declare function escalateTask(channelDir: string, id: string, reason: string): Promise<boolean>;
42
+ /**
43
+ * A stable cycle id for a runtime-opened recurring cycle: `cycle-YYYY-MM-DD`, disambiguated
44
+ * with a `-N` suffix when the same task is reopened more than once on the same local day.
45
+ */
46
+ export declare function nextCycleId(previousCycleId: string | undefined, now: Date): string;
47
+ /**
48
+ * Open the next cycle of a done recurring task entirely in the runtime (spec 029, D2):
49
+ * fold the previous cycle's log into History, reset per-cycle control, clear the wake, and
50
+ * mark it `active`. This is the deterministic replacement for the retired
51
+ * `task_manage start-cycle` action — no LLM turn is spent just to reopen a cycle.
52
+ */
53
+ export declare function openRecurringTaskCycle(channelDir: string, id: string, now: Date): Promise<{
54
+ document: StoredTaskDocument;
55
+ cycleId: string;
56
+ } | undefined>;
30
57
  export declare function dependencyState(channelDir: string, dependencyIds: readonly string[], ownerId?: string): Promise<{
31
58
  ready: boolean;
32
59
  reason?: string;