@oyasmi/pipiclaw 0.7.7 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +23 -2
  2. package/dist/agent/channel-runner.d.ts +4 -4
  3. package/dist/agent/channel-runner.js +25 -23
  4. package/dist/agent/commands.js +7 -2
  5. package/dist/agent/job-manager.d.ts +5 -5
  6. package/dist/agent/prompt-builder.d.ts +3 -13
  7. package/dist/agent/prompt-builder.js +49 -159
  8. package/dist/agent/run-queue.js +2 -1
  9. package/dist/agent/runner-factory.d.ts +1 -2
  10. package/dist/agent/runner-factory.js +2 -2
  11. package/dist/agent/status-render.d.ts +0 -7
  12. package/dist/agent/status-render.js +8 -3
  13. package/dist/agent/types.d.ts +2 -0
  14. package/dist/agent/workspace-resources.d.ts +1 -1
  15. package/dist/agent/workspace-resources.js +3 -15
  16. package/dist/executor.d.ts +20 -0
  17. package/dist/{sandbox.js → executor.js} +3 -95
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/log.d.ts +1 -1
  21. package/dist/log.js +1 -2
  22. package/dist/memory/files.js +0 -0
  23. package/dist/memory/lifecycle.js +6 -5
  24. package/dist/memory/maintenance-jobs.d.ts +0 -1
  25. package/dist/memory/maintenance-jobs.js +2 -2
  26. package/dist/memory/maintenance-state.js +2 -1
  27. package/dist/memory/post-turn-review.d.ts +0 -1
  28. package/dist/memory/post-turn-review.js +4 -4
  29. package/dist/memory/scheduler.d.ts +0 -1
  30. package/dist/memory/scheduler.js +2 -2
  31. package/dist/memory/session.js +2 -2
  32. package/dist/memory/task-digest.js +17 -0
  33. package/dist/paths.d.ts +2 -0
  34. package/dist/paths.js +11 -0
  35. package/dist/playbooks/catalog.d.ts +9 -0
  36. package/dist/playbooks/catalog.js +44 -0
  37. package/dist/playbooks/event-scheduling.md +43 -0
  38. package/dist/playbooks/memory-and-learning.md +45 -0
  39. package/dist/playbooks/runtime-orientation.md +48 -0
  40. package/dist/playbooks/task-closeout.md +45 -0
  41. package/dist/playbooks/task-delegation.md +44 -0
  42. package/dist/playbooks/task-driving.md +43 -0
  43. package/dist/playbooks/task-planning.md +47 -0
  44. package/dist/playbooks/task-recurring.md +42 -0
  45. package/dist/playbooks/task-repair.md +43 -0
  46. package/dist/runtime/bootstrap.d.ts +12 -11
  47. package/dist/runtime/bootstrap.js +81 -57
  48. package/dist/runtime/delivery.js +4 -3
  49. package/dist/runtime/dingtalk.d.ts +2 -0
  50. package/dist/runtime/dingtalk.js +15 -14
  51. package/dist/runtime/durable-dispatch.d.ts +30 -0
  52. package/dist/runtime/durable-dispatch.js +172 -0
  53. package/dist/runtime/event-commands.js +4 -4
  54. package/dist/runtime/events.d.ts +5 -3
  55. package/dist/runtime/events.js +17 -13
  56. package/dist/runtime/task-commands.d.ts +6 -0
  57. package/dist/runtime/task-commands.js +292 -6
  58. package/dist/runtime/task-driver.d.ts +32 -0
  59. package/dist/runtime/task-driver.js +268 -0
  60. package/dist/security/config.js +2 -1
  61. package/dist/security/network.js +9 -2
  62. package/dist/security/path-guard.js +12 -24
  63. package/dist/security/types.d.ts +0 -1
  64. package/dist/settings.d.ts +12 -0
  65. package/dist/settings.js +30 -0
  66. package/dist/shared/jsonl-appender.js +2 -1
  67. package/dist/shared/task-ledger.d.ts +35 -0
  68. package/dist/shared/task-ledger.js +229 -15
  69. package/dist/shared/text-utils.d.ts +1 -0
  70. package/dist/shared/text-utils.js +3 -0
  71. package/dist/subagents/discovery.js +3 -2
  72. package/dist/subagents/tool.d.ts +15 -3
  73. package/dist/subagents/tool.js +194 -17
  74. package/dist/tasks/artifact-subject.d.ts +6 -0
  75. package/dist/tasks/artifact-subject.js +29 -0
  76. package/dist/tasks/control.d.ts +83 -0
  77. package/dist/tasks/control.js +293 -0
  78. package/dist/tasks/store.d.ts +32 -0
  79. package/dist/tasks/store.js +142 -0
  80. package/dist/tasks/verification.d.ts +23 -0
  81. package/dist/tasks/verification.js +69 -0
  82. package/dist/tools/bash.d.ts +1 -1
  83. package/dist/tools/bash.js +3 -5
  84. package/dist/tools/command-optimizer.d.ts +1 -1
  85. package/dist/tools/command-optimizer.js +4 -6
  86. package/dist/tools/config.js +4 -3
  87. package/dist/tools/edit.d.ts +1 -1
  88. package/dist/tools/edit.js +0 -0
  89. package/dist/tools/event-manage.d.ts +0 -1
  90. package/dist/tools/event-manage.js +9 -14
  91. package/dist/tools/grep.d.ts +1 -1
  92. package/dist/tools/grep.js +4 -6
  93. package/dist/tools/index.d.ts +1 -3
  94. package/dist/tools/index.js +1 -4
  95. package/dist/tools/read.d.ts +1 -1
  96. package/dist/tools/read.js +1 -2
  97. package/dist/tools/registry.d.ts +2 -3
  98. package/dist/tools/registry.js +5 -11
  99. package/dist/tools/skill-manage.d.ts +0 -1
  100. package/dist/tools/skill-manage.js +7 -14
  101. package/dist/tools/task-manage.d.ts +37 -4
  102. package/dist/tools/task-manage.js +398 -39
  103. package/dist/tools/write-content.d.ts +1 -1
  104. package/dist/tools/write-content.js +0 -1
  105. package/dist/tools/write.d.ts +1 -1
  106. package/dist/tui/app.d.ts +0 -2
  107. package/dist/tui/app.js +12 -7
  108. package/dist/tui/cli.d.ts +0 -2
  109. package/dist/tui/cli.js +3 -25
  110. package/dist/tui/turn-controller.d.ts +7 -3
  111. package/dist/tui/turn-controller.js +9 -6
  112. package/dist/web/client.js +2 -1
  113. package/package.json +2 -2
  114. package/dist/sandbox.d.ts +0 -42
@@ -5,40 +5,94 @@ import { Type } from "typebox";
5
5
  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
- import { normalizeTaskId, parseTaskFrontmatter, readActiveTasks, renderStandardTaskBody, taskBody, } from "../shared/task-ledger.js";
9
- const SETTABLE_STATUSES = ["open", "in-progress", "awaiting-user", "blocked"];
8
+ import { appendCurrentCycleNote, normalizeTaskId, parseTaskFrontmatter, readActiveTasks, renderStandardTaskBody, renderTaskDocument, startTaskCycle, taskBody, uncheckedTaskAcceptanceItems, } from "../shared/task-ledger.js";
9
+ import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
10
+ import { applyTaskControlPatch, createDefaultTaskControl, invalidateTaskApproval, invalidateTaskVerification, resetTaskControlForCycle, } from "../tasks/control.js";
11
+ import { dependencyState, readStoredTask, taskBodyHash } from "../tasks/store.js";
12
+ import { readVerificationAttestation } from "../tasks/verification.js";
13
+ const SETTABLE_STATUSES = ["open", "in-progress", "awaiting-user", "blocked", "paused"];
14
+ const taskControlSchema = Type.Object({
15
+ priority: Type.Optional(Type.Union([Type.Literal("low"), Type.Literal("normal"), Type.Literal("high"), Type.Literal("critical")])),
16
+ deadline: Type.Optional(Type.String({ description: "ISO8601 deadline; empty string clears it." })),
17
+ nextAction: Type.Optional(Type.String({ description: "Concrete next executable step; empty string clears it." })),
18
+ lastOutcome: Type.Optional(Type.Union([
19
+ Type.Literal("pending"),
20
+ Type.Literal("running"),
21
+ Type.Literal("progress"),
22
+ Type.Literal("blocked"),
23
+ Type.Literal("failed"),
24
+ Type.Literal("verified"),
25
+ ])),
26
+ blockedReason: Type.Optional(Type.String({ description: "Why work cannot currently proceed; empty clears it." })),
27
+ parent: Type.Optional(Type.String({ description: "Parent task id; empty clears it." })),
28
+ dependsOn: Type.Optional(Type.Array(Type.String(), { description: "Task ids that must be done first." })),
29
+ isolation: Type.Optional(Type.Union([Type.Literal("shared"), Type.Literal("worktree")])),
30
+ sideEffects: Type.Optional(Type.Union([Type.Literal("read-only"), Type.Literal("workspace"), Type.Literal("external")])),
31
+ externalApproval: Type.Optional(Type.Union([Type.Literal("not-required"), Type.Literal("required")], {
32
+ description: 'External approval can only be granted by a user with "/tasks approve <id>".',
33
+ })),
34
+ maxAttempts: Type.Optional(Type.Integer({ minimum: 1 })),
35
+ maxTokens: Type.Optional(Type.Number({ minimum: 0, description: "0 clears this budget." })),
36
+ maxCostUsd: Type.Optional(Type.Number({ minimum: 0, description: "0 clears this budget." })),
37
+ 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
+ worktreePath: Type.Optional(Type.String({ description: "Owned worktree path; empty clears it." })),
40
+ worktreeBranch: Type.Optional(Type.String()),
41
+ });
10
42
  const taskManageSchema = Type.Object({
11
43
  label: Type.String({ description: "Brief description of the ledger change (shown to the user)" }),
12
- action: Type.Union([Type.Literal("create"), Type.Literal("set"), Type.Literal("done"), Type.Literal("list")], {
13
- description: '"create" writes a standard task skeleton; "set" updates status/wake/recurrence; "done" closes it out and requires summary/evidence; "list" returns active tasks.',
44
+ action: Type.Union([
45
+ Type.Literal("create"),
46
+ Type.Literal("progress"),
47
+ Type.Literal("set"),
48
+ Type.Literal("verify"),
49
+ Type.Literal("done"),
50
+ Type.Literal("cancel"),
51
+ Type.Literal("start-cycle"),
52
+ Type.Literal("candidate"),
53
+ Type.Literal("list"),
54
+ ], {
55
+ description: '"create" writes a governed task; "progress" atomically checkpoints work; "candidate" requests independent verification; "set" repairs metadata; "verify" imports an independent verifier attestation; "done" closes verified work; "cancel" closes abandoned work; "start-cycle" opens a completed recurring task; "list" returns tasks.',
14
56
  }),
15
- id: Type.Optional(Type.String({ description: "Task id (filename without .md). Required for create/set/done." })),
57
+ id: Type.Optional(Type.String({ description: "Task id (filename without .md). Required for create/progress/set/done." })),
16
58
  title: Type.Optional(Type.String({ description: "Required for create: task title used as the H1 heading." })),
17
59
  goal: Type.Optional(Type.String({ description: "Required for create: concise task goal." })),
18
- dod: Type.Optional(Type.String({ description: "Required for create: acceptance criteria / definition of done." })),
60
+ dod: Type.Optional(Type.String({
61
+ description: 'Required for create: acceptance criteria as Markdown checklist items, one per line, e.g. "- [ ] <criterion>". Plain prose or a numbered list without checkboxes is rejected — candidate/done can only verify items that are checkable.',
62
+ })),
19
63
  manual: Type.Optional(Type.String({ description: "Optional for create: initial operating steps or checklist." })),
20
- status: Type.Optional(Type.Union(SETTABLE_STATUSES.map((status) => Type.Literal(status)), { description: "New status for create/set. To close a task use action done, not status." })),
64
+ verificationPlan: Type.Optional(Type.String({ description: "Optional for create: deterministic checks the verifier must perform." })),
65
+ control: Type.Optional(taskControlSchema),
66
+ status: Type.Optional(Type.Union(SETTABLE_STATUSES.map((status) => Type.Literal(status)), { description: "New status for create/progress/set. To close a task use action done, not status." })),
21
67
  wake: Type.Optional(Type.String({
22
- description: "ISO8601 earliest-recheck time for set; empty string clears it. Keep in sync with any .checkin event.",
68
+ description: "ISO8601 earliest-recheck time for create/progress/set; empty string clears it. The native task driver resumes it; no .checkin event is needed.",
23
69
  })),
24
70
  recurrence: Type.Optional(Type.String({ description: "Annotation only (e.g. 每周一); empty string clears it." })),
71
+ note: Type.Optional(Type.String({
72
+ description: "Required for progress: concise Current Cycle entry covering what changed, evidence observed, and the next step.",
73
+ })),
74
+ verifierRunId: Type.Optional(Type.String({ description: "Required for verify: run id returned by a purpose=verify sub-agent." })),
25
75
  summary: Type.Optional(Type.String({ description: "Required for done: concise completion summary." })),
26
76
  evidence: Type.Optional(Type.String({
27
77
  description: "Required for done: verification evidence (tests, commands, review result, external confirmation, or a clear not-run reason).",
28
78
  })),
29
79
  residualRisk: Type.Optional(Type.String({ description: "Optional for done: remaining risk or follow-up note." })),
80
+ reason: Type.Optional(Type.String({ description: "Required for cancel: why the task was abandoned." })),
81
+ cycleId: Type.Optional(Type.String({ description: "Required for start-cycle: stable id for the newly opened recurring cycle." })),
30
82
  });
31
83
  function parseAction(action) {
32
- if (action === "create" || action === "set" || action === "done" || action === "list") {
84
+ if (action === "create" ||
85
+ action === "progress" ||
86
+ action === "candidate" ||
87
+ action === "set" ||
88
+ action === "verify" ||
89
+ action === "done" ||
90
+ action === "cancel" ||
91
+ action === "start-cycle" ||
92
+ action === "list") {
33
93
  return action;
34
94
  }
35
- throw new Error('Unsupported task action. Use "create", "set", "done", or "list".');
36
- }
37
- function toWorkspacePath(options, hostPath) {
38
- if (hostPath.startsWith(options.workspaceDir)) {
39
- return `${options.workspacePath}${hostPath.slice(options.workspaceDir.length)}`;
40
- }
41
- return hostPath;
95
+ throw new Error("Unsupported task action. Use create, progress, set, verify, done, cancel, start-cycle, or list.");
42
96
  }
43
97
  function tasksDir(options) {
44
98
  return join(options.channelDir, "tasks");
@@ -47,13 +101,7 @@ function eventsDir(options) {
47
101
  return join(options.workspaceDir, "events");
48
102
  }
49
103
  function renderTaskFile(fields, body) {
50
- const lines = ["---", `status: ${fields.status}`];
51
- if (fields.wake)
52
- lines.push(`wake: ${fields.wake}`);
53
- if (fields.recurrence)
54
- lines.push(`recurrence: ${fields.recurrence}`);
55
- lines.push("---");
56
- return `${lines.join("\n")}\n${body}`;
104
+ return renderTaskDocument(fields, body);
57
105
  }
58
106
  function requiredField(value, field, action) {
59
107
  const trimmed = value?.trim();
@@ -99,29 +147,42 @@ function renderTaskSkeleton(request) {
99
147
  const title = requiredField(request.title, "title", "create");
100
148
  const goal = requiredField(request.goal, "goal", "create");
101
149
  const dod = requiredField(request.dod, "dod", "create");
102
- const fields = applySet({ status: normalizeCreateStatus(request.status) }, request);
103
- const body = renderStandardTaskBody({ title, goal, dod, manual: request.manual });
150
+ const mode = request.control?.verificationMode ?? "independent";
151
+ const control = applyTaskControlPatch(createDefaultTaskControl(mode), request.control ?? {});
152
+ const fields = applySet({ status: normalizeCreateStatus(request.status), control }, request);
153
+ const body = renderStandardTaskBody({
154
+ title,
155
+ goal,
156
+ dod,
157
+ manual: request.manual,
158
+ verificationPlan: request.verificationPlan,
159
+ verificationMode: control.verification.mode,
160
+ });
104
161
  return { fields, body };
105
162
  }
106
163
  /**
107
- * Read a task file and split it into its three-field frontmatter and verbatim body.
164
+ * Read a task file and split it into validated frontmatter and a verbatim body.
108
165
  * Fail-closed: an unreadable frontmatter block is rejected (fix it with edit first)
109
166
  * rather than guessed at, so task_manage never silently mangles a body.
110
167
  */
111
- async function readTaskDocument(taskPath, id) {
168
+ async function readTaskDocument(taskPath, id, allowControlRepair = false) {
112
169
  if (!existsSync(taskPath)) {
113
- throw new Error(`Task "${id}" does not exist; create it with write first.`);
170
+ throw new Error(`Task "${id}" does not exist; create it with task_manage action "create" first.`);
114
171
  }
115
172
  const content = await readFile(taskPath, "utf-8");
116
173
  const frontmatter = parseTaskFrontmatter(content);
117
174
  if (!frontmatter.readable) {
118
175
  throw new Error(`Task "${id}" has no readable frontmatter; fix it with edit before using task_manage.`);
119
176
  }
177
+ if (frontmatter.controlReadable === false && !allowControlRepair) {
178
+ throw new Error(`Task "${id}" has invalid control metadata; repair it with task_manage action "set" and an explicit control patch first.`);
179
+ }
120
180
  return {
121
181
  fields: {
122
182
  status: frontmatter.status ?? "open",
123
183
  wake: frontmatter.wake,
124
184
  recurrence: frontmatter.recurrence,
185
+ control: frontmatter.control,
125
186
  },
126
187
  body: taskBody(content),
127
188
  };
@@ -129,6 +190,9 @@ async function readTaskDocument(taskPath, id) {
129
190
  /** Apply a `set` request's optional fields onto the existing frontmatter. */
130
191
  function applySet(fields, request) {
131
192
  const next = { ...fields };
193
+ if (request.control?.externalApproval === "granted") {
194
+ throw new Error('Only a user can grant external-action approval with "/tasks approve <id>".');
195
+ }
132
196
  if (request.status !== undefined) {
133
197
  if (!SETTABLE_STATUSES.includes(request.status)) {
134
198
  throw new Error(`Invalid status "${request.status}". Use one of ${SETTABLE_STATUSES.join(", ")}, or action "done".`);
@@ -151,8 +215,56 @@ function applySet(fields, request) {
151
215
  const trimmed = request.recurrence.trim();
152
216
  next.recurrence = trimmed === "" ? undefined : trimmed;
153
217
  }
218
+ if (request.control !== undefined) {
219
+ next.control = applyTaskControlPatch(next.control ?? createDefaultTaskControl("evidence"), request.control);
220
+ }
154
221
  return next;
155
222
  }
223
+ async function validateTaskRelations(options, id, fields) {
224
+ const control = fields.control;
225
+ if (!control)
226
+ return;
227
+ if (control.parent === id || control.dependsOn.includes(id)) {
228
+ throw new Error(`Task "${id}" cannot be its own parent or dependency.`);
229
+ }
230
+ for (const relatedId of [control.parent, ...control.dependsOn].filter((value) => Boolean(value))) {
231
+ const active = join(tasksDir(options), `${relatedId}.md`);
232
+ const archived = join(tasksDir(options), "archive", `${relatedId}.md`);
233
+ if (!existsSync(active) && !existsSync(archived)) {
234
+ throw new Error(`Related task "${relatedId}" does not exist; create it before linking task "${id}".`);
235
+ }
236
+ }
237
+ if (control.parent) {
238
+ const visited = new Set();
239
+ let current = control.parent;
240
+ while (current) {
241
+ if (visited.has(current)) {
242
+ throw new Error(`Existing parent chain for "${control.parent}" already contains a cycle.`);
243
+ }
244
+ if (current === id) {
245
+ throw new Error(`Task parent cycle detected while linking "${id}" to "${control.parent}".`);
246
+ }
247
+ visited.add(current);
248
+ const task = await readStoredTask(options.channelDir, current, true);
249
+ current = task?.fields.control?.parent;
250
+ }
251
+ }
252
+ for (const dependencyId of control.dependsOn) {
253
+ const visited = new Set();
254
+ const stack = [dependencyId];
255
+ while (stack.length > 0) {
256
+ const current = stack.pop();
257
+ if (!current || visited.has(current))
258
+ continue;
259
+ if (current === id) {
260
+ throw new Error(`Task dependency cycle detected while linking "${id}" to "${dependencyId}".`);
261
+ }
262
+ visited.add(current);
263
+ const task = await readStoredTask(options.channelDir, current, true);
264
+ stack.push(...(task?.fields.control?.dependsOn ?? []));
265
+ }
266
+ }
267
+ }
156
268
  async function createTask(options, request) {
157
269
  if (!request.id)
158
270
  throw new Error('action "create" requires an id.');
@@ -167,12 +279,16 @@ async function createTask(options, request) {
167
279
  throw new Error(`Archived task "${id}" already exists; choose a new id or restore it manually first.`);
168
280
  }
169
281
  const { fields, body } = renderTaskSkeleton(request);
282
+ const badDod = uncheckedTaskAcceptanceItems(body).find((item) => item.startsWith("DoD has no checklist items"));
283
+ if (badDod)
284
+ throw new Error(badDod);
285
+ await validateTaskRelations(options, id, fields);
170
286
  await mkdir(dir, { recursive: true });
171
287
  await writeFileAtomically(taskPath, renderTaskFile(fields, body));
172
288
  return {
173
289
  action: "create",
174
290
  id,
175
- path: toWorkspacePath(options, taskPath),
291
+ path: taskPath,
176
292
  status: fields.status,
177
293
  notice: `已创建任务 \`${id}\`(status: ${fields.status})。`,
178
294
  };
@@ -181,11 +297,11 @@ async function createTask(options, request) {
181
297
  * On close-out, keep only the task's recurring cadence event
182
298
  * (`task.<channelId>.<id>.schedule`) and delete every other task-owned event.
183
299
  *
184
- * A task may also own temporary periodic events (for example an agentmux idle sensor).
300
+ * A task may also own temporary periodic sensor/check-in events.
185
301
  * Those are lifecycle check-ins, not proof that the task itself is recurring, so they
186
302
  * must not prevent a one-shot task from being archived.
187
303
  */
188
- async function cleanupTaskEvents(options, id) {
304
+ async function cleanupTaskEvents(options, id, preserveSchedule = true) {
189
305
  const dir = eventsDir(options);
190
306
  if (!existsSync(dir))
191
307
  return { deleted: [], hasSchedule: false };
@@ -204,7 +320,9 @@ async function cleanupTaskEvents(options, id) {
204
320
  catch {
205
321
  continue; // can't classify → leave it for /events to handle
206
322
  }
207
- if (filename === scheduleFilename && isTaskScheduleEvent({ use: "schedule", event: { type } })) {
323
+ if (preserveSchedule &&
324
+ filename === scheduleFilename &&
325
+ isTaskScheduleEvent({ use: "schedule", event: { type } })) {
208
326
  hasSchedule = true; // the cadence lives on for the next cycle
209
327
  continue;
210
328
  }
@@ -218,17 +336,146 @@ async function setTask(options, request) {
218
336
  throw new Error('action "set" requires an id.');
219
337
  const id = normalizeTaskId(request.id);
220
338
  const taskPath = join(tasksDir(options), `${id}.md`);
221
- const { fields, body } = await readTaskDocument(taskPath, id);
339
+ const { fields, body } = await readTaskDocument(taskPath, id, request.control !== undefined);
340
+ if (request.control !== undefined && fields.control === undefined) {
341
+ fields.control = createDefaultTaskControl("independent");
342
+ }
222
343
  const nextFields = applySet(fields, request);
344
+ await validateTaskRelations(options, id, nextFields);
223
345
  await writeFileAtomically(taskPath, renderTaskFile(nextFields, body));
224
346
  return {
225
347
  action: "set",
226
348
  id,
227
- path: toWorkspacePath(options, taskPath),
349
+ path: taskPath,
228
350
  status: nextFields.status,
229
351
  notice: `已更新任务 \`${id}\`(status: ${nextFields.status}${nextFields.wake ? `, wake: ${nextFields.wake}` : ""})。`,
230
352
  };
231
353
  }
354
+ async function progressTask(options, request) {
355
+ if (!request.id)
356
+ throw new Error('action "progress" requires an id.');
357
+ const id = normalizeTaskId(request.id);
358
+ const note = requiredField(request.note, "note", "progress");
359
+ const taskPath = join(tasksDir(options), `${id}.md`);
360
+ const { fields, body } = await readTaskDocument(taskPath, id);
361
+ if (["done", "cancelled", "escalated", "paused"].includes(fields.status)) {
362
+ throw new Error(`Task "${id}" is ${fields.status} and cannot be progressed.`);
363
+ }
364
+ const nextFields = applySet(fields, request);
365
+ await validateTaskRelations(options, id, nextFields);
366
+ if (nextFields.control) {
367
+ nextFields.control = invalidateTaskVerification(nextFields.control);
368
+ nextFields.control = invalidateTaskApproval(nextFields.control);
369
+ if (request.status === "blocked" || request.status === "awaiting-user") {
370
+ nextFields.control.lastOutcome = "blocked";
371
+ }
372
+ else if (request.control?.lastOutcome === undefined) {
373
+ nextFields.control.lastOutcome = "progress";
374
+ if (request.control?.blockedReason === undefined)
375
+ nextFields.control.blockedReason = undefined;
376
+ }
377
+ }
378
+ const nextBody = appendCurrentCycleNote(body, note);
379
+ await writeFileAtomically(taskPath, renderTaskFile(nextFields, nextBody));
380
+ return {
381
+ action: "progress",
382
+ id,
383
+ path: taskPath,
384
+ status: nextFields.status,
385
+ notice: `已记录任务 \`${id}\` 的进展(status: ${nextFields.status}${nextFields.wake ? `, wake: ${nextFields.wake}` : ""})。`,
386
+ };
387
+ }
388
+ /**
389
+ * Move a task into the verification lane. The runtime driver will explicitly
390
+ * wake a fresh verifier on the next attempt, keeping the maker from grading
391
+ * its own work in the same reasoning context.
392
+ */
393
+ async function candidateTask(options, request) {
394
+ if (!request.id)
395
+ throw new Error('action "candidate" requires an id.');
396
+ const id = normalizeTaskId(request.id);
397
+ const note = requiredField(request.note, "note", "candidate");
398
+ const taskPath = join(tasksDir(options), `${id}.md`);
399
+ const { fields, body } = await readTaskDocument(taskPath, id);
400
+ if (["done", "cancelled", "escalated", "paused"].includes(fields.status)) {
401
+ throw new Error(`Task "${id}" is ${fields.status} and cannot enter verification.`);
402
+ }
403
+ const uncheckedAcceptance = uncheckedTaskAcceptanceItems(body);
404
+ if (uncheckedAcceptance.length > 0) {
405
+ throw new Error(`Task "${id}" still has unchecked acceptance items: ${uncheckedAcceptance.join("; ")}. Check them with evidence before requesting verification.`);
406
+ }
407
+ const control = fields.control ?? createDefaultTaskControl("independent");
408
+ control.verification = { mode: "independent", status: "pending" };
409
+ control.lastOutcome = "progress";
410
+ control.blockedReason = undefined;
411
+ control.nextAction = "Run a purpose=verify sub-agent and import its attestation.";
412
+ const nextBody = appendCurrentCycleNote(body, note);
413
+ await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "verifying", wake: undefined, control }, nextBody));
414
+ return {
415
+ action: "candidate",
416
+ id,
417
+ path: taskPath,
418
+ status: "verifying",
419
+ notice: `任务 \`${id}\` 已进入独立验收队列;driver 将安排 verifier。`,
420
+ };
421
+ }
422
+ async function verifyTask(options, request) {
423
+ if (!request.id)
424
+ throw new Error('action "verify" requires an id.');
425
+ const id = normalizeTaskId(request.id);
426
+ const runId = requiredField(request.verifierRunId, "verifierRunId", "verify");
427
+ const task = await readStoredTask(options.channelDir, id);
428
+ if (!task)
429
+ throw new Error(`Task "${id}" does not exist; create it before verification.`);
430
+ const attestation = await readVerificationAttestation(options.channelDir, runId);
431
+ if (attestation.taskId !== id) {
432
+ throw new Error(`Verification run "${runId}" belongs to task "${attestation.taskId}", not "${id}".`);
433
+ }
434
+ if (attestation.workspaceChanged) {
435
+ throw new Error(`Verification run "${runId}" changed the workspace; rerun a read-only verifier.`);
436
+ }
437
+ if (attestation.bodyHash !== taskBodyHash(task.body)) {
438
+ throw new Error(`Task "${id}" changed after verification run "${runId}"; rerun the verifier on current content.`);
439
+ }
440
+ if (attestation.subjectHash) {
441
+ const currentSubject = await workspaceSubjectHash(options.workingDirectory ?? process.cwd());
442
+ if (!currentSubject) {
443
+ throw new Error(`Verification run "${runId}" is bound to a Git artifact subject, but the current checkout cannot be read. Rerun verification from the project checkout.`);
444
+ }
445
+ if (currentSubject !== attestation.subjectHash) {
446
+ throw new Error(`Task "${id}" artifacts changed after verification run "${runId}"; rerun the verifier.`);
447
+ }
448
+ }
449
+ const control = task.fields.control ?? createDefaultTaskControl("independent");
450
+ control.verification = {
451
+ mode: "independent",
452
+ status: attestation.verdict === "pass" ? "passed" : "failed",
453
+ runId,
454
+ evidence: attestation.evidence,
455
+ bodyHash: attestation.bodyHash,
456
+ subjectHash: attestation.subjectHash,
457
+ checkedAt: attestation.checkedAt,
458
+ };
459
+ control.lastOutcome = attestation.verdict === "pass" ? "verified" : "failed";
460
+ control.blockedReason = attestation.verdict === "fail" ? attestation.evidence : undefined;
461
+ task.fields.control = control;
462
+ await writeFileAtomically(task.path, renderTaskFile(task.fields, task.body));
463
+ return {
464
+ action: "verify",
465
+ id,
466
+ path: task.path,
467
+ status: task.fields.status,
468
+ notice: `任务 \`${id}\` 独立验收结果:${attestation.verdict.toUpperCase()}(run: ${runId})。`,
469
+ };
470
+ }
471
+ async function unfinishedChildren(options, parentId) {
472
+ const entries = await readActiveTasks(tasksDir(options));
473
+ return entries
474
+ .filter((entry) => entry.frontmatter.control?.parent === parentId &&
475
+ entry.frontmatter.status !== "done" &&
476
+ entry.frontmatter.status !== "cancelled")
477
+ .map((entry) => entry.id);
478
+ }
232
479
  async function doneTask(options, request) {
233
480
  if (!request.id)
234
481
  throw new Error('action "done" requires an id.');
@@ -236,7 +483,46 @@ async function doneTask(options, request) {
236
483
  const dir = tasksDir(options);
237
484
  const taskPath = join(dir, `${id}.md`);
238
485
  const { fields, body } = await readTaskDocument(taskPath, id);
486
+ const uncheckedAcceptance = uncheckedTaskAcceptanceItems(body);
487
+ if (uncheckedAcceptance.length > 0) {
488
+ throw new Error(`Task "${id}" still has unchecked acceptance items: ${uncheckedAcceptance.join("; ")}. Check them with evidence before done.`);
489
+ }
490
+ const dependencies = await dependencyState(options.channelDir, fields.control?.dependsOn ?? [], id);
491
+ if (!dependencies.ready) {
492
+ throw new Error(`Task "${id}" cannot be completed: ${dependencies.reason}. Complete its dependencies first.`);
493
+ }
494
+ const children = await unfinishedChildren(options, id);
495
+ if (children.length > 0) {
496
+ throw new Error(`Task "${id}" still has unfinished child tasks: ${children.join(", ")}. Finish or cancel them first.`);
497
+ }
498
+ if (fields.control?.sideEffects === "external") {
499
+ if (fields.control.externalApproval !== "granted") {
500
+ throw new Error(`Task "${id}" requires explicit external-action approval before it can be completed.`);
501
+ }
502
+ if (fields.control.approvalBodyHash !== taskBodyHash(body)) {
503
+ throw new Error(`Task "${id}" changed after external-action approval; ask the user to run /tasks approve ${id} again.`);
504
+ }
505
+ }
506
+ if (fields.control?.verification.mode === "independent") {
507
+ const verification = fields.control.verification;
508
+ if (verification.status !== "passed" || !verification.bodyHash) {
509
+ throw new Error(`Task "${id}" requires an independent PASS. Run a purpose=verify sub-agent, then task_manage verify with its run id.`);
510
+ }
511
+ if (verification.bodyHash !== taskBodyHash(body)) {
512
+ throw new Error(`Task "${id}" changed after its independent PASS; rerun verification before done.`);
513
+ }
514
+ if (verification.subjectHash) {
515
+ const currentSubject = await workspaceSubjectHash(options.workingDirectory ?? process.cwd());
516
+ if (currentSubject !== verification.subjectHash) {
517
+ throw new Error(`Task "${id}" artifacts changed after its independent PASS; rerun verification before done.`);
518
+ }
519
+ }
520
+ }
239
521
  const bodyWithEvidence = appendCompletionEvidence(body, request);
522
+ if (fields.control) {
523
+ fields.control.lastOutcome = "verified";
524
+ fields.control.blockedReason = undefined;
525
+ }
240
526
  await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "done" }, bodyWithEvidence));
241
527
  const { deleted, hasSchedule } = await cleanupTaskEvents(options, id);
242
528
  // Periodic task → sleeps in place until its schedule fires next; one-shot → archive.
@@ -254,13 +540,70 @@ async function doneTask(options, request) {
254
540
  return {
255
541
  action: "done",
256
542
  id,
257
- path: toWorkspacePath(options, finalPath),
543
+ path: finalPath,
258
544
  status: "done",
259
545
  archived,
260
546
  deletedEvents: deleted,
261
547
  notice: `任务 \`${id}\` 已完成(${disposition}${cleanup})。`,
262
548
  };
263
549
  }
550
+ async function cancelTask(options, request) {
551
+ if (!request.id)
552
+ throw new Error('action "cancel" requires an id.');
553
+ const id = normalizeTaskId(request.id);
554
+ const reason = requiredField(request.reason, "reason", "cancel");
555
+ const dir = tasksDir(options);
556
+ const taskPath = join(dir, `${id}.md`);
557
+ const { fields, body } = await readTaskDocument(taskPath, id);
558
+ const children = await unfinishedChildren(options, id);
559
+ if (children.length > 0) {
560
+ throw new Error(`Task "${id}" still has unfinished child tasks: ${children.join(", ")}. Cancel or re-parent them first.`);
561
+ }
562
+ if (fields.control) {
563
+ fields.control.lastOutcome = "blocked";
564
+ fields.control.blockedReason = `Cancelled: ${reason}`;
565
+ }
566
+ const cancelledBody = `${body.replace(/\n+$/, "\n")}\n## Cancellation\n\n- Reason: ${markdownValue(reason)}\n`;
567
+ await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "cancelled", wake: undefined }, cancelledBody));
568
+ const { deleted } = await cleanupTaskEvents(options, id, false);
569
+ const archiveDir = join(dir, "archive");
570
+ await mkdir(archiveDir, { recursive: true });
571
+ const finalPath = join(archiveDir, `${id}.md`);
572
+ await rename(taskPath, finalPath);
573
+ return {
574
+ action: "cancel",
575
+ id,
576
+ path: finalPath,
577
+ status: "cancelled",
578
+ archived: true,
579
+ deletedEvents: deleted,
580
+ notice: `任务 \`${id}\` 已取消并归档${deleted.length ? `,清理事件 ${deleted.join(", ")}` : ""}。`,
581
+ };
582
+ }
583
+ async function startCycleTask(options, request) {
584
+ if (!request.id)
585
+ throw new Error('action "start-cycle" requires an id.');
586
+ const id = normalizeTaskId(request.id);
587
+ const cycleId = requiredField(request.cycleId, "cycleId", "start-cycle");
588
+ const taskPath = join(tasksDir(options), `${id}.md`);
589
+ const { fields, body } = await readTaskDocument(taskPath, id);
590
+ if (fields.status !== "done") {
591
+ throw new Error(`Task "${id}" is ${fields.status}, not done. Finish, cancel, or explicitly resolve the current cycle before starting another.`);
592
+ }
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.`);
595
+ }
596
+ const control = fields.control ? resetTaskControlForCycle(fields.control, cycleId) : undefined;
597
+ const nextBody = startTaskCycle(body, cycleId);
598
+ await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "in-progress", wake: undefined, control }, nextBody));
599
+ return {
600
+ action: "start-cycle",
601
+ id,
602
+ path: taskPath,
603
+ status: "in-progress",
604
+ notice: `已开启周期任务 \`${id}\` 的新周期 \`${cycleId}\`。`,
605
+ };
606
+ }
264
607
  async function listTasks(options) {
265
608
  const entries = await readActiveTasks(tasksDir(options));
266
609
  return {
@@ -271,6 +614,7 @@ async function listTasks(options) {
271
614
  status: entry.frontmatter.readable ? (entry.frontmatter.status ?? "open") : "unreadable",
272
615
  wake: entry.frontmatter.wake,
273
616
  actionable: entry.actionable,
617
+ control: entry.frontmatter.control,
274
618
  })),
275
619
  notice: `台账共有 ${entries.length} 个 active 任务。`,
276
620
  };
@@ -279,10 +623,20 @@ export async function manageTask(options, request) {
279
623
  switch (request.action) {
280
624
  case "create":
281
625
  return createTask(options, request);
626
+ case "progress":
627
+ return progressTask(options, request);
628
+ case "candidate":
629
+ return candidateTask(options, request);
282
630
  case "set":
283
631
  return setTask(options, request);
632
+ case "verify":
633
+ return verifyTask(options, request);
284
634
  case "done":
285
635
  return doneTask(options, request);
636
+ case "cancel":
637
+ return cancelTask(options, request);
638
+ case "start-cycle":
639
+ return startCycleTask(options, request);
286
640
  case "list":
287
641
  return listTasks(options);
288
642
  }
@@ -291,10 +645,9 @@ export function createTaskManageTool(options) {
291
645
  return {
292
646
  name: "task_manage",
293
647
  label: "task_manage",
294
- description: "Manage this channel's task ledger frontmatter and lifecycle: set status/wake/recurrence, close a task out " +
295
- "(requiring summary/evidence, archiving one-shot tasks, and cleaning up residual events), or list active " +
296
- "tasks. Write the task body (goal, DoD, manual, cycle log) with write/edit; this tool owns only the " +
297
- "frontmatter and close-out evidence.",
648
+ description: "Manage governed persistent tasks: create, atomically checkpoint progress/control state, import an independent " +
649
+ "verifier attestation, complete verified work, cancel abandoned work, or list tasks. Use progress for routine " +
650
+ "end-of-turn checkpoints; use write/edit only for substantial Goal/DoD/Manual/Verification changes.",
298
651
  parameters: taskManageSchema,
299
652
  execute: async (_toolCallId, args) => {
300
653
  const result = await manageTask(options, {
@@ -304,12 +657,18 @@ export function createTaskManageTool(options) {
304
657
  goal: args.goal,
305
658
  dod: args.dod,
306
659
  manual: args.manual,
660
+ verificationPlan: args.verificationPlan,
661
+ control: args.control,
307
662
  status: args.status,
308
663
  wake: args.wake,
309
664
  recurrence: args.recurrence,
665
+ note: args.note,
666
+ verifierRunId: args.verifierRunId,
310
667
  summary: args.summary,
311
668
  evidence: args.evidence,
312
669
  residualRisk: args.residualRisk,
670
+ reason: args.reason,
671
+ cycleId: args.cycleId,
313
672
  });
314
673
  return {
315
674
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
@@ -1,4 +1,4 @@
1
- import type { Executor } from "../sandbox.js";
1
+ import type { Executor } from "../executor.js";
2
2
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
3
3
  export declare function writeContent(executor: Executor, path: string, content: string, signal: AbortSignal | undefined, options?: {
4
4
  createParentDir?: boolean;
@@ -16,7 +16,6 @@ export async function writeContent(executor, path, content, signal, options) {
16
16
  const securityConfig = options?.securityConfig ?? DEFAULT_SECURITY_CONFIG;
17
17
  const securityContext = options?.securityContext ?? {
18
18
  workspaceDir: process.cwd(),
19
- workspacePath: process.cwd(),
20
19
  cwd: process.cwd(),
21
20
  };
22
21
  if (securityConfig.enabled && securityConfig.pathGuard.enabled) {
@@ -1,6 +1,6 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
- import type { Executor } from "../sandbox.js";
3
+ import type { Executor } from "../executor.js";
4
4
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
5
5
  declare const writeSchema: Type.TObject<{
6
6
  label: Type.TString;
package/dist/tui/app.d.ts CHANGED
@@ -1,7 +1,5 @@
1
1
  import { type BootstrapIO, type BootstrapPaths } from "../runtime/bootstrap.js";
2
- import type { SandboxConfig } from "../sandbox.js";
3
2
  export interface TuiAppOptions {
4
- sandbox: SandboxConfig;
5
3
  channel?: string;
6
4
  /** One-shot, non-interactive run: process a single prompt then exit. */
7
5
  print?: boolean;