@oyasmi/pipiclaw 0.8.10 → 0.8.11-beta.3

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 (106) hide show
  1. package/README.md +3 -3
  2. package/dist/agent/channel-runner.d.ts +11 -0
  3. package/dist/agent/channel-runner.js +58 -27
  4. package/dist/agent/commands.js +2 -3
  5. package/dist/agent/effect-ledger.d.ts +1 -1
  6. package/dist/agent/effect-ledger.js +2 -2
  7. package/dist/agent/prompt/sections.js +3 -3
  8. package/dist/agent/runner-factory.d.ts +2 -0
  9. package/dist/agent/session-events.js +1 -1
  10. package/dist/main.js +6 -0
  11. package/dist/memory/commands.js +6 -1
  12. package/dist/memory/consolidation.d.ts +8 -1
  13. package/dist/memory/consolidation.js +34 -6
  14. package/dist/memory/extraction.d.ts +11 -3
  15. package/dist/memory/extraction.js +19 -6
  16. package/dist/memory/files.d.ts +2 -0
  17. package/dist/memory/files.js +14 -0
  18. package/dist/memory/maintenance-gates.d.ts +3 -0
  19. package/dist/memory/maintenance-gates.js +5 -2
  20. package/dist/memory/maintenance-jobs.js +19 -2
  21. package/dist/memory/maintenance-state.d.ts +29 -0
  22. package/dist/memory/maintenance-state.js +100 -8
  23. package/dist/memory/metadata.d.ts +9 -0
  24. package/dist/memory/metadata.js +5 -0
  25. package/dist/memory/probation.d.ts +21 -0
  26. package/dist/memory/probation.js +48 -0
  27. package/dist/memory/promotion.d.ts +26 -1
  28. package/dist/memory/promotion.js +34 -4
  29. package/dist/memory/recall.js +38 -19
  30. package/dist/memory/session-corpus.js +12 -11
  31. package/dist/memory/session-search.js +25 -6
  32. package/dist/memory/sidecar-worker.js +2 -0
  33. package/dist/memory/task-digest.d.ts +3 -2
  34. package/dist/memory/task-digest.js +22 -8
  35. package/dist/models/auth-cli.d.ts +25 -0
  36. package/dist/models/auth-cli.js +344 -0
  37. package/dist/models/login-ui.d.ts +35 -0
  38. package/dist/models/login-ui.js +145 -0
  39. package/dist/models/provider-login.d.ts +41 -0
  40. package/dist/models/provider-login.js +126 -0
  41. package/dist/models/utils.d.ts +6 -0
  42. package/dist/models/utils.js +10 -0
  43. package/dist/playbooks/memory-and-learning.md +7 -1
  44. package/dist/playbooks/outbound-media.md +7 -33
  45. package/dist/playbooks/runtime-orientation.md +2 -0
  46. package/dist/playbooks/task-closeout.md +22 -35
  47. package/dist/playbooks/task-delegation.md +13 -35
  48. package/dist/playbooks/task-driving.md +36 -56
  49. package/dist/playbooks/task-planning.md +26 -45
  50. package/dist/runtime/bootstrap.js +48 -14
  51. package/dist/runtime/delivery.js +8 -2
  52. package/dist/runtime/dingtalk.d.ts +6 -3
  53. package/dist/runtime/dingtalk.js +6 -39
  54. package/dist/runtime/events.js +4 -3
  55. package/dist/runtime/proxy.d.ts +36 -0
  56. package/dist/runtime/proxy.js +68 -0
  57. package/dist/runtime/store.d.ts +8 -2
  58. package/dist/runtime/store.js +12 -6
  59. package/dist/runtime/task-commands.d.ts +0 -2
  60. package/dist/runtime/task-commands.js +99 -112
  61. package/dist/runtime/task-driver.d.ts +5 -0
  62. package/dist/runtime/task-driver.js +155 -53
  63. package/dist/runtime/task-migration.d.ts +9 -0
  64. package/dist/runtime/task-migration.js +75 -2
  65. package/dist/security/command-guard.js +51 -17
  66. package/dist/security/path-guard.js +72 -14
  67. package/dist/shared/open-browser.d.ts +6 -0
  68. package/dist/shared/open-browser.js +22 -0
  69. package/dist/shared/recoverable-error.d.ts +1 -1
  70. package/dist/shared/recoverable-error.js +1 -1
  71. package/dist/subagents/tool.js +2 -0
  72. package/dist/tasks/control.d.ts +38 -67
  73. package/dist/tasks/control.js +90 -152
  74. package/dist/tasks/ledger.d.ts +104 -22
  75. package/dist/tasks/ledger.js +419 -56
  76. package/dist/tasks/store.d.ts +11 -10
  77. package/dist/tasks/store.js +58 -27
  78. package/dist/tasks/transitions.d.ts +8 -36
  79. package/dist/tasks/transitions.js +29 -54
  80. package/dist/tasks/verification.d.ts +2 -2
  81. package/dist/tools/index.d.ts +2 -0
  82. package/dist/tools/index.js +1 -0
  83. package/dist/tools/memory-manage.js +8 -1
  84. package/dist/tools/read.js +19 -5
  85. package/dist/tools/registry.d.ts +1 -0
  86. package/dist/tools/registry.js +1 -0
  87. package/dist/tools/task-manage/lifecycle.d.ts +1 -7
  88. package/dist/tools/task-manage/lifecycle.js +76 -77
  89. package/dist/tools/task-manage/schema.d.ts +10 -5
  90. package/dist/tools/task-manage/schema.js +35 -21
  91. package/dist/tools/task-manage/shared.d.ts +1 -1
  92. package/dist/tools/task-manage/shared.js +29 -30
  93. package/dist/tools/task-manage/types.d.ts +7 -1
  94. package/dist/tools/task-manage/verification.d.ts +4 -5
  95. package/dist/tools/task-manage/verification.js +43 -15
  96. package/dist/tools/task-manage.d.ts +1 -1
  97. package/dist/tools/task-manage.js +9 -9
  98. package/dist/tui/app.js +1 -2
  99. package/dist/tui/commands.d.ts +1 -1
  100. package/dist/tui/commands.js +1 -1
  101. package/dist/tui/turn-controller.d.ts +1 -1
  102. package/dist/usage/ledger.d.ts +1 -1
  103. package/dist/usage/ledger.js +47 -22
  104. package/dist/usage/render.d.ts +1 -1
  105. package/dist/usage/render.js +8 -6
  106. package/package.json +7 -6
@@ -1,10 +1,20 @@
1
1
  import { readdir, readFile, stat } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
4
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
4
5
  import { nextTaskWake } from "../shared/task-schedule.js";
5
- import { parseTaskControl, taskPriorityRank } from "./control.js";
6
- import { normalizeStoredStatus, TERMINAL_TASK_STATUSES, wasLegacyEscalated } from "./transitions.js";
7
- const FRONTMATTER_FIELDS = ["status", "wake", "schedule", "recurrence", "control"];
6
+ import { createDefaultTaskControl, parseTaskControl, taskPriorityRank } from "./control.js";
7
+ import { normalizeStoredStatus, wasLegacyEscalated } from "./transitions.js";
8
+ const FRONTMATTER_FIELDS = [
9
+ "status",
10
+ "enabled",
11
+ "wake",
12
+ "schedule",
13
+ "recurrence",
14
+ "outcome",
15
+ "closedAt",
16
+ "control",
17
+ ];
8
18
  const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
9
19
  export const DEFAULT_TASK_MANUAL = "- Follow the DoD, keep the current cycle log updated, and schedule check-ins when waiting.";
10
20
  export const STANDARD_TASK_SECTIONS = [
@@ -15,6 +25,12 @@ export const STANDARD_TASK_SECTIONS = [
15
25
  { label: "Current Cycle", names: ["Current Cycle", "当前周期"] },
16
26
  { label: "History", names: ["History", "历史"] },
17
27
  ];
28
+ /**
29
+ * `## Plan` is a deliberately optional section (spec 037, D2) — it is not part of
30
+ * `STANDARD_TASK_SECTIONS`, so `missingStandardTaskSections` never flags its absence. A two-step
31
+ * task or any pre-existing task simply has no Plan.
32
+ */
33
+ const PLAN_SECTION_NAMES = ["Plan", "计划"];
18
34
  /** Recurring task files are working context, not an unbounded audit log. */
19
35
  export const MAX_INLINE_TASK_HISTORY_ENTRIES = 8;
20
36
  export const MAX_INLINE_TASK_HISTORY_CHARS = 24 * 1024;
@@ -41,33 +57,205 @@ export function taskBody(content) {
41
57
  return after === -1 ? "" : content.slice(after + 1);
42
58
  }
43
59
  /**
44
- * The task's *contract* segment: the body up to (excluding) the "Current Cycle" heading —
45
- * i.e. the H1 title, Goal, DoD (with its checkbox state), Manual and Verification (spec 029, D4).
60
+ * The task's *contract* segment: the body up to (excluding) whichever of "Plan" or "Current
61
+ * Cycle" appears first — i.e. the H1 title, Goal, DoD (with its checkbox state), Manual and
62
+ * Verification (spec 029, D4).
46
63
  *
47
- * Verification PASS and external approval bind to this segment, not the whole body, so routine
48
- * `progress` notes (Current Cycle) and appended History/Completion Evidence never invalidate a
49
- * PASS or approval — only a change to what the task promises to do and how it is checked does.
50
- * A body without a Current Cycle heading (non-standard) falls back to the whole body.
64
+ * Verification PASS binds to this segment, not the whole body, so routine `progress` notes
65
+ * (Current Cycle, and — spec 037, D1 — Plan step status) never invalidate a PASS; only a change
66
+ * to what the task promises to do and how it is checked does.
67
+ * Plan is deliberately excluded from the contract even though it always precedes Current Cycle
68
+ * in a freshly rendered skeleton: it is the task's *means*, not its promise, and is meant to be
69
+ * revised without re-triggering verification. This also means a task with an existing PASS can
70
+ * have `## Plan` inserted between Verification and Current Cycle with the contract segment
71
+ * unchanged byte-for-byte, as long as nothing before it changed.
72
+ * A body without either heading (non-standard) falls back to the whole body.
51
73
  */
52
74
  export function taskContractSegment(body) {
53
75
  const lines = body.split("\n");
54
76
  for (let index = 0; index < lines.length; index++) {
55
77
  const match = /^#{1,6}\s+(.+?)\s*$/.exec(lines[index] ?? "");
56
- if (match && matchesTaskSectionTitle(match[1] ?? "", ["Current Cycle", "当前周期"])) {
78
+ if (match &&
79
+ (matchesTaskSectionTitle(match[1] ?? "", PLAN_SECTION_NAMES) ||
80
+ matchesTaskSectionTitle(match[1] ?? "", ["Current Cycle", "当前周期"]))) {
57
81
  return lines.slice(0, index).join("\n").replace(/\s+$/, "");
58
82
  }
59
83
  }
60
84
  return body;
61
85
  }
62
- /** Parse the leading `---` frontmatter block into the three known fields. */
86
+ const PLAN_STEP_STATUS_BY_MARKER = {
87
+ " ": "todo",
88
+ x: "done",
89
+ X: "done",
90
+ "!": "blocked",
91
+ "~": "dropped",
92
+ };
93
+ const PLAN_CHECKBOX_LINE = /^\s*[-*]\s+\[([ xX!~])\]\s+(.*)$/;
94
+ const PLAN_STEP_ID_PREFIX = /^(P\d+)[.、)]?\s+(\S.*)$/i;
95
+ const PLAN_DOD_REF_SUFFIX = /(?:→|->)\s*dod:\s*([\d,\s]+)\s*$/i;
96
+ function parsePlanStepLine(line, lineIndex, fallbackId) {
97
+ const checkbox = PLAN_CHECKBOX_LINE.exec(line);
98
+ if (!checkbox)
99
+ return undefined;
100
+ const status = PLAN_STEP_STATUS_BY_MARKER[checkbox[1] ?? " "] ?? "todo";
101
+ let rest = (checkbox[2] ?? "").trim();
102
+ let dodRefs = [];
103
+ const dodMatch = PLAN_DOD_REF_SUFFIX.exec(rest);
104
+ if (dodMatch) {
105
+ dodRefs = (dodMatch[1] ?? "")
106
+ .split(",")
107
+ .map((part) => Number.parseInt(part.trim(), 10))
108
+ .filter((n) => Number.isInteger(n) && n > 0);
109
+ rest = rest.slice(0, dodMatch.index).trim();
110
+ }
111
+ const idMatch = PLAN_STEP_ID_PREFIX.exec(rest);
112
+ const id = idMatch ? (idMatch[1] ?? fallbackId).toUpperCase() : fallbackId;
113
+ const text = idMatch ? (idMatch[2] ?? "").trim() : rest;
114
+ return { id, status, text, dodRefs, lineIndex };
115
+ }
116
+ /**
117
+ * Parse the optional `## Plan` section: a fourth, hand-maintained layer between the contract
118
+ * (Goal/DoD/Manual/Verification) and the append-only Current Cycle/History log (spec 037, D2).
119
+ *
120
+ * Four checkbox states — `[ ]` todo, `[x]` done, `[!]` blocked, `[~]` dropped — and no separate
121
+ * "doing" marker: the current step is *derived* (first `todo`/`blocked` in document order), not
122
+ * self-reported, for the same reason `task-driver.ts`'s fingerprint excludes the model's own
123
+ * progress notes — a runtime-derived signal cannot be talked into lying about itself.
124
+ *
125
+ * Returns `undefined` when there is no Plan heading, or the heading has no checkbox lines under
126
+ * it (nothing to summarize) — both read the same as "this task has no Plan yet".
127
+ */
128
+ export function parseTaskPlan(content) {
129
+ const lines = content.split("\n");
130
+ let sectionStart = -1;
131
+ let sectionLevel = 0;
132
+ for (let index = 0; index < lines.length; index++) {
133
+ const match = /^(#{1,6})\s+(.+?)\s*$/.exec(lines[index] ?? "");
134
+ if (!match || !matchesTaskSectionTitle(match[2] ?? "", PLAN_SECTION_NAMES))
135
+ continue;
136
+ sectionStart = index;
137
+ sectionLevel = match[1]?.length ?? 0;
138
+ break;
139
+ }
140
+ if (sectionStart === -1)
141
+ return undefined;
142
+ let sectionEnd = lines.length;
143
+ for (let index = sectionStart + 1; index < lines.length; index++) {
144
+ const match = /^(#{1,6})\s+/.exec(lines[index] ?? "");
145
+ if (match && (match[1]?.length ?? 7) <= sectionLevel) {
146
+ sectionEnd = index;
147
+ break;
148
+ }
149
+ }
150
+ const steps = [];
151
+ let position = 0;
152
+ for (let index = sectionStart + 1; index < sectionEnd; index++) {
153
+ const line = lines[index] ?? "";
154
+ if (!/^\s*[-*]\s+\[/.test(line))
155
+ continue;
156
+ position++;
157
+ const step = parsePlanStepLine(line, index, `P${position}`);
158
+ if (step)
159
+ steps.push(step);
160
+ }
161
+ if (steps.length === 0)
162
+ return undefined;
163
+ return {
164
+ steps,
165
+ total: steps.filter((step) => step.status !== "dropped").length,
166
+ done: steps.filter((step) => step.status === "done").length,
167
+ current: steps.find((step) => step.status === "todo" || step.status === "blocked"),
168
+ };
169
+ }
170
+ const PLAN_STATUS_MARKER = { todo: " ", done: "x", blocked: "!", dropped: "~" };
171
+ function renderPlanStepLine(id, status, text, dodRefs = []) {
172
+ const suffix = dodRefs.length > 0 ? ` → dod:${dodRefs.join(",")}` : "";
173
+ return `- [${PLAN_STATUS_MARKER[status]}] ${id} ${text}${suffix}`;
174
+ }
175
+ /** Insert an empty "## Plan" heading immediately before "## Current Cycle" (spec 037, D3). */
176
+ function insertEmptyPlanSection(body) {
177
+ const lines = body.split("\n");
178
+ for (let index = 0; index < lines.length; index++) {
179
+ const match = /^(#{1,6})\s+(.+?)\s*$/.exec(lines[index] ?? "");
180
+ if (match && matchesTaskSectionTitle(match[2] ?? "", ["Current Cycle", "当前周期"])) {
181
+ lines.splice(index, 0, "## Plan", "");
182
+ return lines.join("\n");
183
+ }
184
+ }
185
+ throw new RecoverableToolError('Task body has no "Current Cycle" section, so a Plan cannot be inserted; normalize the task skeleton with edit first.');
186
+ }
187
+ /**
188
+ * Update or append Plan steps by id (spec 037, D3). An id that already exists gets its
189
+ * status/text patched in place, preserving its `dod` refs and position; an unseen id is appended
190
+ * as a new step (`text` is then required — there is nothing sensible to append otherwise). A task
191
+ * with no `## Plan` section yet gets an empty one inserted before Current Cycle first, so the
192
+ * very first `planSteps` call on a task is also the one that creates its Plan.
193
+ *
194
+ * The returned `summary` is deliberately not a new persisted field (see the file-level doc on
195
+ * `TaskPlanSummary`): it is meant to be appended to the caller's own Current Cycle note, so the
196
+ * change history rides on the log `startTaskCycle` already folds into History — no second,
197
+ * unconsumed revision counter.
198
+ */
199
+ export function applyTaskPlanPatch(body, patches) {
200
+ if (patches.length === 0)
201
+ return { body, summary: "" };
202
+ let working = parseTaskPlan(body) ? body : insertEmptyPlanSection(body);
203
+ const deltas = [];
204
+ for (const patch of patches) {
205
+ const trimmedId = patch.id.trim();
206
+ if (!trimmedId)
207
+ throw new RecoverableToolError("A planSteps entry's id must not be empty.");
208
+ const existing = parseTaskPlan(working)?.steps.find((step) => step.id.toUpperCase() === trimmedId.toUpperCase());
209
+ if (existing) {
210
+ const lines = working.split("\n");
211
+ const nextStatus = patch.status ?? existing.status;
212
+ const nextText = patch.text?.trim() || existing.text;
213
+ lines[existing.lineIndex] = renderPlanStepLine(existing.id, nextStatus, nextText, existing.dodRefs);
214
+ working = lines.join("\n");
215
+ deltas.push(patch.status ? `${existing.id}→${patch.status}` : `${existing.id} updated`);
216
+ continue;
217
+ }
218
+ const text = patch.text?.trim();
219
+ if (!text) {
220
+ throw new RecoverableToolError(`Plan step "${trimmedId}" does not exist yet; adding a new step requires text.`);
221
+ }
222
+ const id = trimmedId.toUpperCase();
223
+ const lines = working.split("\n");
224
+ let sectionStart = -1;
225
+ let sectionLevel = 0;
226
+ for (let index = 0; index < lines.length; index++) {
227
+ const match = /^(#{1,6})\s+(.+?)\s*$/.exec(lines[index] ?? "");
228
+ if (match && matchesTaskSectionTitle(match[2] ?? "", PLAN_SECTION_NAMES)) {
229
+ sectionStart = index;
230
+ sectionLevel = match[1]?.length ?? 0;
231
+ break;
232
+ }
233
+ }
234
+ let insertAt = lines.length;
235
+ for (let index = sectionStart + 1; index < lines.length; index++) {
236
+ const match = /^(#{1,6})\s+/.exec(lines[index] ?? "");
237
+ if (match && (match[1]?.length ?? 7) <= sectionLevel) {
238
+ insertAt = index;
239
+ break;
240
+ }
241
+ }
242
+ while (insertAt > sectionStart + 1 && (lines[insertAt - 1] ?? "").trim() === "")
243
+ insertAt--;
244
+ lines.splice(insertAt, 0, renderPlanStepLine(id, patch.status ?? "todo", text));
245
+ working = lines.join("\n");
246
+ deltas.push(`+${id} ${text}`);
247
+ }
248
+ return { body: working, summary: deltas.length > 0 ? `plan: ${deltas.join("; ")}` : "" };
249
+ }
250
+ /** Parse the leading frontmatter block and normalize legacy v1 fields in memory. */
63
251
  export function parseTaskFrontmatter(content) {
64
252
  if (!content.startsWith("---"))
65
- return { readable: false };
253
+ return { readable: false, enabled: true };
66
254
  const end = content.indexOf("\n---", 3);
67
255
  if (end === -1)
68
- return { readable: false };
256
+ return { readable: false, enabled: true };
69
257
  const block = content.slice(3, end);
70
- const frontmatter = { readable: true };
258
+ const frontmatter = { readable: true, enabled: true };
71
259
  for (const line of block.split("\n")) {
72
260
  const idx = line.indexOf(":");
73
261
  if (idx === -1)
@@ -95,19 +283,43 @@ export function parseTaskFrontmatter(content) {
95
283
  }
96
284
  }
97
285
  }
98
- else {
286
+ else if (key === "enabled") {
287
+ frontmatter.enabled = value !== "false";
288
+ }
289
+ else if (key === "outcome") {
290
+ if (value === "completed" || value === "cancelled")
291
+ frontmatter.archiveOutcome = value;
292
+ }
293
+ else if (key === "closedAt") {
294
+ frontmatter.closedAt = value || undefined;
295
+ }
296
+ else if (key === "status" || key === "wake" || key === "schedule" || key === "recurrence") {
99
297
  frontmatter[key] = value || undefined;
100
298
  }
101
299
  }
102
300
  }
103
- // Canonicalise the (possibly legacy) status on read. A legacy `escalated` file is read as
104
- // `paused` by the deterministic governor; the nuance is preserved in control.pausedBy so
105
- // nothing downstream has to know the old name.
301
+ // Canonicalise the possibly legacy status on read. Terminal v1 values are marked as archive
302
+ // outcomes so an active-directory scan can never execute them before startup migration moves
303
+ // them. A legacy recurring terminal is the v2 sleeping state.
106
304
  const rawStatus = frontmatter.status;
305
+ frontmatter.rawStatus = rawStatus;
107
306
  if (frontmatter.readable) {
108
- frontmatter.status = normalizeStoredStatus(rawStatus);
109
- if (wasLegacyEscalated(rawStatus) && frontmatter.control && frontmatter.control.pausedBy === undefined) {
110
- frontmatter.control.pausedBy = "governor";
307
+ if (rawStatus === "done" && !frontmatter.schedule)
308
+ frontmatter.archiveOutcome = "completed";
309
+ if (rawStatus === "cancelled")
310
+ frontmatter.archiveOutcome = "cancelled";
311
+ frontmatter.status = normalizeStoredStatus(rawStatus, Boolean(frontmatter.schedule));
312
+ if (rawStatus === "paused" || wasLegacyEscalated(rawStatus)) {
313
+ frontmatter.enabled = false;
314
+ frontmatter.control ??= createDefaultTaskControl();
315
+ if (frontmatter.control && !frontmatter.control.stop) {
316
+ frontmatter.control.stop = {
317
+ by: wasLegacyEscalated(rawStatus) ? "governor" : "user",
318
+ reason: frontmatter.control.blockedReason ??
319
+ `Task stopped by ${wasLegacyEscalated(rawStatus) ? "governor" : "user"}.`,
320
+ at: formatLocalTime(),
321
+ };
322
+ }
111
323
  }
112
324
  }
113
325
  return frontmatter;
@@ -122,7 +334,7 @@ export function parseTaskFrontmatter(content) {
122
334
  * and only that signal may resume it. Without this the runtime's own recommended shape for
123
335
  * delegating work (start a blocking wait as a `bash async` job, park the task, end the turn)
124
336
  * was re-dispatched the instant the turn ended, found the job still running, answered
125
- * `[SILENT]`, and after three such wakes got paused by the governor. A `waiting` task that
337
+ * `[SILENT]`, and after three such wakes was disabled by the governor. A `waiting` task that
126
338
  * *does* carry a wake is an ordinary timed re-check and stays gated on that wake; an
127
339
  * unparseable wake still fails open so a hand-edited file surfaces rather than parks forever.
128
340
  */
@@ -135,9 +347,13 @@ export function isTaskActionable(frontmatter, now) {
135
347
  return true;
136
348
  if (frontmatter.controlReadable === false)
137
349
  return true;
138
- // status is already canonicalised by parseTaskFrontmatter.
139
- if (TERMINAL_TASK_STATUSES.has(frontmatter.status ?? ""))
350
+ if (frontmatter.archiveOutcome || frontmatter.enabled === false)
140
351
  return false;
352
+ // status is already canonicalised by parseTaskFrontmatter.
353
+ if (frontmatter.status === "sleeping") {
354
+ const wakeAt = parseWakeMs(frontmatter);
355
+ return wakeAt !== undefined && wakeAt <= now;
356
+ }
141
357
  if (isTaskParked(frontmatter))
142
358
  return false;
143
359
  const wakeAt = parseWakeMs(frontmatter);
@@ -180,7 +396,7 @@ export function missingStandardTaskSections(content) {
180
396
  * Without the "no checklist items" case, a DoD written as prose or a numbered
181
397
  * list (no `- [ ]` anywhere) makes this function return an empty array —
182
398
  * indistinguishable from "everything is checked" — which would silently let
183
- * `task_manage candidate`/`done` through with nothing ever actually verified.
399
+ * `task_manage request-verification`/`complete` through with nothing ever actually verified.
184
400
  */
185
401
  export function uncheckedTaskAcceptanceItems(content) {
186
402
  const unchecked = [];
@@ -218,14 +434,48 @@ export function uncheckedTaskAcceptanceItems(content) {
218
434
  }
219
435
  }
220
436
  if (dodHasContent && !dodHasCheckbox) {
221
- unchecked.push('DoD has no checklist items — rewrite it as "- [ ] ..." acceptance items before requesting verification or done.');
437
+ unchecked.push('DoD has no checklist items — rewrite it as "- [ ] ..." acceptance items before requesting verification or complete.');
222
438
  }
223
439
  return unchecked;
224
440
  }
441
+ /**
442
+ * Count of checkbox items (checked or not) under the DoD heading, for cross-referencing a Plan
443
+ * step's `→ dod:N` refs (spec 037, D4 — `/tasks doctor`'s drift checks).
444
+ */
445
+ export function countTaskDodItems(content) {
446
+ let inDod = false;
447
+ let sectionLevel = 0;
448
+ let count = 0;
449
+ for (const line of content.split("\n")) {
450
+ const heading = /^(#{1,6})\s+(.+?)\s*$/.exec(line);
451
+ if (heading) {
452
+ const level = heading[1]?.length ?? 7;
453
+ if (matchesTaskSectionTitle(heading[2] ?? "", ["DoD"])) {
454
+ inDod = true;
455
+ sectionLevel = level;
456
+ }
457
+ else if (inDod && level <= sectionLevel) {
458
+ inDod = false;
459
+ }
460
+ continue;
461
+ }
462
+ if (inDod && /^\s*[-*]\s+\[[ xX]\]/.test(line))
463
+ count++;
464
+ }
465
+ return count;
466
+ }
467
+ /** A plain plan-step line gets an auto-assigned `P<n>` id unless it already starts with one. */
468
+ function ensurePlanStepId(line, fallbackIndex) {
469
+ return PLAN_STEP_ID_PREFIX.test(line) ? line : `P${fallbackIndex} ${line}`;
470
+ }
225
471
  export function renderStandardTaskBody(input) {
226
472
  const manual = input.manual?.trim() || DEFAULT_TASK_MANUAL;
227
473
  const verificationPlan = input.verificationPlan?.trim() ||
228
474
  "- Check every DoD item against concrete evidence.\n- Run the relevant deterministic checks before declaring PASS.";
475
+ const planLines = (input.plan ?? "")
476
+ .split("\n")
477
+ .map((line) => line.trim())
478
+ .filter(Boolean);
229
479
  return [
230
480
  `# ${input.title}`,
231
481
  "",
@@ -244,6 +494,11 @@ export function renderStandardTaskBody(input) {
244
494
  ...(input.verificationRequired ? ["Independent verification: required"] : []),
245
495
  verificationPlan,
246
496
  "",
497
+ // Plan is optional (spec 037, D2/D3): omitted entirely when create was not given one,
498
+ // rather than rendering an empty section a doctor check would then have to special-case.
499
+ ...(planLines.length > 0
500
+ ? ["## Plan", ...planLines.map((line, index) => `- [ ] ${ensurePlanStepId(line, index + 1)}`), ""]
501
+ : []),
247
502
  "## Current Cycle",
248
503
  "- Created; next step: start work and append progress here before ending each turn.",
249
504
  "",
@@ -252,28 +507,100 @@ export function renderStandardTaskBody(input) {
252
507
  ].join("\n");
253
508
  }
254
509
  /**
255
- * The single time rule, enforced on the write path (spec 029, D1).
256
- *
257
- * The rule "a done recurring task's next wake is its cron next occurrence" becomes a
258
- * construction-time invariant: every `done + schedule` document has its `wake` set to the
259
- * next occurrence on the write path, regardless of any prior/stale/unparseable value. Once
260
- * the cycle comes due the runtime reopens it (status leaves `done`, so this no longer fires).
261
- * Every other field combination is left verbatim — `create`'s first-cycle seed (status
262
- * `active`) and an explicit `wake` on a non-recurring task are honoured. When the cron cannot
263
- * be parsed the existing value is kept so the corruption surfaces rather than being erased.
510
+ * Enforce the v2 write-path invariants. Runtime due transitions are intentionally separate: a
511
+ * waiting task is first written active, and a sleeping task is first opened into a cycle, before
512
+ * the driver dispatches anything.
264
513
  */
265
- export function normalizeTaskFields(fields) {
266
- if (fields.status !== "done" || !fields.schedule)
267
- return fields;
268
- const next = nextTaskWake(fields.schedule);
269
- if (!next)
270
- return fields;
271
- const wake = formatLocalTime(next);
272
- return wake === fields.wake ? fields : { ...fields, wake };
514
+ export function normalizeTaskFields(fields, now = new Date()) {
515
+ const next = {
516
+ ...fields,
517
+ status: normalizeStoredStatus(fields.status, Boolean(fields.schedule)),
518
+ enabled: fields.enabled !== false,
519
+ };
520
+ if (next.outcome) {
521
+ // Archive documents are never driver inputs. Do not carry a live stop marker into them.
522
+ next.enabled = undefined;
523
+ return next;
524
+ }
525
+ if (next.enabled === true && next.control?.stop) {
526
+ next.control = { ...next.control, stop: undefined };
527
+ }
528
+ if (next.enabled === false) {
529
+ // Pausing is intentionally lossless: do not normalize status, wake, or schedule while disabled.
530
+ // A hand-written disabled task without a stop receipt is diagnosed rather than given a fabricated actor.
531
+ return next;
532
+ }
533
+ const nowMs = now.getTime();
534
+ const wakeMs = next.wake ? parseLocalTime(next.wake) : undefined;
535
+ if (next.status === "active") {
536
+ if (wakeMs !== undefined && wakeMs > nowMs) {
537
+ next.status = "waiting";
538
+ next.control = next.control ? { ...next.control, waitingFor: "time" } : undefined;
539
+ }
540
+ else {
541
+ next.wake = undefined;
542
+ next.control = next.control ? { ...next.control, waitingFor: undefined } : undefined;
543
+ }
544
+ }
545
+ if (next.status === "waiting") {
546
+ if (next.wake && wakeMs !== undefined) {
547
+ const waitingFor = next.control?.waitingFor === "external-signal" ? "external-signal" : "time";
548
+ next.control = next.control ? { ...next.control, waitingFor } : undefined;
549
+ }
550
+ else if (!next.wake && next.control) {
551
+ const waitingFor = next.control.waitingFor === "time" ? "external-signal" : next.control.waitingFor;
552
+ next.control = { ...next.control, waitingFor: waitingFor ?? "external-signal" };
553
+ }
554
+ }
555
+ if (next.status === "sleeping" && next.schedule) {
556
+ const occurrence = next.wake ? parseLocalTime(next.wake) : undefined;
557
+ const validOccurrence = occurrence !== undefined && nextTaskWake(next.schedule, new Date(occurrence - 1))?.getTime() === occurrence;
558
+ if (!validOccurrence) {
559
+ const upcoming = nextTaskWake(next.schedule, now);
560
+ if (upcoming)
561
+ next.wake = formatLocalTime(upcoming);
562
+ }
563
+ if (next.control?.waitingFor) {
564
+ next.control = { ...next.control, waitingFor: undefined };
565
+ }
566
+ }
567
+ return next;
568
+ }
569
+ /**
570
+ * Whether an open recurring cycle has already crossed its next schedule occurrence.
571
+ * The runtime must keep working on the old cycle rather than opening a concurrent one.
572
+ * Cycle ids intentionally carry the local calendar date; the optional suffix handles a
573
+ * same-day manual reopen deterministically.
574
+ */
575
+ export function recurringTaskMissedOccurrence(fields, now = new Date()) {
576
+ if (!fields.schedule || (fields.status !== "active" && fields.status !== "waiting") || !fields.control?.cycleId) {
577
+ return false;
578
+ }
579
+ const match = /^cycle-(\d{4})-(\d{2})-(\d{2})(?:-(\d+))?$/.exec(fields.control.cycleId);
580
+ if (!match)
581
+ return false;
582
+ const start = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]));
583
+ if (!Number.isFinite(start.getTime()))
584
+ return false;
585
+ let occurrence = nextTaskWake(fields.schedule, new Date(start.getTime() - 1));
586
+ const count = match[4] ? Number.parseInt(match[4], 10) : 1;
587
+ for (let index = 1; occurrence && index < count; index++) {
588
+ occurrence = nextTaskWake(fields.schedule, occurrence);
589
+ }
590
+ const next = occurrence ? nextTaskWake(fields.schedule, occurrence) : undefined;
591
+ return next !== undefined && next.getTime() <= now.getTime();
273
592
  }
274
593
  export function renderTaskDocument(fields, rawBody) {
275
594
  const document = normalizeTaskFields(fields);
276
- const lines = ["---", `status: ${document.status}`];
595
+ const lines = ["---"];
596
+ if (document.outcome) {
597
+ lines.push(`outcome: ${document.outcome}`);
598
+ if (document.closedAt)
599
+ lines.push(`closedAt: ${document.closedAt}`);
600
+ }
601
+ else {
602
+ lines.push(`status: ${document.status}`, `enabled: ${document.enabled !== false}`);
603
+ }
277
604
  if (document.wake)
278
605
  lines.push(`wake: ${document.wake}`);
279
606
  if (document.schedule)
@@ -323,7 +650,7 @@ export function appendCurrentCycleNote(content, note) {
323
650
  * Upsert the completion evidence subsection inside Current Cycle.
324
651
  *
325
652
  * Evidence is part of the cycle log, not a new top-level section. This makes the next
326
- * `startTaskCycle` fold it into the matching History entry and prevents repeated `done`
653
+ * `startTaskCycle` fold it into the matching History entry and prevents repeated completion
327
654
  * attempts from appending duplicate evidence blocks.
328
655
  */
329
656
  export function upsertCurrentCycleCompletionEvidence(content, evidenceLines) {
@@ -484,7 +811,7 @@ function compactTaskHistory(content, alreadyOmitted = false) {
484
811
  * instead of asking the model to hand-edit headings and risk appending future
485
812
  * checkpoints to the previous cycle.
486
813
  */
487
- export function startTaskCycle(content, cycleId) {
814
+ export function startTaskCycle(content, cycleId, archivePrevious = true) {
488
815
  const normalizedCycleId = cycleId.trim();
489
816
  if (!normalizedCycleId)
490
817
  throw new Error("Cycle id must not be empty.");
@@ -543,16 +870,14 @@ export function startTaskCycle(content, cycleId) {
543
870
  ];
544
871
  lines.splice(currentStart, currentEnd - currentStart, ...replacement);
545
872
  const shiftedHistoryStart = historyStart + replacement.length - (currentEnd - currentStart);
546
- const historyEntry = [
547
- `### ${previousHeading} — closed`,
548
- ...(previous ? [previous] : ["- No checkpoint was recorded in the previous cycle."]),
549
- "",
550
- ];
551
- // A nested history heading would be unusual; inserting directly after the
552
- // canonical History heading remains predictable and preserves all older notes.
553
- lines.splice(shiftedHistoryStart + 1, 0, ...historyEntry);
873
+ if (archivePrevious && previous && !/^[-*]\s+Created; next step:/i.test(previous)) {
874
+ const historyEntry = [`### ${previousHeading} — closed`, previous, ""];
875
+ // A nested history heading would be unusual; inserting directly after the
876
+ // canonical History heading remains predictable and preserves all older notes.
877
+ lines.splice(shiftedHistoryStart + 1, 0, ...historyEntry);
878
+ }
554
879
  const compacted = compactTaskHistory(lines.join("\n"), legacy.blocks.length > 1);
555
- return resetTaskAcceptanceCheckboxes(compacted);
880
+ return resetPlanStepCheckboxes(resetTaskAcceptanceCheckboxes(compacted));
556
881
  }
557
882
  /**
558
883
  * Uncheck every "- [x]" under DoD/Verification.
@@ -592,6 +917,41 @@ function resetTaskAcceptanceCheckboxes(content) {
592
917
  }
593
918
  return lines.join("\n");
594
919
  }
920
+ /**
921
+ * Reset `## Plan` steps for a new cycle: `[x]` done and `[!]` blocked both go back to `[ ]`
922
+ * todo, exactly like `resetTaskAcceptanceCheckboxes` — a stale "done" step from the previous
923
+ * cycle must not silently pass as still true. `[~]` dropped is left alone: that step was
924
+ * deliberately abandoned, not merely finished, and a new cycle should not resurrect it.
925
+ */
926
+ function resetPlanStepCheckboxes(content) {
927
+ const lines = content.split("\n");
928
+ let sectionStart = -1;
929
+ let sectionLevel = 0;
930
+ for (let index = 0; index < lines.length; index++) {
931
+ const match = /^(#{1,6})\s+(.+?)\s*$/.exec(lines[index] ?? "");
932
+ if (!match || !matchesTaskSectionTitle(match[2] ?? "", PLAN_SECTION_NAMES))
933
+ continue;
934
+ sectionStart = index;
935
+ sectionLevel = match[1]?.length ?? 0;
936
+ break;
937
+ }
938
+ if (sectionStart === -1)
939
+ return content;
940
+ let sectionEnd = lines.length;
941
+ for (let index = sectionStart + 1; index < lines.length; index++) {
942
+ const match = /^(#{1,6})\s+/.exec(lines[index] ?? "");
943
+ if (match && (match[1]?.length ?? 7) <= sectionLevel) {
944
+ sectionEnd = index;
945
+ break;
946
+ }
947
+ }
948
+ for (let index = sectionStart + 1; index < sectionEnd; index++) {
949
+ const checkbox = /^(\s*[-*]\s+)\[[xX!]\](\s*.*)$/.exec(lines[index] ?? "");
950
+ if (checkbox)
951
+ lines[index] = `${checkbox[1]}[ ]${checkbox[2]}`;
952
+ }
953
+ return lines.join("\n");
954
+ }
595
955
  /** Last non-empty bullet/line under a "当前周期"/"current cycle" heading. */
596
956
  function extractLatestNote(content) {
597
957
  const lines = content.split("\n");
@@ -626,6 +986,8 @@ function parseWakeMs(frontmatter) {
626
986
  export function compareTaskEntries(a, b) {
627
987
  if (a.actionable !== b.actionable)
628
988
  return a.actionable ? -1 : 1;
989
+ if (a.frontmatter.enabled !== b.frontmatter.enabled)
990
+ return a.frontmatter.enabled ? -1 : 1;
629
991
  if (a.actionable && b.actionable) {
630
992
  const ap = taskPriorityRank(a.frontmatter.control?.priority ?? "normal");
631
993
  const bp = taskPriorityRank(b.frontmatter.control?.priority ?? "normal");
@@ -655,6 +1017,7 @@ function toEntry(id, content, now) {
655
1017
  actionable: isTaskActionable(frontmatter, now),
656
1018
  wakeMs: parseWakeMs(frontmatter),
657
1019
  latestNote: extractLatestNote(content),
1020
+ plan: parseTaskPlan(content),
658
1021
  };
659
1022
  }
660
1023
  const parseCache = new Map();
@@ -700,7 +1063,7 @@ export async function readActiveTasks(tasksDir, now = Date.now()) {
700
1063
  entries.push({
701
1064
  id,
702
1065
  title: id,
703
- frontmatter: { readable: false },
1066
+ frontmatter: { readable: false, enabled: true },
704
1067
  actionable: true,
705
1068
  });
706
1069
  }