@oyasmi/pipiclaw 0.8.8-beta.2 → 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 (43) hide show
  1. package/dist/agent/channel-runner.d.ts +1 -0
  2. package/dist/agent/channel-runner.js +8 -0
  3. package/dist/agent/runner-factory.d.ts +2 -0
  4. package/dist/memory/task-digest.js +1 -1
  5. package/dist/playbooks/task-closeout.md +11 -10
  6. package/dist/playbooks/task-delegation.md +1 -1
  7. package/dist/playbooks/task-driving.md +6 -7
  8. package/dist/playbooks/task-planning.md +7 -5
  9. package/dist/playbooks/task-recurring.md +7 -4
  10. package/dist/playbooks/task-repair.md +7 -7
  11. package/dist/runtime/bootstrap.d.ts +12 -1
  12. package/dist/runtime/bootstrap.js +9 -1
  13. package/dist/runtime/task-commands.js +29 -51
  14. package/dist/runtime/task-driver.d.ts +3 -8
  15. package/dist/runtime/task-driver.js +97 -84
  16. package/dist/runtime/task-migration.d.ts +11 -0
  17. package/dist/runtime/task-migration.js +70 -0
  18. package/dist/security/path-guard.js +3 -1
  19. package/dist/shared/task-events.d.ts +0 -26
  20. package/dist/shared/task-events.js +0 -15
  21. package/dist/shared/task-ledger.d.ts +23 -1
  22. package/dist/shared/task-ledger.js +65 -16
  23. package/dist/tasks/control.d.ts +4 -0
  24. package/dist/tasks/control.js +3 -0
  25. package/dist/tasks/store.d.ts +28 -1
  26. package/dist/tasks/store.js +63 -6
  27. package/dist/tasks/transitions.d.ts +40 -0
  28. package/dist/tasks/transitions.js +81 -0
  29. package/dist/tools/task-manage/create.d.ts +2 -0
  30. package/dist/tools/task-manage/create.js +34 -0
  31. package/dist/tools/task-manage/lifecycle.d.ts +6 -0
  32. package/dist/tools/task-manage/lifecycle.js +196 -0
  33. package/dist/tools/task-manage/schema.d.ts +43 -0
  34. package/dist/tools/task-manage/schema.js +89 -0
  35. package/dist/tools/task-manage/shared.d.ts +36 -0
  36. package/dist/tools/task-manage/shared.js +246 -0
  37. package/dist/tools/task-manage/types.d.ts +53 -0
  38. package/dist/tools/task-manage/types.js +1 -0
  39. package/dist/tools/task-manage/verification.d.ts +16 -0
  40. package/dist/tools/task-manage/verification.js +111 -0
  41. package/dist/tools/task-manage.d.ts +9 -89
  42. package/dist/tools/task-manage.js +8 -696
  43. package/package.json +5 -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;` : "",
@@ -92,33 +91,14 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
92
91
  text: `[TASK_DRIVER:${entry.id}] Resume task ${entry.id}. ${capsule}${repair} ` +
93
92
  `Open tasks/${entry.id}.md and read ${join(PLAYBOOKS_DIR, "task-driving.md")} before acting. ` +
94
93
  "Advance the next concrete step under the task's current control, acceptance, approval, and verification state. " +
95
- `If complete or waiting, use the matching task_manage lifecycle/checkpoint action from the playbook.${verificationInstruction}`,
94
+ `If complete or waiting, use the matching task_manage lifecycle/checkpoint action from the playbook.${verificationInstruction} ` +
95
+ "If the task explicitly says there is no change and no tool action is needed, do not call task_manage; respond with exactly [SILENT]. Otherwise, if this wake produces no user-visible change or result, respond with exactly [SILENT].",
96
96
  ts: String(nowMs),
97
97
  conversationId: "",
98
98
  conversationType: channelId.startsWith("group_") ? "2" : "1",
99
99
  };
100
100
  }
101
- /**
102
- * A done recurring task whose schedule has come due. This is the one place the driver
103
- * wakes a `done` task: to open its next cycle. It uses a `[TASK_CYCLE:...]` tag (not
104
- * `[TASK_DRIVER:...]`) so the turn is not charged an attempt — start-cycle resets usage
105
- * anyway, matching the retired periodic-event flow.
106
- */
107
- export function createCycleStartEvent(channelId, entry, nowMs) {
108
- return {
109
- type: channelId.startsWith("group_") ? "group" : "dm",
110
- channelId,
111
- user: "TASK_DRIVER",
112
- userName: "TASK_DRIVER",
113
- text: `[TASK_CYCLE:${entry.id}] Start a new cycle for task ${entry.id} (${entry.title}). ` +
114
- `Open tasks/${entry.id}.md and read ${join(PLAYBOOKS_DIR, "task-recurring.md")}, then use ` +
115
- "task_manage start-cycle with a stable cycleId to fold the previous cycle and begin work.",
116
- ts: String(nowMs),
117
- conversationId: "",
118
- conversationType: channelId.startsWith("group_") ? "2" : "1",
119
- };
120
- }
121
- /** 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. */
122
102
  function isCycleStartReady(entry, nowMs) {
123
103
  return (entry.frontmatter.status === "done" &&
124
104
  Boolean(entry.frontmatter.schedule) &&
@@ -146,7 +126,7 @@ function taskEscalationEvent(channelId, entry, reason, nowMs) {
146
126
  function terminalDependencyReason(reason) {
147
127
  return reason?.includes(" is missing") ||
148
128
  reason?.includes(" is cancelled") ||
149
- reason?.includes(" is escalated") ||
129
+ reason?.includes(" is paused by the governor") ||
150
130
  reason?.includes("dependency cycle")
151
131
  ? reason
152
132
  : undefined;
@@ -178,6 +158,14 @@ export class TaskDriver {
178
158
  */
179
159
  this.lastDispatchedTaskId = new Map();
180
160
  }
161
+ observeDispatch(event, accepted) {
162
+ try {
163
+ this.options.onDispatch?.(event, accepted);
164
+ }
165
+ catch (error) {
166
+ log.logWarning("Task driver dispatch observer failed", errorMessage(error));
167
+ }
168
+ }
181
169
  start() {
182
170
  if (this.loopActive)
183
171
  return;
@@ -251,19 +239,6 @@ export class TaskDriver {
251
239
  }
252
240
  }
253
241
  }
254
- async hasLiveScheduleEvent(channelId, id) {
255
- const filename = taskScheduleEventFilename(channelId, id);
256
- const eventPath = join(this.options.workspaceDir, "events", filename);
257
- if (!existsSync(eventPath))
258
- return false;
259
- try {
260
- const type = parseScheduledEventContent(await readFile(eventPath, "utf-8"), filename).type;
261
- return isTaskScheduleEvent({ use: "schedule", event: { type } });
262
- }
263
- catch {
264
- return false;
265
- }
266
- }
267
242
  async runOnce(now = new Date()) {
268
243
  if (this.options.isEnabled?.() === false || this.running)
269
244
  return;
@@ -292,22 +267,23 @@ export class TaskDriver {
292
267
  this.collectHorizons(entries, nowMs);
293
268
  if (dispatched >= settings.maxDispatchesPerTick || this.options.isChannelActive(channelId))
294
269
  continue;
295
- // Zero-token self-heal: a done recurring task with a missing/unparseable wake gets
296
- // its next occurrence recomputed deterministically rather than fail-open into an
297
- // 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.
298
273
  for (const entry of entries) {
299
274
  if (!needsWakeHeal(entry))
300
275
  continue;
301
- const next = nextTaskWake(entry.frontmatter.schedule, now);
302
- 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) {
303
282
  log.logWarning(`[${channelId}] Task ${entry.id} has an unparseable schedule`, entry.frontmatter.schedule);
304
283
  continue;
305
284
  }
306
- await updateStoredTask(channelDir, entry.id, (task) => {
307
- task.fields.wake = next.toISOString();
308
- });
309
- this.noteHorizon(next.getTime(), nowMs);
310
- 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);
311
287
  }
312
288
  let governanceHandled = false;
313
289
  for (const candidate of entries) {
@@ -320,7 +296,9 @@ export class TaskDriver {
320
296
  if (!escalationReason)
321
297
  continue;
322
298
  governanceHandled = true;
323
- const accepted = await this.options.dispatch(taskEscalationEvent(channelId, candidate, escalationReason, nowMs));
299
+ const escalationEvent = taskEscalationEvent(channelId, candidate, escalationReason, nowMs);
300
+ const accepted = await this.options.dispatch(escalationEvent);
301
+ this.observeDispatch(escalationEvent, accepted);
324
302
  if (accepted && (await escalateTask(channelDir, candidate.id, escalationReason))) {
325
303
  dispatched++;
326
304
  lastDispatchOffset = offset;
@@ -331,7 +309,8 @@ export class TaskDriver {
331
309
  if (governanceHandled)
332
310
  continue;
333
311
  // Actionable tasks and cycle-start-ready recurring tasks share one per-channel slot
334
- // 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.
335
314
  const candidates = entries.filter((candidate) => candidate.actionable || isCycleStartReady(candidate, nowMs));
336
315
  if (candidates.length === 0)
337
316
  continue;
@@ -341,53 +320,87 @@ export class TaskDriver {
341
320
  ? [...candidates.slice(lastIndex + 1), ...candidates.slice(0, lastIndex + 1)]
342
321
  : candidates;
343
322
  let entry;
344
- let isCycleStart = false;
345
323
  for (const candidate of rotatedCandidates) {
346
- if (candidate.actionable) {
347
- const control = candidate.frontmatter.control;
348
- if (control) {
349
- const dependencies = await dependencyState(channelDir, control.dependsOn, candidate.id);
350
- if (!dependencies.ready)
351
- continue;
352
- }
353
- entry = candidate;
354
- isCycleStart = false;
355
- 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;
356
329
  }
357
- // Migration compat: while a parseable legacy `.schedule` event still owns the
358
- // cadence, defer to it so the cycle is not opened twice.
359
- if (await this.hasLiveScheduleEvent(channelId, candidate.id))
360
- continue;
361
330
  entry = candidate;
362
- isCycleStart = true;
363
331
  break;
364
332
  }
365
333
  if (!entry || dispatched >= settings.maxDispatchesPerTick)
366
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
+ }
367
365
  const key = attemptKey(channelId, entry.id);
368
366
  let fingerprint = await taskFingerprint(channelDir, entry);
369
- if (!isEligible(this.attempts.get(key), fingerprint, nowMs, settings))
367
+ const previous = this.attempts.get(key);
368
+ if (!isEligible(previous, fingerprint, nowMs, settings))
370
369
  continue;
371
- // Cycle-start does not claim an attempt: start-cycle clears the previous cycle's usage,
372
- // so a claim would be immediately erased. Normal driving claims as before.
373
- const claim = !isCycleStart && entry.frontmatter.control
374
- ? await claimTaskAttempt(channelDir, entry.id, now)
375
- : undefined;
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
+ }
387
+ continue;
388
+ }
389
+ const claim = entry.frontmatter.control ? await claimTaskAttempt(channelDir, entry.id, now) : undefined;
376
390
  if (claim) {
377
391
  fingerprint = await taskFingerprint(channelDir, entry);
378
392
  }
379
- const event = isCycleStart
380
- ? createCycleStartEvent(channelId, entry, nowMs)
381
- : createTaskDriverEvent(channelId, entry, nowMs);
393
+ const event = createTaskDriverEvent(channelId, entry, nowMs);
382
394
  const accepted = await this.options.dispatch(event);
395
+ this.observeDispatch(event, accepted);
383
396
  if (!accepted && claim)
384
397
  await releaseTaskAttemptClaim(channelDir, entry.id, claim, now);
385
- this.attempts.set(key, { fingerprint, atMs: nowMs, accepted });
398
+ this.attempts.set(key, { fingerprint, atMs: nowMs, accepted, futileCount });
386
399
  this.lastDispatchedTaskId.set(channelId, entry.id);
387
400
  if (accepted) {
388
401
  dispatched++;
389
402
  lastDispatchOffset = offset;
390
- log.logInfo(`[${channelId}] Task driver enqueued ${entry.id}${isCycleStart ? " (cycle-start)" : ""}`);
403
+ log.logInfo(`[${channelId}] Task driver enqueued ${entry.id}`);
391
404
  }
392
405
  else {
393
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
+ }
@@ -161,7 +161,9 @@ function isDeniedSystemPath(path) {
161
161
  return SYSTEM_DENY_PREFIXES.some((prefix) => startsWithPathPrefix(path, normalize(prefix)));
162
162
  }
163
163
  function matchesConfiguredPath(path, entries, ctx) {
164
- return entries.map((entry) => resolveConfiguredPath(entry, ctx)).some((entry) => startsWithPathPrefix(path, entry));
164
+ return entries
165
+ .map((entry) => resolveForGuard(resolveConfiguredPath(entry, ctx), ctx))
166
+ .some((entry) => startsWithPathPrefix(path, entry));
165
167
  }
166
168
  function pathAllowedByDefaults(path, ctx) {
167
169
  const homeDir = ctx.homeDir ?? homedir();
@@ -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) {