@oyasmi/pipiclaw 0.8.8-beta.1 → 0.8.8-beta.2

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.
package/README.md CHANGED
@@ -230,15 +230,15 @@ pipiclaw
230
230
  - 未知的斜杠命令会被直接拒绝并提示 `/help`,不会作为普通消息发给模型(避免 `/modle` 这类笔误变成一整轮 LLM 调用)。workspace skill 也可作为命令调用(`/skill:<名称>`)。
231
231
  - `/model` 依次尝试精确 `provider/modelId`、精确 `modelId`、对完整引用的子串匹配,只有唯一命中时才切换,例如 `/model turbo`。
232
232
 
233
- 事件与任务的详细用法见 [docs/events-and-sub-agents.md](./docs/events-and-sub-agents.md) 与 [docs/tasks.md](./docs/tasks.md)。
233
+ 事件与任务的详细用法见 [docs/events-and-tasks.md](./docs/events-and-tasks.md);子代理见 [docs/sub-agents.md](./docs/sub-agents.md)。
234
234
 
235
235
  ## 文档地图(Documentation)
236
236
 
237
237
  | 文档 | 内容 |
238
238
  |------|------|
239
239
  | [docs/configuration.md](./docs/configuration.md) | 全部配置项:钉钉、模型、settings、tools、TUI、记忆与工作区文件 |
240
- | [docs/events-and-sub-agents.md](./docs/events-and-sub-agents.md) | 定时事件(含 `preAction` 门控、`event_manage`)与预定义子代理 |
241
- | [docs/tasks.md](./docs/tasks.md) | 任务台账、内建 task driver、`/tasks` 控制面与 `task_manage` 工具 |
240
+ | [docs/events-and-tasks.md](./docs/events-and-tasks.md) | 定时事件(含 `preAction` 门控、`event_manage`)、任务台账、内建 task driver、`/tasks` 控制面与 `task_manage` 工具 |
241
+ | [docs/sub-agents.md](./docs/sub-agents.md) | 预定义子代理:委派、隔离 worktree 与独立验收 |
242
242
  | [docs/runtime-playbooks.md](./docs/runtime-playbooks.md) | Runtime playbooks 与知识分层模型 |
243
243
  | [docs/deployment-and-operations.md](./docs/deployment-and-operations.md) | 长期运行、日志、可观测性、升级、备份与排障 |
244
244
  | [docs/scaling-and-concurrency.md](./docs/scaling-and-concurrency.md) | 并发模型与容量边界 |
@@ -13,8 +13,8 @@ priority: 30
13
13
 
14
14
  - 当前回合立即能做:直接做,不建 immediate。`event_manage` 会拒绝 immediate,防止自触发循环。
15
15
  - 将来某时只提醒一次:one-shot,至少提前 2 分钟。
16
- - 固定节奏重复提醒/检查:periodic,五段 cron + timezone。
17
- - 周期性产出任务:task + canonical `.schedule`,见 `task-recurring.md`。
16
+ - 固定节奏重复提醒/检查:periodic,五段 cron(按主机时区解释,无 timezone 字段)。
17
+ - 周期性产出任务:单个 task 文件,节奏写在 frontmatter 的 `schedule`,见 `task-recurring.md`。
18
18
 
19
19
  优先使用 `event_manage`,它会验证 JSON、channel、时间间隔、preAction command guard 和总量。工具不可用时才直接维护 `events/*.json`;无效文件可能被 scheduler 忽略。
20
20
 
@@ -25,7 +25,7 @@ priority: 30
25
25
  ```
26
26
 
27
27
  ```json
28
- {"type":"periodic","channelId":"<当前channel>","text":"执行工作日巡检","schedule":"0 9 * * 1-5","timezone":"Asia/Shanghai"}
28
+ {"type":"periodic","channelId":"<当前channel>","text":"执行工作日巡检","schedule":"0 9 * * 1-5"}
29
29
  ```
30
30
 
31
31
  普通 periodic 最小间隔 30 分钟;带 preAction gate 时最小 5 分钟;事件总数上限 50。任务拥有的事件使用 `task.<channelId>.<taskId>.<use>`,便于闭环清理。
@@ -40,8 +40,8 @@ FAIL 后用 progress 记录失败证据、status 回 in-progress,修复后重
40
40
 
41
41
  ## done / cancel
42
42
 
43
- `task_manage done` 需要 summary 和可查证 evidence,可附 residualRisk。它检查 checkbox、依赖、child、外部授权、独立 PASS,再记录收尾、清理临时 task events;一次性任务归档,周期任务保留 `.schedule` 并原地睡眠。
43
+ `task_manage done` 需要 summary 和可查证 evidence,可附 residualRisk。它检查 checkbox、依赖、child、外部授权、独立 PASS,再记录收尾、清理临时 task events;一次性任务归档,有 `schedule` frontmatter 的周期任务算出下一次 `wake` 并原地睡眠。
44
44
 
45
- 放弃用 `cancel` + reason,不伪装 done。cancel 要求先处理 child,随后归档并删除包括 `.schedule` 在内的所有 task-owned events。
45
+ 放弃用 `cancel` + reason,不伪装 done。cancel 要求先处理 child,随后归档并删除全部 task-owned events。
46
46
 
47
47
  完成结论必须来自证据:具体命令、测试结果、review、外部确认或明确的未运行理由。“看起来可以”不是 evidence。
@@ -1,44 +1,41 @@
1
1
  ---
2
2
  name: task-recurring
3
- description: Before creating, rescheduling, pausing, or retiring a recurring task and its schedule event.
3
+ description: Before creating, rescheduling, pausing, or retiring a recurring task.
4
4
  requires-tools: task_manage
5
5
  priority: 43
6
6
  ---
7
7
 
8
8
  # 周期性任务
9
9
 
10
- 一个周期任务由两份真相组成:
10
+ 一个周期任务就是**一个文件**:`tasks/<id>.md`。节奏在 frontmatter 的 `schedule`(五段 cron,按主机时区解释),做法与跨周期经验在正文。没有配套事件,也没有 `.schedule` 命名约定。
11
11
 
12
- - `tasks/<id>.md`:目标、DoD、Manual、验收与跨周期经验。
13
- - `task.<channelId>.<id>.schedule`:唯一 canonical periodic cadence。
14
-
15
- 节奏在 event,做法在 task。`recurrence` 只是可读标注。
12
+ `recurrence` 只是给人看的可选标注(如 `每周一`),没有机器语义。周期性 = `schedule` 是否存在。
16
13
 
17
14
  ## 创建
18
15
 
19
- 先按 `task-planning.md` 创建 task,必须填写 recurrence;再用 `event_manage create` 建 `.schedule`:
16
+ 按 `task-planning.md` 创建 task,并给 `schedule`:
20
17
 
21
- ```json
22
- {"type":"periodic","channelId":"<当前channel>","text":"推进任务 weekly-report:读取任务文件,必要时 start-cycle","schedule":"30 9 * * 1","timezone":"Asia/Shanghai"}
18
+ ```
19
+ task_manage create id=weekly-report title=... goal=... dod=... schedule="30 9 * * 1"
23
20
  ```
24
21
 
25
- 纯提醒没有产出和验收,不建 task,使用普通 periodic event。
22
+ cron 最密每 30 分钟一次,落盘前校验。纯提醒(无产出、无验收)不建 task,用普通 periodic event。
26
23
 
27
24
  ## 周期运行
28
25
 
29
- done 的周期任务留在原地睡眠,driver 不唤醒;只有 `.schedule` 开启新周期。
26
+ done 的周期任务留在原地睡眠:`task_manage done` 会用 croner 算出下一次 occurrence 写入 `wake`,状态是 `done` + 未来的 `wake`。到点时 driver 自动派发一条 cycle-start 唤醒。
30
27
 
31
- - 上周期 done:调用 `task_manage start-cycle`,给稳定 cycleId。它原子折叠上一周期日志、清空本周期用量/验收/授权/worktree 元数据并置 in-progress。
28
+ - 收到 cycle-start:调用 `task_manage start-cycle`,给稳定 cycleId。它原子折叠上一周期日志、清空本周期用量/验收/授权/worktree 元数据并置 in-progress。
32
29
  - 上周期未完成:不要覆盖或虚勾 DoD。先完成、如实缩小本轮范围并验收,或与用户确认后 cancel 整项任务。
33
30
 
34
- 周期内继续、等待和恢复只使用 task wake,不建 `.checkin`。
31
+ 周期内继续、等待和恢复只用 task `wake`。
35
32
 
36
33
  ## 复盘、调整和退役
37
34
 
38
35
  每轮闭环前把返工原因、预检步骤和格式偏好写回 Manual;跨任务才沉淀 workspace skill。
39
36
 
40
- - 改节奏:整体 update `.schedule`,并用 task_manage set 同步 recurrence 标注。
41
- - 暂停:pause task;若要完全安静也删除 schedule,恢复时重建。
42
- - 退役:`task_manage cancel`,它归档任务并删除全部 task-owned events,包括 schedule。
37
+ - 改节奏:`task_manage set schedule="<新 cron>"`;若任务当前 done,同一次写入会重算 `wake`。一处真相。
38
+ - 暂停:`/tasks pause <id>`;`/tasks resume` 恢复。
39
+ - 退役:`task_manage cancel`,归档任务并清理全部 task-owned events。
43
40
 
44
- 不要手工改 status 开周期,也不要只删 schedule 留下永远不会再开始的活任务。
41
+ 不要手工改 status 开周期。
@@ -40,6 +40,6 @@ PASS 和 external approval 都绑定 task body;PASS 还可能绑定 Git artifa
40
40
 
41
41
  ## 事件与重启
42
42
 
43
- done/cancel 会清理 `task.<channelId>.<id>.*`;孤儿事件用 event_manage 删除。recurring task 没有 canonical `.schedule` 则补建。旧 `.checkin` 是 legacy,删除并以 wake 为单一恢复条件。
43
+ done/cancel 会清理 `task.<channelId>.<id>.*`;孤儿事件用 event_manage 删除。周期任务的节奏在 frontmatter 的 `schedule`;旧 `.checkin` / `.schedule` 是 legacy,把 cron 折进 frontmatter 后删除事件,以 wake 为单一恢复条件(`/tasks doctor` 会给出迁移提示)。
44
44
 
45
45
  task 文件是恢复真相。daemon 重启会清空内存 cooldown,可推进任务可能很快重放;durable dispatch 租约也提供至少一次派发。每次先核对已完成产物,避免重复外部动作。
@@ -68,8 +68,8 @@ interface RuntimeContextOptions {
68
68
  createTaskDriver?: () => {
69
69
  start(): void;
70
70
  stop(): void;
71
+ nudge?(): void;
71
72
  };
72
- taskDriverIntervalMs?: number;
73
73
  startServices?: boolean;
74
74
  registerSignalHandlers?: boolean;
75
75
  }
@@ -436,7 +436,7 @@ export function createRuntimeContext(options) {
436
436
  const runner = channelRunners.get(channelId);
437
437
  if (runner?.isBusy()) {
438
438
  runner.requestStop();
439
- const taskId = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(runner.getTurnStatus().taskText ?? "")?.[1];
439
+ const taskId = /^\[TASK_(?:DRIVER|CYCLE):([A-Za-z0-9._-]+)\]/.exec(runner.getTurnStatus().taskText ?? "")?.[1];
440
440
  if (taskId) {
441
441
  const pauseResult = await pauseTask({
442
442
  args: "",
@@ -646,6 +646,9 @@ export function createRuntimeContext(options) {
646
646
  finally {
647
647
  await durableDispatch?.markCompleted(event.dispatchId);
648
648
  runner.endTurn();
649
+ // A finished turn may have written task files (progress/done/start-cycle); rescan
650
+ // now so a continuing task chain advances immediately instead of after a full sleep.
651
+ taskDriver.nudge?.();
649
652
  }
650
653
  })();
651
654
  activeTasks.add(task);
@@ -716,7 +719,6 @@ export function createRuntimeContext(options) {
716
719
  return runtimeSettingsManager.getTaskDriverSettings();
717
720
  },
718
721
  isEnabled: () => loadToolsConfig(options.paths.appHomeDir).tools.tasks.enabled,
719
- intervalMs: options.taskDriverIntervalMs,
720
722
  });
721
723
  const shutdownWithReason = async (reason = "manual") => {
722
724
  if (shutdownPromise) {
@@ -72,7 +72,7 @@ function formatEventSummary(name, event) {
72
72
  lines.push(` at: ${event.at}`);
73
73
  }
74
74
  if (event.type === "periodic") {
75
- lines.push(` schedule: ${event.schedule}`, ` timezone: ${event.timezone}`);
75
+ lines.push(` schedule: ${event.schedule}`);
76
76
  }
77
77
  lines.push(` text: ${clipText(event.text)}`);
78
78
  return lines.join("\n");
@@ -140,8 +140,6 @@ function formatHistoryRecord(record) {
140
140
  details.push(` channelId: ${record.channelId}`);
141
141
  if (record.schedule)
142
142
  details.push(` schedule: ${record.schedule}`);
143
- if (record.timezone)
144
- details.push(` timezone: ${record.timezone}`);
145
143
  if (record.at)
146
144
  details.push(` at: ${record.at}`);
147
145
  if (record.nextRunAt)
@@ -24,7 +24,12 @@ export interface PeriodicEvent {
24
24
  channelId: string;
25
25
  text: string;
26
26
  schedule: string;
27
- timezone: string;
27
+ /**
28
+ * Legacy field only. Pre-027 events carried an IANA `timezone`; it is no longer part of
29
+ * the contract (cron follows the host timezone) but is preserved here on load so the
30
+ * watcher can warn when it disagrees with the host, without rejecting or rewriting the file.
31
+ */
32
+ legacyTimezone?: string;
28
33
  preAction?: EventAction;
29
34
  }
30
35
  export type ScheduledEvent = ImmediateEvent | OneShotEvent | PeriodicEvent;
@@ -40,7 +45,6 @@ export interface EventHistoryRecord {
40
45
  result: EventHistoryResult;
41
46
  reason?: string;
42
47
  schedule?: string;
43
- timezone?: string;
44
48
  at?: string;
45
49
  nextRunAt?: string;
46
50
  textPreview?: string;
@@ -91,15 +91,15 @@ export function parseScheduledEventContent(content, filename) {
91
91
  if (typeof data.schedule !== "string" || data.schedule.trim().length === 0) {
92
92
  throw new Error(`Missing 'schedule' field for periodic event in ${filename}`);
93
93
  }
94
- if (typeof data.timezone !== "string" || data.timezone.trim().length === 0) {
95
- throw new Error(`Missing 'timezone' field for periodic event in ${filename}`);
96
- }
94
+ // A legacy `timezone` is tolerated (never a parse error) and carried through only for
95
+ // the host-mismatch warning; the cron itself is always host-timezone.
96
+ const legacyTimezone = typeof data.timezone === "string" && data.timezone.trim().length > 0 ? data.timezone : undefined;
97
97
  return {
98
98
  type,
99
99
  channelId,
100
100
  text,
101
101
  schedule: data.schedule,
102
- timezone: data.timezone,
102
+ ...(legacyTimezone ? { legacyTimezone } : {}),
103
103
  ...(preAction ? { preAction } : {}),
104
104
  };
105
105
  }
@@ -212,7 +212,7 @@ export class EventsWatcher {
212
212
  result,
213
213
  textPreview: truncateTextPreview(event.text),
214
214
  ...(event.type === "one-shot" ? { at: event.at } : {}),
215
- ...(event.type === "periodic" ? { schedule: event.schedule, timezone: event.timezone } : {}),
215
+ ...(event.type === "periodic" ? { schedule: event.schedule } : {}),
216
216
  ...extra,
217
217
  });
218
218
  }
@@ -401,8 +401,17 @@ export class EventsWatcher {
401
401
  this.timers.set(filename, timer);
402
402
  }
403
403
  handlePeriodic(filename, event) {
404
+ if (event.legacyTimezone) {
405
+ const hostTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
406
+ if (event.legacyTimezone !== hostTimezone) {
407
+ log.logWarning(`Event ${filename} carries a legacy timezone ${event.legacyTimezone} that differs from the host ${hostTimezone}`, "The cron is now interpreted in the host timezone; trigger times may shift.");
408
+ this.appendEventHistory(filename, event, "loaded", "ok", {
409
+ reason: `legacy timezone ${event.legacyTimezone} ignored; using host ${hostTimezone}`,
410
+ });
411
+ }
412
+ }
404
413
  try {
405
- const cron = new Cron(event.schedule, { timezone: event.timezone }, async () => {
414
+ const cron = new Cron(event.schedule, async () => {
406
415
  try {
407
416
  log.logInfo(`Executing periodic event: ${filename}`);
408
417
  this.appendEventHistory(filename, event, "triggered", "ok");
@@ -1,11 +1,12 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { readdir, readFile } from "node:fs/promises";
3
3
  import { join, resolve, sep } from "node:path";
4
- import { isTaskCheckinEvent, isTaskScheduleEvent, parseTaskEventName, taskEventPrefix, taskScheduleEventName, } from "../shared/task-events.js";
4
+ import { isTaskCheckinEvent, isTaskScheduleEvent, parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
5
5
  import { extractTaskTitle, missingStandardTaskSections, normalizeTaskId, readActiveTasks, } from "../shared/task-ledger.js";
6
6
  import { errorMessage } from "../shared/text-utils.js";
7
7
  import { taskBudgetViolation } from "../tasks/control.js";
8
8
  import { claimTaskAttempt, readStoredTask, releaseTaskAttemptClaim, taskBodyHash, writeStoredTask, } from "../tasks/store.js";
9
+ import { readVerificationAttestation } from "../tasks/verification.js";
9
10
  import { parseScheduledEventContent } from "./events.js";
10
11
  function usage() {
11
12
  return `# Tasks
@@ -408,6 +409,7 @@ async function doctor(options) {
408
409
  return "# Task Doctor\n\nNot available: workspaceDir and channelId are required.";
409
410
  }
410
411
  const now = Date.now();
412
+ const hostTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
411
413
  const entries = await readActiveTasks(tasksDir(options.channelDir), now);
412
414
  const activeIds = new Set(entries.map((entry) => entry.id));
413
415
  const archivedIds = await readArchivedTaskIds(options.channelDir);
@@ -450,10 +452,30 @@ async function doctor(options) {
450
452
  if (storedTask && taskBodyHash(storedTask.body) !== control.verification.bodyHash) {
451
453
  issues.push(issue(`tasks/${entry.id}.md changed after its recorded independent PASS.`, `Run a fresh purpose=verify sub-agent and import its attestation before completion.`));
452
454
  }
455
+ else if (control.verification.mode === "independent") {
456
+ const attestationOk = control.verification.runId
457
+ ? await readVerificationAttestation(options.channelDir, control.verification.runId)
458
+ .then((attestation) => attestation.taskId === entry.id && attestation.verdict === "pass")
459
+ .catch(() => false)
460
+ : false;
461
+ if (!attestationOk) {
462
+ issues.push(issue(`tasks/${entry.id}.md records an independent PASS with no matching verifier attestation on disk.`, `Run a fresh purpose=verify sub-agent and import its attestation with task_manage verify before completion.`));
463
+ }
464
+ }
453
465
  }
454
466
  }
455
- if (status === "done" && !isParseableSchedule(events, entry.id)) {
456
- issues.push(issue(`tasks/${entry.id}.md is done but still in the active directory.`, `Ask the agent to archive one-shot task ${entry.id}, or add a parseable .schedule event if it is recurring.`));
467
+ const legacySchedule = eventKey(events, entry.id, "schedule");
468
+ const recurring = Boolean(entry.frontmatter.schedule) || isParseableSchedule(events, entry.id);
469
+ if (status === "done" && !recurring) {
470
+ issues.push(issue(`tasks/${entry.id}.md is done but still in the active directory.`, `Archive one-shot task ${entry.id}, or add a schedule cron with task_manage set if it is recurring.`));
471
+ }
472
+ // Migration (027): recurrence cadence now lives in the task's `schedule` frontmatter.
473
+ // A remaining canonical .schedule event should be folded in and deleted.
474
+ if (legacySchedule && isTaskScheduleEvent(legacySchedule)) {
475
+ issues.push(issue(`events/${legacySchedule.filename} is a legacy task .schedule event; cadence is now native to tasks/${entry.id}.md.`, `Fold its cron "${legacySchedule.event.schedule}" into the task's schedule frontmatter with task_manage set, then delete events/${legacySchedule.filename}.`));
476
+ if (legacySchedule.event.legacyTimezone && legacySchedule.event.legacyTimezone !== hostTimezone) {
477
+ issues.push(issue(`events/${legacySchedule.filename} declares timezone ${legacySchedule.event.legacyTimezone}, which differs from the host ${hostTimezone}.`, `Confirm the intended cadence after folding into frontmatter; the cron will run in the host timezone.`));
478
+ }
457
479
  }
458
480
  const content = await readActiveTaskContent(options.channelDir, entry.id);
459
481
  if (content === undefined) {
@@ -465,9 +487,6 @@ async function doctor(options) {
465
487
  issues.push(issue(`tasks/${entry.id}.md is missing standard section(s): ${missing.join(", ")}.`, `Ask the agent to normalize tasks/${entry.id}.md to the standard task skeleton.`));
466
488
  }
467
489
  }
468
- if (entry.frontmatter.recurrence && !isParseableSchedule(events, entry.id)) {
469
- issues.push(issue(`tasks/${entry.id}.md has recurrence but no parseable ${taskScheduleEventName(options.channelId, entry.id)} event.`, `Create or repair events/${taskScheduleEventName(options.channelId, entry.id)}.json as a periodic event.`));
470
- }
471
490
  if (entry.frontmatter.wake && validWakeMs(entry) === undefined) {
472
491
  issues.push(issue(`tasks/${entry.id}.md has an invalid wake value (${entry.frontmatter.wake}); the native driver will treat it as due.`, `Use task_manage set or progress to replace wake with ISO8601, or clear it if the task should continue now.`));
473
492
  }
@@ -9,10 +9,18 @@ export interface TaskDriverOptions {
9
9
  getSettings: () => PipiclawTaskDriverSettings;
10
10
  /** Master autonomy switch (`tools.tasks.enabled`); re-read every tick. Defaults to on. */
11
11
  isEnabled?: () => boolean;
12
+ /** Test-only override for the idle-sleep cap; production uses `settings.maxSleepMinutes`. */
12
13
  intervalMs?: number;
13
14
  }
14
15
  export declare function discoverTaskChannels(workspaceDir: string, knownChannelIds?: Iterable<string>): Promise<string[]>;
15
16
  export declare function createTaskDriverEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number): DingTalkEvent;
17
+ /**
18
+ * A done recurring task whose schedule has come due. This is the one place the driver
19
+ * wakes a `done` task: to open its next cycle. It uses a `[TASK_CYCLE:...]` tag (not
20
+ * `[TASK_DRIVER:...]`) so the turn is not charged an attempt — start-cycle resets usage
21
+ * anyway, matching the retired periodic-event flow.
22
+ */
23
+ export declare function createCycleStartEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number): DingTalkEvent;
16
24
  /**
17
25
  * Native, token-gated driver for the persistent task ledger.
18
26
  *
@@ -24,11 +32,36 @@ export declare function createTaskDriverEvent(channelId: string, entry: TaskLedg
24
32
  export declare class TaskDriver {
25
33
  private readonly options;
26
34
  private timer;
35
+ private nudgeTimer;
36
+ private loopActive;
27
37
  private running;
28
38
  private nextChannelIndex;
39
+ /** Absolute ms of the next moment worth waking for (min wake/deadline/backoff), recomputed each scan. */
40
+ private nextWakeMs;
29
41
  private readonly attempts;
42
+ /**
43
+ * Last task id dispatched per channel. Cross-channel fairness is handled by
44
+ * `nextChannelIndex`, but within one channel every tick used to pick the first ready
45
+ * candidate in sort order — an actively-progressing task keeps winning that slot forever,
46
+ * starving every other ready task (including its own unlocked dependents) in the same
47
+ * channel. Remembering the last pick and starting the search just after it gives ready
48
+ * candidates in a channel the same round-robin fairness across ticks.
49
+ */
50
+ private readonly lastDispatchedTaskId;
30
51
  constructor(options: TaskDriverOptions);
31
52
  start(): void;
32
53
  stop(): void;
54
+ /**
55
+ * In-process wake: after a turn ends or a task file is written, re-scan promptly instead
56
+ * of waiting out the current sleep. The timer is a hint; the scan re-reads every file, so
57
+ * a stale or missed nudge only costs one capped sleep of latency, never correctness.
58
+ */
59
+ nudge(): void;
60
+ private tick;
61
+ private scheduleNext;
62
+ /** Fold `candidate` into the earliest interesting wake moment. */
63
+ private noteHorizon;
64
+ private collectHorizons;
65
+ private hasLiveScheduleEvent;
33
66
  runOnce(now?: Date): Promise<void>;
34
67
  }
@@ -1,13 +1,21 @@
1
- import { readdir } from "node:fs/promises";
1
+ import { existsSync } from "node:fs";
2
+ import { readdir, readFile } from "node:fs/promises";
2
3
  import { join } from "node:path";
3
4
  import * as log from "../log.js";
4
5
  import { PLAYBOOKS_DIR } from "../paths.js";
6
+ import { isTaskScheduleEvent, taskScheduleEventFilename } from "../shared/task-events.js";
5
7
  import { readActiveTasks } from "../shared/task-ledger.js";
8
+ import { nextTaskWake } from "../shared/task-schedule.js";
6
9
  import { errorMessage } from "../shared/text-utils.js";
7
10
  import { taskBudgetViolation } from "../tasks/control.js";
8
- import { claimTaskAttempt, dependencyState, escalateTask, releaseTaskAttemptClaim } from "../tasks/store.js";
9
- const DEFAULT_SCAN_INTERVAL_MS = 60_000;
11
+ import { claimTaskAttempt, dependencyState, escalateTask, releaseTaskAttemptClaim, updateStoredTask, } from "../tasks/store.js";
12
+ import { parseScheduledEventContent } from "./events.js";
13
+ /** Short debounce so a burst of nudges collapses into a single rescan. */
14
+ const NUDGE_DEBOUNCE_MS = 50;
15
+ /** Never schedule a scan closer than this, so near-now horizons cannot spin the loop. */
16
+ const MIN_SLEEP_MS = 250;
10
17
  const CHANNEL_ID_PATTERN = /^(dm|group)_[A-Za-z0-9._:-]+$/;
18
+ const TERMINAL_STATUSES = new Set(["done", "cancelled", "escalated", "paused"]);
11
19
  function isChannelId(value) {
12
20
  return CHANNEL_ID_PATTERN.test(value);
13
21
  }
@@ -41,6 +49,7 @@ async function taskFingerprint(_channelDir, entry) {
41
49
  entry.frontmatter.readable ? "readable" : "unreadable",
42
50
  entry.frontmatter.status ?? "",
43
51
  entry.frontmatter.wake ?? "",
52
+ entry.frontmatter.schedule ?? "",
44
53
  entry.frontmatter.recurrence ?? "",
45
54
  entry.latestNote ?? "",
46
55
  control?.nextAction ?? "",
@@ -89,6 +98,37 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
89
98
  conversationType: channelId.startsWith("group_") ? "2" : "1",
90
99
  };
91
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. */
122
+ function isCycleStartReady(entry, nowMs) {
123
+ return (entry.frontmatter.status === "done" &&
124
+ Boolean(entry.frontmatter.schedule) &&
125
+ entry.wakeMs !== undefined &&
126
+ entry.wakeMs <= nowMs);
127
+ }
128
+ /** done + schedule but no parseable wake → self-heal target (recompute wake, zero token). */
129
+ function needsWakeHeal(entry) {
130
+ return entry.frontmatter.status === "done" && Boolean(entry.frontmatter.schedule) && entry.wakeMs === undefined;
131
+ }
92
132
  function taskEscalationEvent(channelId, entry, reason, nowMs) {
93
133
  return {
94
134
  type: channelId.startsWith("group_") ? "group" : "dm",
@@ -123,31 +163,114 @@ export class TaskDriver {
123
163
  constructor(options) {
124
164
  this.options = options;
125
165
  this.timer = null;
166
+ this.nudgeTimer = null;
167
+ this.loopActive = false;
126
168
  this.running = false;
127
169
  this.nextChannelIndex = 0;
128
170
  this.attempts = new Map();
171
+ /**
172
+ * Last task id dispatched per channel. Cross-channel fairness is handled by
173
+ * `nextChannelIndex`, but within one channel every tick used to pick the first ready
174
+ * candidate in sort order — an actively-progressing task keeps winning that slot forever,
175
+ * starving every other ready task (including its own unlocked dependents) in the same
176
+ * channel. Remembering the last pick and starting the search just after it gives ready
177
+ * candidates in a channel the same round-robin fairness across ticks.
178
+ */
179
+ this.lastDispatchedTaskId = new Map();
129
180
  }
130
181
  start() {
131
- if (this.timer)
182
+ if (this.loopActive)
132
183
  return;
133
- this.timer = setInterval(() => {
134
- void this.runOnce().catch((error) => {
135
- log.logWarning("Task driver tick failed", errorMessage(error));
136
- });
137
- }, this.options.intervalMs ?? DEFAULT_SCAN_INTERVAL_MS);
138
- this.timer.unref?.();
184
+ this.loopActive = true;
185
+ void this.tick();
139
186
  }
140
187
  stop() {
141
- if (!this.timer)
188
+ this.loopActive = false;
189
+ if (this.timer) {
190
+ clearTimeout(this.timer);
191
+ this.timer = null;
192
+ }
193
+ if (this.nudgeTimer) {
194
+ clearTimeout(this.nudgeTimer);
195
+ this.nudgeTimer = null;
196
+ }
197
+ }
198
+ /**
199
+ * In-process wake: after a turn ends or a task file is written, re-scan promptly instead
200
+ * of waiting out the current sleep. The timer is a hint; the scan re-reads every file, so
201
+ * a stale or missed nudge only costs one capped sleep of latency, never correctness.
202
+ */
203
+ nudge() {
204
+ if (!this.loopActive || this.nudgeTimer)
142
205
  return;
143
- clearInterval(this.timer);
144
- this.timer = null;
206
+ if (this.timer) {
207
+ clearTimeout(this.timer);
208
+ this.timer = null;
209
+ }
210
+ this.nudgeTimer = setTimeout(() => {
211
+ this.nudgeTimer = null;
212
+ void this.tick();
213
+ }, NUDGE_DEBOUNCE_MS);
214
+ this.nudgeTimer.unref?.();
215
+ }
216
+ async tick() {
217
+ try {
218
+ await this.runOnce();
219
+ }
220
+ catch (error) {
221
+ log.logWarning("Task driver tick failed", errorMessage(error));
222
+ }
223
+ this.scheduleNext();
224
+ }
225
+ scheduleNext() {
226
+ if (!this.loopActive || this.timer || this.nudgeTimer)
227
+ return;
228
+ const settings = this.options.getSettings();
229
+ const capMs = this.options.intervalMs ?? settings.maxSleepMinutes * 60_000;
230
+ const untilNext = this.nextWakeMs !== undefined ? this.nextWakeMs - Date.now() : Number.POSITIVE_INFINITY;
231
+ const sleepMs = Math.max(MIN_SLEEP_MS, Math.min(capMs, untilNext));
232
+ this.timer = setTimeout(() => {
233
+ this.timer = null;
234
+ void this.tick();
235
+ }, sleepMs);
236
+ this.timer.unref?.();
237
+ }
238
+ /** Fold `candidate` into the earliest interesting wake moment. */
239
+ noteHorizon(candidate, nowMs) {
240
+ if (candidate === undefined || !Number.isFinite(candidate) || candidate <= nowMs)
241
+ return;
242
+ if (this.nextWakeMs === undefined || candidate < this.nextWakeMs)
243
+ this.nextWakeMs = candidate;
244
+ }
245
+ collectHorizons(entries, nowMs) {
246
+ for (const entry of entries) {
247
+ this.noteHorizon(entry.wakeMs, nowMs);
248
+ const control = entry.frontmatter.control;
249
+ if (control?.deadline && !TERMINAL_STATUSES.has(entry.frontmatter.status ?? "")) {
250
+ this.noteHorizon(new Date(control.deadline).getTime(), nowMs);
251
+ }
252
+ }
253
+ }
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
+ }
145
266
  }
146
267
  async runOnce(now = new Date()) {
147
268
  if (this.options.isEnabled?.() === false || this.running)
148
269
  return;
149
270
  const settings = this.options.getSettings();
271
+ const nowMs = now.getTime();
150
272
  this.running = true;
273
+ this.nextWakeMs = undefined;
151
274
  try {
152
275
  const channels = await discoverTaskChannels(this.options.workspaceDir, this.options.getKnownChannelIds?.());
153
276
  if (channels.length === 0) {
@@ -163,27 +286,41 @@ export class TaskDriver {
163
286
  if (!channelId)
164
287
  continue;
165
288
  const channelDir = join(this.options.workspaceDir, channelId);
166
- const entries = await readActiveTasks(join(channelDir, "tasks"), now.getTime());
289
+ const entries = await readActiveTasks(join(channelDir, "tasks"), nowMs);
167
290
  for (const entry of entries)
168
291
  seen.add(attemptKey(channelId, entry.id));
292
+ this.collectHorizons(entries, nowMs);
169
293
  if (dispatched >= settings.maxDispatchesPerTick || this.options.isChannelActive(channelId))
170
294
  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.
298
+ for (const entry of entries) {
299
+ if (!needsWakeHeal(entry))
300
+ continue;
301
+ const next = nextTaskWake(entry.frontmatter.schedule, now);
302
+ if (!next) {
303
+ log.logWarning(`[${channelId}] Task ${entry.id} has an unparseable schedule`, entry.frontmatter.schedule);
304
+ continue;
305
+ }
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());
311
+ }
171
312
  let governanceHandled = false;
172
313
  for (const candidate of entries) {
173
314
  const status = candidate.frontmatter.status;
174
315
  const control = candidate.frontmatter.control;
175
- if (!control ||
176
- status === "done" ||
177
- status === "cancelled" ||
178
- status === "escalated" ||
179
- status === "paused")
316
+ if (!control || TERMINAL_STATUSES.has(status ?? ""))
180
317
  continue;
181
318
  const dependencies = await dependencyState(channelDir, control.dependsOn, candidate.id);
182
- const escalationReason = taskBudgetViolation(control, now.getTime()) ?? terminalDependencyReason(dependencies.reason);
319
+ const escalationReason = taskBudgetViolation(control, nowMs) ?? terminalDependencyReason(dependencies.reason);
183
320
  if (!escalationReason)
184
321
  continue;
185
322
  governanceHandled = true;
186
- const accepted = await this.options.dispatch(taskEscalationEvent(channelId, candidate, escalationReason, now.getTime()));
323
+ const accepted = await this.options.dispatch(taskEscalationEvent(channelId, candidate, escalationReason, nowMs));
187
324
  if (accepted && (await escalateTask(channelDir, candidate.id, escalationReason))) {
188
325
  dispatched++;
189
326
  lastDispatchOffset = offset;
@@ -193,40 +330,64 @@ export class TaskDriver {
193
330
  }
194
331
  if (governanceHandled)
195
332
  continue;
196
- const candidates = entries.filter((candidate) => candidate.actionable);
333
+ // 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.
335
+ const candidates = entries.filter((candidate) => candidate.actionable || isCycleStartReady(candidate, nowMs));
197
336
  if (candidates.length === 0)
198
337
  continue;
338
+ const lastId = this.lastDispatchedTaskId.get(channelId);
339
+ const lastIndex = lastId ? candidates.findIndex((candidate) => candidate.id === lastId) : -1;
340
+ const rotatedCandidates = lastIndex >= 0
341
+ ? [...candidates.slice(lastIndex + 1), ...candidates.slice(0, lastIndex + 1)]
342
+ : candidates;
199
343
  let entry;
200
- for (const candidate of candidates) {
201
- const control = candidate.frontmatter.control;
202
- if (!control) {
344
+ let isCycleStart = false;
345
+ 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
+ }
203
353
  entry = candidate;
354
+ isCycleStart = false;
204
355
  break;
205
356
  }
206
- const dependencies = await dependencyState(channelDir, control.dependsOn, candidate.id);
207
- if (!dependencies.ready)
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))
208
360
  continue;
209
361
  entry = candidate;
362
+ isCycleStart = true;
210
363
  break;
211
364
  }
212
365
  if (!entry || dispatched >= settings.maxDispatchesPerTick)
213
366
  continue;
214
367
  const key = attemptKey(channelId, entry.id);
215
368
  let fingerprint = await taskFingerprint(channelDir, entry);
216
- if (!isEligible(this.attempts.get(key), fingerprint, now.getTime(), settings))
369
+ if (!isEligible(this.attempts.get(key), fingerprint, nowMs, settings))
217
370
  continue;
218
- const claim = entry.frontmatter.control ? await claimTaskAttempt(channelDir, entry.id, now) : undefined;
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;
219
376
  if (claim) {
220
377
  fingerprint = await taskFingerprint(channelDir, entry);
221
378
  }
222
- const accepted = await this.options.dispatch(createTaskDriverEvent(channelId, entry, now.getTime()));
379
+ const event = isCycleStart
380
+ ? createCycleStartEvent(channelId, entry, nowMs)
381
+ : createTaskDriverEvent(channelId, entry, nowMs);
382
+ const accepted = await this.options.dispatch(event);
223
383
  if (!accepted && claim)
224
384
  await releaseTaskAttemptClaim(channelDir, entry.id, claim, now);
225
- this.attempts.set(key, { fingerprint, atMs: now.getTime(), accepted });
385
+ this.attempts.set(key, { fingerprint, atMs: nowMs, accepted });
386
+ this.lastDispatchedTaskId.set(channelId, entry.id);
226
387
  if (accepted) {
227
388
  dispatched++;
228
389
  lastDispatchOffset = offset;
229
- log.logInfo(`[${channelId}] Task driver enqueued ${entry.id}`);
390
+ log.logInfo(`[${channelId}] Task driver enqueued ${entry.id}${isCycleStart ? " (cycle-start)" : ""}`);
230
391
  }
231
392
  else {
232
393
  log.logWarning(`[${channelId}] Task driver could not enqueue ${entry.id}`, "channel queue unavailable");
@@ -236,6 +397,17 @@ export class TaskDriver {
236
397
  if (!seen.has(key))
237
398
  this.attempts.delete(key);
238
399
  }
400
+ // A backed-off task becomes eligible again at attempt time + its retry delay; wake then
401
+ // so an unchanged ledger is still retried without polling. Changed ledgers arrive via nudge.
402
+ for (const attempt of this.attempts.values()) {
403
+ const delayMinutes = attempt.accepted ? settings.stalledRetryMinutes : settings.continuationDelayMinutes;
404
+ this.noteHorizon(attempt.atMs + delayMinutes * 60_000, nowMs);
405
+ }
406
+ const channelSet = new Set(channels);
407
+ for (const channelId of this.lastDispatchedTaskId.keys()) {
408
+ if (!channelSet.has(channelId))
409
+ this.lastDispatchedTaskId.delete(channelId);
410
+ }
239
411
  this.nextChannelIndex = (start + (lastDispatchOffset >= 0 ? lastDispatchOffset + 1 : 1)) % channels.length;
240
412
  }
241
413
  finally {
@@ -71,6 +71,8 @@ export interface PipiclawTaskDriverSettings {
71
71
  stalledRetryMinutes: number;
72
72
  /** Global enqueue cap per scan, with round-robin fairness across channels. */
73
73
  maxDispatchesPerTick: number;
74
+ /** Cap on idle sleep between scans; also the upper bound on how late a manual edit is noticed. */
75
+ maxSleepMinutes: number;
74
76
  }
75
77
  export interface PipiclawSessionMemorySettings {
76
78
  enabled: boolean;
package/dist/settings.js CHANGED
@@ -42,6 +42,7 @@ const DEFAULT_TASK_DRIVER = {
42
42
  continuationDelayMinutes: 5,
43
43
  stalledRetryMinutes: 60,
44
44
  maxDispatchesPerTick: 4,
45
+ maxSleepMinutes: 15,
45
46
  };
46
47
  const DEFAULT_SESSION_MEMORY = {
47
48
  enabled: true,
@@ -201,10 +202,14 @@ export class PipiclawSettingsManager {
201
202
  const maxDispatchesPerTick = Number.isFinite(configured.maxDispatchesPerTick)
202
203
  ? Math.min(20, Math.max(1, Math.floor(configured.maxDispatchesPerTick)))
203
204
  : DEFAULT_TASK_DRIVER.maxDispatchesPerTick;
205
+ const maxSleepMinutes = Number.isFinite(configured.maxSleepMinutes)
206
+ ? Math.min(60, Math.max(1, Math.floor(configured.maxSleepMinutes)))
207
+ : DEFAULT_TASK_DRIVER.maxSleepMinutes;
204
208
  return {
205
209
  continuationDelayMinutes,
206
210
  stalledRetryMinutes,
207
211
  maxDispatchesPerTick,
212
+ maxSleepMinutes,
208
213
  };
209
214
  }
210
215
  getSessionMemorySettings() {
@@ -14,6 +14,8 @@ export interface TaskFrontmatter {
14
14
  readable: boolean;
15
15
  status?: string;
16
16
  wake?: string;
17
+ /** Five-field cron cadence (host timezone). Present ⇒ this is a recurring task. */
18
+ schedule?: string;
17
19
  recurrence?: string;
18
20
  control?: TaskControl;
19
21
  /** false only when a control field exists but cannot be parsed/validated. */
@@ -90,6 +92,7 @@ export declare function renderStandardTaskBody(input: TaskSkeletonInput): string
90
92
  export interface TaskDocumentFields {
91
93
  status: string;
92
94
  wake?: string;
95
+ schedule?: string;
93
96
  recurrence?: string;
94
97
  control?: TaskControl;
95
98
  }
@@ -1,7 +1,7 @@
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
- const FRONTMATTER_FIELDS = ["status", "wake", "recurrence", "control"];
4
+ const FRONTMATTER_FIELDS = ["status", "wake", "schedule", "recurrence", "control"];
5
5
  const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
6
6
  export const DEFAULT_TASK_MANUAL = "- Follow the DoD, keep the current cycle log updated, and schedule check-ins when waiting.";
7
7
  export const STANDARD_TASK_SECTIONS = [
@@ -198,6 +198,8 @@ export function renderTaskDocument(fields, body) {
198
198
  const lines = ["---", `status: ${fields.status}`];
199
199
  if (fields.wake)
200
200
  lines.push(`wake: ${fields.wake}`);
201
+ if (fields.schedule)
202
+ lines.push(`schedule: ${fields.schedule}`);
201
203
  if (fields.recurrence)
202
204
  lines.push(`recurrence: ${fields.recurrence}`);
203
205
  if (fields.control)
@@ -296,6 +298,44 @@ export function startTaskCycle(content, cycleId) {
296
298
  // A nested history heading would be unusual; inserting directly after the
297
299
  // canonical History heading remains predictable and preserves all older notes.
298
300
  lines.splice(shiftedHistoryStart + 1, 0, ...historyEntry);
301
+ return resetTaskAcceptanceCheckboxes(lines.join("\n"));
302
+ }
303
+ /**
304
+ * Uncheck every "- [x]" under DoD/Verification.
305
+ *
306
+ * `startTaskCycle` archives the previous cycle's log but never touched these boxes, so a
307
+ * periodic task that finished cycle 1 with a fully checked DoD would open cycle 2 with
308
+ * `uncheckedTaskAcceptanceItems` reporting zero unchecked items — the acceptance gate would
309
+ * silently pass on stale evidence from a cycle that no longer exists.
310
+ */
311
+ function resetTaskAcceptanceCheckboxes(content) {
312
+ const lines = content.split("\n");
313
+ let section;
314
+ let sectionLevel = 0;
315
+ for (let index = 0; index < lines.length; index++) {
316
+ const line = lines[index] ?? "";
317
+ const heading = /^(#{1,6})\s+(.+?)\s*$/.exec(line);
318
+ if (heading) {
319
+ const level = heading[1]?.length ?? 7;
320
+ if (matchesTaskSectionTitle(heading[2] ?? "", ["DoD"])) {
321
+ section = "DoD";
322
+ sectionLevel = level;
323
+ }
324
+ else if (matchesTaskSectionTitle(heading[2] ?? "", ["Verification", "验收"])) {
325
+ section = "Verification";
326
+ sectionLevel = level;
327
+ }
328
+ else if (section && level <= sectionLevel) {
329
+ section = undefined;
330
+ }
331
+ continue;
332
+ }
333
+ if (!section)
334
+ continue;
335
+ const checkbox = /^(\s*[-*]\s+)\[[xX]\](\s*.*)$/.exec(line);
336
+ if (checkbox)
337
+ lines[index] = `${checkbox[1]}[ ]${checkbox[2]}`;
338
+ }
299
339
  return lines.join("\n");
300
340
  }
301
341
  /** Last non-empty bullet/line under a "当前周期"/"current cycle" heading. */
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The cron cadence of a recurring task lives in its `schedule` frontmatter key.
3
+ * Cron is always interpreted in the host timezone — tasks (and events) follow the
4
+ * person on their machine, so no `timezone` field or config exists.
5
+ */
6
+ /** A task schedule may fire no more often than this (anti-self-nudge floor). */
7
+ export declare const MIN_TASK_SCHEDULE_INTERVAL_MS: number;
8
+ /**
9
+ * Validate a task `schedule` cron: it must parse (host timezone) and fire no more
10
+ * often than every 30 minutes. Throws with an agent-readable message otherwise.
11
+ * Mirrors the `event_manage` periodic gate so both write paths reject the same cron.
12
+ */
13
+ export declare function validateTaskSchedule(schedule: string): void;
14
+ /**
15
+ * Next occurrence of a task `schedule` strictly after `from`, or undefined when the
16
+ * cron cannot be parsed (the caller decides how to surface that).
17
+ */
18
+ export declare function nextTaskWake(schedule: string, from?: Date): Date | undefined;
@@ -0,0 +1,50 @@
1
+ import { Cron } from "croner";
2
+ import { errorMessage } from "./text-utils.js";
3
+ /**
4
+ * The cron cadence of a recurring task lives in its `schedule` frontmatter key.
5
+ * Cron is always interpreted in the host timezone — tasks (and events) follow the
6
+ * person on their machine, so no `timezone` field or config exists.
7
+ */
8
+ /** A task schedule may fire no more often than this (anti-self-nudge floor). */
9
+ export const MIN_TASK_SCHEDULE_INTERVAL_MS = 30 * 60 * 1000;
10
+ /**
11
+ * Validate a task `schedule` cron: it must parse (host timezone) and fire no more
12
+ * often than every 30 minutes. Throws with an agent-readable message otherwise.
13
+ * Mirrors the `event_manage` periodic gate so both write paths reject the same cron.
14
+ */
15
+ export function validateTaskSchedule(schedule) {
16
+ let runs;
17
+ try {
18
+ const cron = new Cron(schedule);
19
+ runs = cron.nextRuns(3);
20
+ cron.stop();
21
+ }
22
+ catch (error) {
23
+ throw new Error(`schedule "${schedule}" is not a valid cron: ${errorMessage(error)}`);
24
+ }
25
+ if (runs.length === 0) {
26
+ throw new Error(`schedule "${schedule}" never fires; use a valid five-field cron.`);
27
+ }
28
+ const floorMinutes = Math.round(MIN_TASK_SCHEDULE_INTERVAL_MS / 60_000);
29
+ // Fewer than two upcoming runs means no cadence to rate-limit (e.g. a one-off cron); allow it.
30
+ for (let i = 1; i < runs.length; i++) {
31
+ if (runs[i].getTime() - runs[i - 1].getTime() < MIN_TASK_SCHEDULE_INTERVAL_MS) {
32
+ throw new Error(`schedule "${schedule}" must fire no more often than every ${floorMinutes} minutes.`);
33
+ }
34
+ }
35
+ }
36
+ /**
37
+ * Next occurrence of a task `schedule` strictly after `from`, or undefined when the
38
+ * cron cannot be parsed (the caller decides how to surface that).
39
+ */
40
+ export function nextTaskWake(schedule, from = new Date()) {
41
+ try {
42
+ const cron = new Cron(schedule);
43
+ const next = cron.nextRun(from);
44
+ cron.stop();
45
+ return next ?? undefined;
46
+ }
47
+ catch {
48
+ return undefined;
49
+ }
50
+ }
@@ -31,6 +31,7 @@ export async function readStoredTask(channelDir, idInput, includeArchive = false
31
31
  fields: {
32
32
  status: frontmatter.status ?? "open",
33
33
  wake: frontmatter.wake,
34
+ schedule: frontmatter.schedule,
34
35
  recurrence: frontmatter.recurrence,
35
36
  control: frontmatter.control,
36
37
  },
@@ -41,14 +41,6 @@ function parseAction(action) {
41
41
  }
42
42
  throw new Error('Unsupported event action. Use "create", "update", or "delete".');
43
43
  }
44
- function validateTimezone(timezone) {
45
- try {
46
- new Intl.DateTimeFormat(undefined, { timeZone: timezone });
47
- }
48
- catch {
49
- throw new Error(`Invalid timezone: ${timezone}`);
50
- }
51
- }
52
44
  function validateOneShot(event) {
53
45
  const atTime = new Date(event.at).getTime();
54
46
  if (!Number.isFinite(atTime)) {
@@ -59,10 +51,9 @@ function validateOneShot(event) {
59
51
  }
60
52
  }
61
53
  function validatePeriodic(event) {
62
- validateTimezone(event.timezone);
63
54
  let runs;
64
55
  try {
65
- const cron = new Cron(event.schedule, { timezone: event.timezone });
56
+ const cron = new Cron(event.schedule);
66
57
  runs = cron.nextRuns(3);
67
58
  cron.stop();
68
59
  }
@@ -193,6 +184,11 @@ export async function manageEvent(options, request) {
193
184
  }
194
185
  }
195
186
  const event = validateDefinition(request.definition, eventName, options);
187
+ // Persist the canonical form: a tolerated legacy `timezone` is dropped so freshly written
188
+ // events never carry the deprecated field (cron is always host-timezone now).
189
+ if (event.type === "periodic" && event.legacyTimezone !== undefined) {
190
+ delete event.legacyTimezone;
191
+ }
196
192
  const content = `${JSON.stringify(event, null, 2)}\n`;
197
193
  await writeFileAtomically(eventPath, content);
198
194
  return {
@@ -31,6 +31,7 @@ declare const taskManageSchema: Type.TObject<{
31
31
  }>>;
32
32
  status: Type.TOptional<Type.TUnion<Type.TLiteral<"blocked" | "paused" | "open" | "in-progress" | "awaiting-user">[]>>;
33
33
  wake: Type.TOptional<Type.TString>;
34
+ schedule: Type.TOptional<Type.TString>;
34
35
  recurrence: Type.TOptional<Type.TString>;
35
36
  note: Type.TOptional<Type.TString>;
36
37
  verifierRunId: Type.TOptional<Type.TString>;
@@ -67,6 +68,7 @@ export interface TaskManageRequest {
67
68
  manual?: string;
68
69
  status?: string;
69
70
  wake?: string;
71
+ schedule?: string;
70
72
  recurrence?: string;
71
73
  note?: string;
72
74
  verificationPlan?: string;
@@ -6,6 +6,7 @@ import { parseScheduledEventContent } from "../runtime/events.js";
6
6
  import { writeFileAtomically } from "../shared/atomic-file.js";
7
7
  import { isTaskScheduleEvent, taskEventPrefix, taskScheduleEventFilename } from "../shared/task-events.js";
8
8
  import { appendCurrentCycleNote, normalizeTaskId, parseTaskFrontmatter, readActiveTasks, renderStandardTaskBody, renderTaskDocument, startTaskCycle, taskBody, uncheckedTaskAcceptanceItems, } from "../shared/task-ledger.js";
9
+ import { nextTaskWake, validateTaskSchedule } from "../shared/task-schedule.js";
9
10
  import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
10
11
  import { applyTaskControlPatch, createDefaultTaskControl, invalidateTaskApproval, invalidateTaskVerification, resetTaskControlForCycle, } from "../tasks/control.js";
11
12
  import { dependencyState, readStoredTask, taskBodyHash } from "../tasks/store.js";
@@ -35,7 +36,9 @@ const taskControlSchema = Type.Object({
35
36
  maxTokens: Type.Optional(Type.Number({ minimum: 0, description: "0 clears this budget." })),
36
37
  maxCostUsd: Type.Optional(Type.Number({ minimum: 0, description: "0 clears this budget." })),
37
38
  maxWallTimeMinutes: Type.Optional(Type.Number({ minimum: 0, description: "0 clears this budget." })),
38
- verificationMode: Type.Optional(Type.Union([Type.Literal("evidence"), Type.Literal("independent")])),
39
+ verificationMode: Type.Optional(Type.Union([Type.Literal("evidence"), Type.Literal("independent")], {
40
+ description: 'On create, defaults to "evidence" (maker self-checks the DoD against concrete evidence). Set "independent" only when the task produces a checkable artifact (code, config, a runnable command) that a separate read-only verifier sub-agent can inspect — for research/writing/reminder-style tasks, "evidence" is cheaper and just as trustworthy.',
41
+ })),
39
42
  worktreePath: Type.Optional(Type.String({ description: "Owned worktree path; empty clears it." })),
40
43
  worktreeBranch: Type.Optional(Type.String()),
41
44
  });
@@ -67,7 +70,11 @@ const taskManageSchema = Type.Object({
67
70
  wake: Type.Optional(Type.String({
68
71
  description: "ISO8601 earliest-recheck time for create/progress/set; empty string clears it. The native task driver resumes it; no .checkin event is needed.",
69
72
  })),
70
- recurrence: Type.Optional(Type.String({ description: "Annotation only (e.g. 每周一); empty string clears it." })),
73
+ schedule: Type.Optional(Type.String({
74
+ description: "Five-field cron cadence (host timezone) that makes this a recurring task; empty string clears it. " +
75
+ "On done, the driver sleeps the task until the next occurrence and re-opens it with start-cycle. Min every 30 minutes.",
76
+ })),
77
+ recurrence: Type.Optional(Type.String({ description: "Human annotation only (e.g. 每周一); empty string clears it." })),
71
78
  note: Type.Optional(Type.String({
72
79
  description: "Required for progress: concise Current Cycle entry covering what changed, evidence observed, and the next step.",
73
80
  })),
@@ -147,7 +154,11 @@ function renderTaskSkeleton(request) {
147
154
  const title = requiredField(request.title, "title", "create");
148
155
  const goal = requiredField(request.goal, "goal", "create");
149
156
  const dod = requiredField(request.dod, "dod", "create");
150
- const mode = request.control?.verificationMode ?? "independent";
157
+ // Independent verification is a real tax (an extra dispatch round plus a verifier
158
+ // sub-agent run) that only pays off when there is something a read-only verifier can
159
+ // actually check. Default to evidence (maker self-checks the DoD); the tool schema asks
160
+ // the model to opt into independent explicitly for tasks with a checkable artifact.
161
+ const mode = request.control?.verificationMode ?? "evidence";
151
162
  const control = applyTaskControlPatch(createDefaultTaskControl(mode), request.control ?? {});
152
163
  const fields = applySet({ status: normalizeCreateStatus(request.status), control }, request);
153
164
  const body = renderStandardTaskBody({
@@ -181,6 +192,7 @@ async function readTaskDocument(taskPath, id, allowControlRepair = false) {
181
192
  fields: {
182
193
  status: frontmatter.status ?? "open",
183
194
  wake: frontmatter.wake,
195
+ schedule: frontmatter.schedule,
184
196
  recurrence: frontmatter.recurrence,
185
197
  control: frontmatter.control,
186
198
  },
@@ -211,6 +223,16 @@ function applySet(fields, request) {
211
223
  next.wake = trimmed;
212
224
  }
213
225
  }
226
+ if (request.schedule !== undefined) {
227
+ const trimmed = request.schedule.trim();
228
+ if (trimmed === "") {
229
+ next.schedule = undefined;
230
+ }
231
+ else {
232
+ validateTaskSchedule(trimmed);
233
+ next.schedule = trimmed;
234
+ }
235
+ }
214
236
  if (request.recurrence !== undefined) {
215
237
  const trimmed = request.recurrence.trim();
216
238
  next.recurrence = trimmed === "" ? undefined : trimmed;
@@ -218,6 +240,12 @@ function applySet(fields, request) {
218
240
  if (request.control !== undefined) {
219
241
  next.control = applyTaskControlPatch(next.control ?? createDefaultTaskControl("evidence"), request.control);
220
242
  }
243
+ // A done recurring task sleeps until its next occurrence; changing the cadence of a
244
+ // task that is currently done recomputes that wake in the same atomic write.
245
+ if (next.status === "done" && next.schedule) {
246
+ const nextWake = nextTaskWake(next.schedule);
247
+ next.wake = nextWake ? nextWake.toISOString() : undefined;
248
+ }
221
249
  return next;
222
250
  }
223
251
  async function validateTaskRelations(options, id, fields) {
@@ -331,6 +359,23 @@ async function cleanupTaskEvents(options, id, preserveSchedule = true) {
331
359
  }
332
360
  return { deleted, hasSchedule };
333
361
  }
362
+ /**
363
+ * Migration compat: a task may still carry a legacy canonical `.schedule` periodic event
364
+ * as its cadence truth (pre-027). `start-cycle` accepts such a task even without `schedule`
365
+ * frontmatter so an in-flight migration is not blocked mid-cycle.
366
+ */
367
+ async function hasLegacyScheduleEvent(options, id) {
368
+ const eventPath = join(eventsDir(options), taskScheduleEventFilename(options.channelId, id));
369
+ if (!existsSync(eventPath))
370
+ return false;
371
+ try {
372
+ const type = parseScheduledEventContent(await readFile(eventPath, "utf-8"), taskScheduleEventFilename(options.channelId, id)).type;
373
+ return isTaskScheduleEvent({ use: "schedule", event: { type } });
374
+ }
375
+ catch {
376
+ return false;
377
+ }
378
+ }
334
379
  async function setTask(options, request) {
335
380
  if (!request.id)
336
381
  throw new Error('action "set" requires an id.');
@@ -468,6 +513,27 @@ async function verifyTask(options, request) {
468
513
  notice: `任务 \`${id}\` 独立验收结果:${attestation.verdict.toUpperCase()}(run: ${runId})。`,
469
514
  };
470
515
  }
516
+ /**
517
+ * `verify` writes control.verification from a real attestation file, but the task Markdown
518
+ * itself is writable by the agent's own write/edit tools — nothing stops it from hand-crafting
519
+ * a "passed" verification block that was never backed by a real verifier run. Re-check the
520
+ * attestation file on the consuming side (done/doctor) too, not just at import time.
521
+ */
522
+ async function assertVerificationAttestationMatches(channelDir, id, verification) {
523
+ if (!verification.runId) {
524
+ throw new Error(`Task "${id}" has no verification run id; rerun task_manage verify before done.`);
525
+ }
526
+ const attestation = await readVerificationAttestation(channelDir, verification.runId);
527
+ if (attestation.taskId !== id) {
528
+ throw new Error(`Verification run "${verification.runId}" belongs to task "${attestation.taskId}", not "${id}"; rerun verification.`);
529
+ }
530
+ if (attestation.verdict !== "pass") {
531
+ throw new Error(`Verification run "${verification.runId}" recorded a FAIL, not a PASS; rerun verification.`);
532
+ }
533
+ if (attestation.bodyHash !== verification.bodyHash) {
534
+ throw new Error(`Task "${id}" control.verification.bodyHash does not match the attestation for run "${verification.runId}"; rerun task_manage verify.`);
535
+ }
536
+ }
471
537
  async function unfinishedChildren(options, parentId) {
472
538
  const entries = await readActiveTasks(tasksDir(options));
473
539
  return entries
@@ -505,7 +571,7 @@ async function doneTask(options, request) {
505
571
  }
506
572
  if (fields.control?.verification.mode === "independent") {
507
573
  const verification = fields.control.verification;
508
- if (verification.status !== "passed" || !verification.bodyHash) {
574
+ if (verification.status !== "passed" || !verification.bodyHash || !verification.runId) {
509
575
  throw new Error(`Task "${id}" requires an independent PASS. Run a purpose=verify sub-agent, then task_manage verify with its run id.`);
510
576
  }
511
577
  if (verification.bodyHash !== taskBodyHash(body)) {
@@ -517,18 +583,26 @@ async function doneTask(options, request) {
517
583
  throw new Error(`Task "${id}" artifacts changed after its independent PASS; rerun verification before done.`);
518
584
  }
519
585
  }
586
+ await assertVerificationAttestationMatches(options.channelDir, id, verification);
520
587
  }
521
588
  const bodyWithEvidence = appendCompletionEvidence(body, request);
522
589
  if (fields.control) {
523
590
  fields.control.lastOutcome = "verified";
524
591
  fields.control.blockedReason = undefined;
525
592
  }
526
- await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "done" }, bodyWithEvidence));
593
+ // A recurring task (schedule frontmatter) sleeps in place until its next occurrence;
594
+ // the wake is computed here so "done + wake" fully describes "asleep until next cycle".
595
+ const doneFields = fields.schedule
596
+ ? { ...fields, status: "done", wake: nextTaskWake(fields.schedule)?.toISOString() }
597
+ : { ...fields, status: "done" };
598
+ await writeFileAtomically(taskPath, renderTaskFile(doneFields, bodyWithEvidence));
527
599
  const { deleted, hasSchedule } = await cleanupTaskEvents(options, id);
528
- // Periodic task → sleeps in place until its schedule fires next; one-shot → archive.
600
+ // Recurring (schedule frontmatter, or a legacy .schedule event during migration) →
601
+ // sleeps in place; one-shot → archive.
602
+ const recurring = Boolean(fields.schedule) || hasSchedule;
529
603
  let archived = false;
530
604
  let finalPath = taskPath;
531
- if (!hasSchedule) {
605
+ if (!recurring) {
532
606
  const archiveDir = join(dir, "archive");
533
607
  await mkdir(archiveDir, { recursive: true });
534
608
  finalPath = join(archiveDir, `${id}.md`);
@@ -590,8 +664,8 @@ async function startCycleTask(options, request) {
590
664
  if (fields.status !== "done") {
591
665
  throw new Error(`Task "${id}" is ${fields.status}, not done. Finish, cancel, or explicitly resolve the current cycle before starting another.`);
592
666
  }
593
- if (!fields.recurrence) {
594
- throw new Error(`Task "${id}" is not marked recurring. Add recurrence and its canonical .schedule event before starting a cycle.`);
667
+ if (!fields.schedule && !(await hasLegacyScheduleEvent(options, id))) {
668
+ throw new Error(`Task "${id}" is not recurring. Add a schedule cron with task_manage set before starting a cycle.`);
595
669
  }
596
670
  const control = fields.control ? resetTaskControlForCycle(fields.control, cycleId) : undefined;
597
671
  const nextBody = startTaskCycle(body, cycleId);
@@ -661,6 +735,7 @@ export function createTaskManageTool(options) {
661
735
  control: args.control,
662
736
  status: args.status,
663
737
  wake: args.wake,
738
+ schedule: args.schedule,
664
739
  recurrence: args.recurrence,
665
740
  note: args.note,
666
741
  verifierRunId: args.verifierRunId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oyasmi/pipiclaw",
3
- "version": "0.8.8-beta.1",
3
+ "version": "0.8.8-beta.2",
4
4
  "description": "An AI assistant runtime for coding and team workflows, with DingTalk AI Cards, sub-agents, memory, and scheduled events.",
5
5
  "type": "module",
6
6
  "bin": {