@oyasmi/pipiclaw 0.8.9 → 0.8.10-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.
Files changed (75) hide show
  1. package/README.md +3 -3
  2. package/dist/agent/channel-runner.d.ts +1 -0
  3. package/dist/agent/channel-runner.js +6 -10
  4. package/dist/agent/maintenance-context.d.ts +0 -1
  5. package/dist/agent/maintenance-context.js +0 -7
  6. package/dist/agent/session-events.d.ts +1 -0
  7. package/dist/agent/session-events.js +10 -0
  8. package/dist/agent/types.d.ts +7 -0
  9. package/dist/agent/types.js +2 -0
  10. package/dist/index.d.ts +16 -34
  11. package/dist/index.js +14 -32
  12. package/dist/memory/consolidation.js +0 -1
  13. package/dist/memory/extraction.d.ts +1 -7
  14. package/dist/memory/extraction.js +2 -46
  15. package/dist/memory/lifecycle.js +3 -3
  16. package/dist/memory/maintenance-gates.d.ts +4 -16
  17. package/dist/memory/maintenance-gates.js +11 -51
  18. package/dist/memory/maintenance-jobs.d.ts +3 -14
  19. package/dist/memory/maintenance-jobs.js +12 -103
  20. package/dist/memory/maintenance-state.d.ts +2 -6
  21. package/dist/memory/maintenance-state.js +14 -10
  22. package/dist/memory/maintenance-tuning.d.ts +37 -0
  23. package/dist/memory/maintenance-tuning.js +46 -0
  24. package/dist/memory/promotion.d.ts +0 -22
  25. package/dist/memory/promotion.js +1 -8
  26. package/dist/memory/review-log.d.ts +1 -1
  27. package/dist/memory/scheduler.d.ts +1 -9
  28. package/dist/memory/scheduler.js +3 -15
  29. package/dist/memory/source-window.d.ts +2 -2
  30. package/dist/memory/task-digest.js +2 -5
  31. package/dist/models/utils.d.ts +5 -0
  32. package/dist/models/utils.js +10 -0
  33. package/dist/paths.d.ts +0 -1
  34. package/dist/paths.js +0 -1
  35. package/dist/playbooks/task-closeout.md +2 -0
  36. package/dist/playbooks/task-delegation.md +8 -14
  37. package/dist/playbooks/task-driving.md +3 -4
  38. package/dist/playbooks/task-planning.md +8 -9
  39. package/dist/runtime/bootstrap.d.ts +14 -0
  40. package/dist/runtime/bootstrap.js +9 -4
  41. package/dist/runtime/task-commands.js +46 -73
  42. package/dist/runtime/task-driver.js +6 -23
  43. package/dist/settings.d.ts +39 -40
  44. package/dist/settings.js +87 -107
  45. package/dist/shared/task-ledger.d.ts +19 -2
  46. package/dist/shared/task-ledger.js +194 -5
  47. package/dist/subagents/discovery.d.ts +41 -7
  48. package/dist/subagents/discovery.js +74 -24
  49. package/dist/subagents/tool.d.ts +3 -12
  50. package/dist/subagents/tool.js +11 -115
  51. package/dist/tasks/control.d.ts +57 -27
  52. package/dist/tasks/control.js +94 -93
  53. package/dist/tasks/store.d.ts +1 -4
  54. package/dist/tasks/store.js +1 -39
  55. package/dist/tasks/transitions.d.ts +1 -1
  56. package/dist/tasks/transitions.js +1 -0
  57. package/dist/tasks/verification.d.ts +10 -6
  58. package/dist/tasks/verification.js +0 -6
  59. package/dist/tools/memory-manage.js +46 -24
  60. package/dist/tools/task-manage/create.js +1 -2
  61. package/dist/tools/task-manage/lifecycle.d.ts +7 -0
  62. package/dist/tools/task-manage/lifecycle.js +52 -32
  63. package/dist/tools/task-manage/schema.d.ts +2 -9
  64. package/dist/tools/task-manage/schema.js +9 -19
  65. package/dist/tools/task-manage/shared.d.ts +0 -2
  66. package/dist/tools/task-manage/shared.js +8 -69
  67. package/dist/tools/task-manage/types.d.ts +1 -1
  68. package/dist/tools/task-manage/verification.js +5 -6
  69. package/dist/tools/task-manage.js +4 -2
  70. package/examples/sub-agents/README.md +1 -1
  71. package/package.json +3 -1
  72. package/dist/memory/post-turn-review.d.ts +0 -43
  73. package/dist/memory/post-turn-review.js +0 -136
  74. package/dist/memory/promotion-signals.d.ts +0 -5
  75. package/dist/memory/promotion-signals.js +0 -33
@@ -10,10 +10,9 @@ import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
10
10
  import { splitH1Sections } from "../shared/markdown-sections.js";
11
11
  import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
12
12
  import { shellEscape } from "../shared/shell-escape.js";
13
- import { clipText, errorMessage, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
13
+ import { clipText, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
14
14
  import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
15
- import { applyTaskControlPatch } from "../tasks/control.js";
16
- import { readStoredTask, updateStoredTask } from "../tasks/store.js";
15
+ import { readStoredTask } from "../tasks/store.js";
17
16
  import { parseVerificationVerdict, writeVerificationAttestation } from "../tasks/verification.js";
18
17
  import { buildToolSet } from "../tools/registry.js";
19
18
  import { formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, } from "./discovery.js";
@@ -27,15 +26,11 @@ const subagentSchema = Type.Object({
27
26
  })),
28
27
  tools: Type.Optional(Type.Array(Type.String(), { description: "Optional tool whitelist for the sub-agent" })),
29
28
  model: Type.Optional(Type.String({ description: "Optional exact model reference. Defaults to the parent's current model." })),
30
- maxTurns: Type.Optional(Type.Number({ description: "Optional maximum assistant turns for this sub-agent" })),
31
- maxToolCalls: Type.Optional(Type.Number({ description: "Optional maximum tool calls for this sub-agent" })),
32
- maxWallTimeSec: Type.Optional(Type.Number({ description: "Optional wall time budget in seconds for this sub-agent" })),
33
- bashTimeoutSec: Type.Optional(Type.Number({ description: "Optional default timeout in seconds for bash commands inside this sub-agent" })),
34
- contextMode: Type.Optional(Type.Union([Type.Literal("isolated"), Type.Literal("contextual")], {
35
- description: 'Optional context mode. "isolated" (default) runs with no injected context; "contextual" injects selected session and memory context.',
29
+ effort: Type.Optional(Type.Union([Type.Literal("quick"), Type.Literal("standard"), Type.Literal("deep")], {
30
+ description: 'Execution budget preset (turns, tool calls, wall time). "standard" is the default; "quick" for narrow lookups, "deep" for long analyses.',
36
31
  })),
37
- memory: Type.Optional(Type.Union([Type.Literal("none"), Type.Literal("session"), Type.Literal("relevant")], {
38
- description: 'Optional memory mode for contextual sub-agents: "none", "session", or "relevant".',
32
+ context: Type.Optional(Type.Union([Type.Literal("none"), Type.Literal("session"), Type.Literal("relevant")], {
33
+ description: 'What context to inject. "none" (default) runs fully isolated; "session" adds current session state; "relevant" adds session state plus recalled memory.',
39
34
  })),
40
35
  paths: Type.Optional(Type.Array(Type.String(), {
41
36
  description: "Optional preferred file or directory paths for the sub-agent to focus on.",
@@ -44,12 +39,8 @@ const subagentSchema = Type.Object({
44
39
  description: 'Use "verify" for an independent, read-only task acceptance check.',
45
40
  })),
46
41
  taskId: Type.Optional(Type.String({ description: "Persistent task id, required when purpose=verify." })),
47
- isolation: Type.Optional(Type.Union([Type.Literal("shared"), Type.Literal("worktree")], {
48
- description: '"worktree" runs in a dedicated git worktree.',
49
- })),
50
- worktreePath: Type.Optional(Type.String({ description: "Reuse an existing task-owned worktree; must be under channel tasks/worktrees/." })),
51
42
  returns: Type.Optional(Type.Union([Type.Literal("text"), Type.Literal("artifact")], {
52
- description: 'How the sub-agent should hand back its result. "text" (default) returns the response directly. "artifact" instructs it to write its primary output to a file and end with an ARTIFACT: <filename> marker. Either way the full output is always saved under the artifact directory, and a reply over the size budget is truncated with a pointer to that file.',
43
+ description: '"text" (default) returns the response directly; "artifact" makes the sub-agent write its primary output to a file and end with an ARTIFACT: <filename> marker. The full output is saved to disk either way.',
53
44
  })),
54
45
  thinkingLevel: Type.Optional(Type.Union([
55
46
  Type.Literal("off"),
@@ -101,12 +92,6 @@ class DirectoryExecutor {
101
92
  function safeRunSegment(value) {
102
93
  return value.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 48) || "run";
103
94
  }
104
- function safeGitBranchSegment(value) {
105
- return (value
106
- .replace(/[^A-Za-z0-9_-]/g, "-")
107
- .replace(/^-+|-+$/g, "")
108
- .slice(0, 48) || "run");
109
- }
110
95
  function getSubAgentArtifactsRoot(channelDir) {
111
96
  return join(channelDir, "subagent-artifacts");
112
97
  }
@@ -123,94 +108,12 @@ async function prepareRunContext(runId, params, options) {
123
108
  throw new Error("purpose=verify requires taskId.");
124
109
  if (taskId && !TASK_ID_PATTERN.test(taskId))
125
110
  throw new Error(`Invalid taskId: ${taskId}`);
126
- const ownedTask = taskId ? await readStoredTask(options.channelDir, taskId) : undefined;
127
- if (taskId && !ownedTask) {
111
+ if (taskId && !(await readStoredTask(options.channelDir, taskId))) {
128
112
  throw new Error(`Task ${taskId} does not exist. Create it with task_manage before delegating task-owned work.`);
129
113
  }
130
114
  const artifactDir = await prepareArtifactDir(options.channelDir, runId);
131
- const isolation = params.isolation ?? "shared";
132
- if (isolation === "shared") {
133
- if (params.worktreePath)
134
- throw new Error("worktreePath requires isolation=worktree.");
135
- const workingDirectory = resolve(options.workingDirectory ?? process.cwd());
136
- return { runId, purpose, taskId, isolation, workingDirectory, artifactDir };
137
- }
138
- if (!taskId)
139
- throw new Error("isolation=worktree requires taskId so the worktree has a durable owner.");
140
- if (!ownedTask?.fields.control) {
141
- throw new Error(`Task ${taskId} has no governed control metadata. Normalize it with task_manage set first.`);
142
- }
143
- const baseDir = resolve(options.channelDir, "tasks", "worktrees");
144
- await mkdir(baseDir, { recursive: true });
145
- if (params.worktreePath) {
146
- const existing = resolve(params.worktreePath);
147
- const rel = relative(baseDir, existing);
148
- if (!rel || rel.startsWith("..") || isAbsolute(rel)) {
149
- throw new Error(`worktreePath must be inside ${baseDir}.`);
150
- }
151
- const check = await options.executor.exec(`git -C ${shellEscape(existing)} rev-parse --is-inside-work-tree`);
152
- if (check.code !== 0 || check.stdout.trim() !== "true") {
153
- throw new Error(`worktreePath is not a usable git worktree: ${existing}`);
154
- }
155
- const branchResult = await options.executor.exec(`git -C ${shellEscape(existing)} branch --show-current`);
156
- const context = {
157
- runId,
158
- purpose,
159
- taskId,
160
- isolation,
161
- workingDirectory: existing,
162
- worktreePath: existing,
163
- worktreeBranch: branchResult.code === 0 ? branchResult.stdout.trim() || undefined : undefined,
164
- artifactDir,
165
- };
166
- await recordTaskWorktree(options.channelDir, taskId, context);
167
- return context;
168
- }
169
- const sourceDirectory = resolve(options.workingDirectory ?? process.cwd());
170
- const rootResult = await options.executor.exec(`git -C ${shellEscape(sourceDirectory)} rev-parse --show-toplevel`);
171
- if (rootResult.code !== 0 || !rootResult.stdout.trim()) {
172
- throw new Error("Cannot create an isolated worktree: the current working directory is not inside a git repository.");
173
- }
174
- const repoRoot = rootResult.stdout.trim();
175
- const runSegment = safeRunSegment(runId).slice(-16);
176
- const taskSegment = safeRunSegment(taskId);
177
- const path = join(baseDir, taskSegment, runSegment);
178
- const branch = `pipiclaw-task/${safeGitBranchSegment(taskId)}/${safeGitBranchSegment(runId).slice(-16)}`;
179
- await mkdir(join(baseDir, taskSegment), { recursive: true });
180
- const created = await options.executor.exec(`git -C ${shellEscape(repoRoot)} worktree add -b ${shellEscape(branch)} ${shellEscape(path)} HEAD`, { timeout: 60 });
181
- if (created.code !== 0) {
182
- throw new Error(`Could not create git worktree for task ${taskId}: ${created.stderr || created.stdout}. Remove the stale worktree/branch or use isolation=shared.`);
183
- }
184
- const context = {
185
- runId,
186
- purpose,
187
- taskId,
188
- isolation,
189
- workingDirectory: path,
190
- worktreePath: path,
191
- worktreeBranch: branch,
192
- artifactDir,
193
- };
194
- try {
195
- await recordTaskWorktree(options.channelDir, taskId, context);
196
- }
197
- catch (error) {
198
- await options.executor.exec(`git -C ${shellEscape(repoRoot)} worktree remove --force ${shellEscape(path)}`);
199
- await options.executor.exec(`git -C ${shellEscape(repoRoot)} branch -D ${shellEscape(branch)}`);
200
- throw new Error(`Created the worktree but could not record its ownership on task ${taskId}; the temporary worktree was removed. ${errorMessage(error)}`);
201
- }
202
- return context;
203
- }
204
- async function recordTaskWorktree(channelDir, taskId, context) {
205
- await updateStoredTask(channelDir, taskId, (task) => {
206
- if (!task.fields.control || !context.worktreePath)
207
- return;
208
- task.fields.control = applyTaskControlPatch(task.fields.control, {
209
- isolation: "worktree",
210
- worktreePath: context.worktreePath,
211
- worktreeBranch: context.worktreeBranch,
212
- });
213
- });
115
+ const workingDirectory = resolve(options.workingDirectory ?? process.cwd());
116
+ return { runId, purpose, taskId, workingDirectory, artifactDir };
214
117
  }
215
118
  async function gitWorkspaceState(executor) {
216
119
  const result = await executor.exec("git status --porcelain=v1 --untracked-files=all", { timeout: 30 });
@@ -344,7 +247,6 @@ function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runConte
344
247
  `- Channel id: ${runtimeContext.channelId}`,
345
248
  `- Channel directory: ${runtimeContext.workspaceDir}/${runtimeContext.channelId}`,
346
249
  `- Working directory: ${runContext.workingDirectory}`,
347
- `- Filesystem isolation: ${runContext.isolation === "worktree" ? "dedicated git worktree" : "shared with parent"}`,
348
250
  `- Artifact directory: ${runContext.artifactDir}`,
349
251
  `- Your configured role: ${config.name}`,
350
252
  ];
@@ -462,9 +364,6 @@ function createDetails(config, runContext, usage, turns, toolCalls, durationMs,
462
364
  runId: runContext.runId,
463
365
  purpose: runContext.purpose,
464
366
  taskId: runContext.taskId,
465
- isolation: runContext.isolation,
466
- worktreePath: runContext.worktreePath,
467
- worktreeBranch: runContext.worktreeBranch,
468
367
  verificationVerdict,
469
368
  artifactDir: runContext.artifactDir,
470
369
  artifactPath: extras?.artifactPath,
@@ -487,7 +386,7 @@ export function createSubAgentTool(options) {
487
386
  return {
488
387
  name: "subagent",
489
388
  label: "subagent",
490
- description: "Delegate a task to a sub-agent with an isolated context. Default path: pass an inline systemPrompt (plus optional tools/model) to define a temporary sub-agent — no configured agent is required. You may instead name a configured sub-agent via `agent`; workspaceDir/sub-agents/ may be empty on a given install, which does not block inline delegation. Sub-agents never receive the subagent tool, so they cannot create nested agents.",
389
+ description: "Delegate a task to a sub-agent with an isolated context. Default path: pass an inline systemPrompt (plus optional tools/model) to define a temporary sub-agent — no configured agent is required. You may instead name a configured sub-agent via `agent`; workspaceDir/sub-agents/ may be empty on a given install, which does not block inline delegation. Execution budgets come from `effort` presets and context injection from `context`; both have safe defaults, so state the task well and leave them alone unless you have a reason. Sub-agents never receive the subagent tool, so they cannot create nested agents.",
491
390
  parameters: subagentSchema,
492
391
  execute: async (_toolCallId, params, signal, onUpdate) => {
493
392
  const availableModels = options.getAvailableModels();
@@ -681,13 +580,10 @@ export function createSubAgentTool(options) {
681
580
  runId: runContext.runId,
682
581
  taskId: runContext.taskId,
683
582
  verdict: verificationVerdict,
684
- agent: config.name,
685
- model: formatModelReference(config.model),
686
583
  checkedAt: new Date().toISOString(),
687
584
  evidence,
688
585
  workspaceChanged: Boolean(workspaceChanged),
689
586
  subjectHash: workspaceChanged ? undefined : verifierSubjectAfter,
690
- output: finalText,
691
587
  });
692
588
  }
693
589
  if (effectiveFailureReason) {
@@ -1,36 +1,66 @@
1
1
  export type TaskPriority = "low" | "normal" | "high" | "critical";
2
- export type TaskIsolation = "shared" | "worktree";
3
- export type TaskSideEffects = "read-only" | "workspace" | "external";
4
- export type TaskVerificationMode = "evidence" | "independent";
2
+ /**
3
+ * Whether the task may touch systems outside the workspace. Only `external` carries machine
4
+ * semantics (it gates the approval chain); the former `read-only`/`workspace` split had no
5
+ * enforcement anywhere and is read back as `workspace`.
6
+ */
7
+ export type TaskSideEffects = "workspace" | "external";
5
8
  export type TaskVerificationStatus = "pending" | "passed" | "failed";
6
- export type TaskOutcome = "pending" | "running" | "progress" | "blocked" | "failed" | "verified";
9
+ /**
10
+ * How the last agent run on this task ended. Pure telemetry, written only by the runtime
11
+ * (attempt claim/finish and governor escalation) — never by a `task_manage` action or a
12
+ * `/tasks` command, so it cannot drift into a second state machine alongside `status`.
13
+ */
14
+ export type TaskOutcome = "pending" | "running" | "progress" | "blocked" | "failed";
7
15
  /** Who paused a task: a user via /tasks pause, or the deterministic governor (ex-`escalated`). */
8
16
  export type TaskPausedBy = "user" | "governor";
17
+ /**
18
+ * The single per-task stop-loss (spec 036, D1).
19
+ *
20
+ * Token / cost / wall-time budgets were removed: they are per-task per-cycle, while spend is
21
+ * global — fifty individually-compliant tasks still burn through a monthly budget. Cost control
22
+ * belongs in a global spend guard, not here. `usage` below still *measures* all four dimensions;
23
+ * only the enforcement was dropped.
24
+ */
9
25
  export interface TaskBudget {
10
26
  maxAttempts: number;
11
- maxTokens?: number;
12
- maxCostUsd?: number;
13
- maxWallTimeMinutes?: number;
14
27
  }
15
28
  export interface TaskUsage {
16
29
  attempts: number;
17
30
  tokens: number;
18
31
  costUsd: number;
32
+ /** False when at least one contributing model omitted pricing metadata. */
33
+ costKnown: boolean;
19
34
  wallTimeMinutes: number;
20
35
  }
36
+ /**
37
+ * Independent acceptance state (spec 036, D5).
38
+ *
39
+ * There used to be two shapes here, `mode: "evidence" | "independent"`. The `evidence` half was
40
+ * the maker writing `status: "passed"` about its own work at `done` time, duplicating the
41
+ * Summary/Evidence already appended to the task body — a record, not a check. Only the
42
+ * independent form ever verified anything, so `mode` collapsed to a single boolean: does closing
43
+ * this task require a separate verifier's attestation?
44
+ *
45
+ * Dropping the second shape also removed five contradictory defaults for it (create said
46
+ * evidence, body rendering and the disk parser said independent).
47
+ */
21
48
  export interface TaskVerification {
22
- mode: TaskVerificationMode;
49
+ /** True ⇒ `done` requires a matching attestation on disk from a `purpose=verify` sub-agent. */
50
+ required: boolean;
23
51
  status: TaskVerificationStatus;
24
52
  runId?: string;
25
53
  evidence?: string;
54
+ /**
55
+ * Hash of the task's *contract* segment, not the whole body (see `taskBodyHash`). The key
56
+ * keeps its historical name: renaming it would make every stored task's recorded PASS
57
+ * unreadable and force a re-verify, which is not worth a naming fix.
58
+ */
26
59
  bodyHash?: string;
27
60
  checkedAt?: string;
61
+ /** Git view of the artifacts the verifier inspected; guards against edits between verify and done. */
28
62
  subjectHash?: string;
29
63
  }
30
- export interface TaskWorktree {
31
- path: string;
32
- branch?: string;
33
- }
34
64
  export interface TaskControl {
35
65
  version: 1;
36
66
  priority: TaskPriority;
@@ -38,18 +68,15 @@ export interface TaskControl {
38
68
  nextAction?: string;
39
69
  lastOutcome: TaskOutcome;
40
70
  blockedReason?: string;
41
- parent?: string;
42
- dependsOn: string[];
43
- isolation: TaskIsolation;
44
71
  sideEffects: TaskSideEffects;
45
72
  externalApproval: "not-required" | "required" | "granted";
46
73
  approvalBy?: string;
47
74
  approvedAt?: string;
48
75
  approvalBodyHash?: string;
49
76
  budget: TaskBudget;
77
+ /** Usage in the current recurring cycle (or the full one-shot task). */
50
78
  usage: TaskUsage;
51
79
  verification: TaskVerification;
52
- worktree?: TaskWorktree;
53
80
  lastStartedAt?: string;
54
81
  lastFinishedAt?: string;
55
82
  /** Identifier of the currently open recurring-task cycle, when applicable. */
@@ -61,22 +88,25 @@ export interface TaskControlPatch {
61
88
  priority?: TaskPriority;
62
89
  deadline?: string;
63
90
  nextAction?: string;
64
- lastOutcome?: TaskOutcome;
65
91
  blockedReason?: string;
66
- parent?: string;
67
- dependsOn?: string[];
68
- isolation?: TaskIsolation;
69
92
  sideEffects?: TaskSideEffects;
70
93
  externalApproval?: "not-required" | "required" | "granted";
71
94
  maxAttempts?: number;
72
- maxTokens?: number;
73
- maxCostUsd?: number;
74
- maxWallTimeMinutes?: number;
75
- verificationMode?: TaskVerificationMode;
76
- worktreePath?: string;
77
- worktreeBranch?: string;
95
+ /** Whether closing this task requires an independent verifier attestation (spec 036, D5). */
96
+ verificationRequired?: boolean;
78
97
  }
79
- export declare function createDefaultTaskControl(mode?: TaskVerificationMode): TaskControl;
98
+ /**
99
+ * Control keys that older builds wrote and this one ignores (spec 036, D8).
100
+ *
101
+ * Ignoring them keeps stored tasks readable with no migration script, but silence would be
102
+ * wrong for `parent`/`dependsOn`: the task survives, the ordering constraint it expressed does
103
+ * not. `/tasks doctor` reports whatever a stored control block still carries so the loss is
104
+ * visible rather than silent.
105
+ */
106
+ export declare const RETIRED_TASK_CONTROL_KEYS: readonly string[];
107
+ /** Retired keys actually present in a raw stored control block, in `RETIRED_TASK_CONTROL_KEYS` order. */
108
+ export declare function retiredTaskControlKeys(raw: unknown): string[];
109
+ export declare function createDefaultTaskControl(requiresVerification?: boolean): TaskControl;
80
110
  export declare function parseTaskControl(raw: string): TaskControl;
81
111
  /** Reset state which is meaningful only within one recurring task cycle. */
82
112
  export declare function resetTaskControlForCycle(control: TaskControl, cycleId: string): TaskControl;
@@ -1,12 +1,9 @@
1
1
  import { errorMessage } from "../shared/text-utils.js";
2
2
  const PRIORITIES = ["low", "normal", "high", "critical"];
3
- const ISOLATIONS = ["shared", "worktree"];
4
- const SIDE_EFFECTS = ["read-only", "workspace", "external"];
5
- const VERIFICATION_MODES = ["evidence", "independent"];
3
+ const SIDE_EFFECTS = ["workspace", "external"];
6
4
  const VERIFICATION_STATUSES = ["pending", "passed", "failed"];
7
- const OUTCOMES = ["pending", "running", "progress", "blocked", "failed", "verified"];
5
+ const OUTCOMES = ["pending", "running", "progress", "blocked", "failed"];
8
6
  const PAUSED_BY = ["user", "governor"];
9
- const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
10
7
  function isRecord(value) {
11
8
  return typeof value === "object" && value !== null && !Array.isArray(value);
12
9
  }
@@ -24,6 +21,14 @@ function finiteNonNegative(value, fallback = 0) {
24
21
  }
25
22
  return value;
26
23
  }
24
+ function parseTaskUsage(value) {
25
+ const attempts = Math.floor(finiteNonNegative(value.attempts));
26
+ const tokens = Math.floor(finiteNonNegative(value.tokens));
27
+ const costUsd = finiteNonNegative(value.costUsd);
28
+ const wallTimeMinutes = finiteNonNegative(value.wallTimeMinutes);
29
+ const costKnown = typeof value.costKnown === "boolean" ? value.costKnown : costUsd > 0 || (tokens === 0 && wallTimeMinutes === 0);
30
+ return { attempts, tokens, costUsd, costKnown, wallTimeMinutes };
31
+ }
27
32
  function optionalPositive(value) {
28
33
  if (value === undefined)
29
34
  return undefined;
@@ -32,6 +37,16 @@ function optionalPositive(value) {
32
37
  }
33
38
  return value;
34
39
  }
40
+ /**
41
+ * Read `verification.required`, mapping the retired `mode` enum losslessly (spec 036, D5/D8):
42
+ * `"independent"` was the only form that gated `done`, so it becomes `true`; `"evidence"` was
43
+ * maker self-certification and becomes `false`.
44
+ */
45
+ function parseVerificationRequired(verification) {
46
+ if (typeof verification.required === "boolean")
47
+ return verification.required;
48
+ return verification.mode === "independent";
49
+ }
35
50
  function enumValue(value, values, fallback) {
36
51
  if (value === undefined)
37
52
  return fallback;
@@ -40,35 +55,70 @@ function enumValue(value, values, fallback) {
40
55
  }
41
56
  return value;
42
57
  }
43
- function taskIds(value) {
44
- if (value === undefined)
45
- return [];
46
- if (!Array.isArray(value))
47
- throw new Error("control.dependsOn must be an array of task ids");
48
- if (value.some((item) => typeof item !== "string" || !TASK_ID_PATTERN.test(item.trim()))) {
49
- throw new Error("control.dependsOn contains an invalid task id");
58
+ /**
59
+ * Values retired from an enum are read back as their canonical replacement rather than failing
60
+ * the parse, so task files written by an older build stay readable; the next write normalizes
61
+ * them on disk and no migration script is needed. Keys retired outright are simply ignored:
62
+ * `control.isolation`, and — per spec 036 — `parent`, `dependsOn`, `worktree`, `lifetimeUsage`
63
+ * and the `budget.max{Tokens,CostUsd,WallTimeMinutes}` trio. They are listed in
64
+ * `RETIRED_TASK_CONTROL_KEYS` so `/tasks doctor` can report what a stored task still carries;
65
+ * dropping `parent`/`dependsOn` silently discards an ordering intent the user once expressed,
66
+ * which is exactly why it must be reported rather than only ignored (D8).
67
+ */
68
+ function canonicalEnumValue(value) {
69
+ switch (value) {
70
+ // The read-only/workspace split never gated anything; only `external` has semantics.
71
+ case "read-only":
72
+ return "workspace";
73
+ // Outcomes once written by `task_manage` actions; the runtime now owns this field and
74
+ // records only how the last run ended.
75
+ case "verified":
76
+ case "skipped":
77
+ return "progress";
78
+ default:
79
+ return value;
50
80
  }
51
- return Array.from(new Set(value
52
- .filter((item) => typeof item === "string")
53
- .map((item) => item.trim())
54
- .filter((item) => TASK_ID_PATTERN.test(item))));
55
81
  }
56
- function validateTaskId(value, field) {
57
- if (value && !TASK_ID_PATTERN.test(value))
58
- throw new Error(`${field} contains an invalid task id: ${value}`);
82
+ /**
83
+ * Control keys that older builds wrote and this one ignores (spec 036, D8).
84
+ *
85
+ * Ignoring them keeps stored tasks readable with no migration script, but silence would be
86
+ * wrong for `parent`/`dependsOn`: the task survives, the ordering constraint it expressed does
87
+ * not. `/tasks doctor` reports whatever a stored control block still carries so the loss is
88
+ * visible rather than silent.
89
+ */
90
+ export const RETIRED_TASK_CONTROL_KEYS = [
91
+ "parent",
92
+ "dependsOn",
93
+ "worktree",
94
+ "lifetimeUsage",
95
+ "isolation",
96
+ "budget.maxTokens",
97
+ "budget.maxCostUsd",
98
+ "budget.maxWallTimeMinutes",
99
+ ];
100
+ /** Retired keys actually present in a raw stored control block, in `RETIRED_TASK_CONTROL_KEYS` order. */
101
+ export function retiredTaskControlKeys(raw) {
102
+ if (!isRecord(raw))
103
+ return [];
104
+ return RETIRED_TASK_CONTROL_KEYS.filter((key) => {
105
+ const [head, nested] = key.split(".");
106
+ if (!nested)
107
+ return Object.hasOwn(raw, head);
108
+ const parent = raw[head];
109
+ return isRecord(parent) && Object.hasOwn(parent, nested);
110
+ });
59
111
  }
60
- export function createDefaultTaskControl(mode = "independent") {
112
+ export function createDefaultTaskControl(requiresVerification = false) {
61
113
  return {
62
114
  version: 1,
63
115
  priority: "normal",
64
116
  lastOutcome: "pending",
65
- dependsOn: [],
66
- isolation: "shared",
67
117
  sideEffects: "workspace",
68
118
  externalApproval: "not-required",
69
119
  budget: { maxAttempts: 12 },
70
- usage: { attempts: 0, tokens: 0, costUsd: 0, wallTimeMinutes: 0 },
71
- verification: { mode, status: "pending" },
120
+ usage: { attempts: 0, tokens: 0, costUsd: 0, costKnown: true, wallTimeMinutes: 0 },
121
+ verification: { required: requiresVerification, status: "pending" },
72
122
  };
73
123
  }
74
124
  export function parseTaskControl(raw) {
@@ -84,8 +134,8 @@ export function parseTaskControl(raw) {
84
134
  }
85
135
  const budget = isRecord(value.budget) ? value.budget : {};
86
136
  const usage = isRecord(value.usage) ? value.usage : {};
137
+ const parsedUsage = parseTaskUsage(usage);
87
138
  const verification = isRecord(value.verification) ? value.verification : {};
88
- const worktree = isRecord(value.worktree) ? value.worktree : undefined;
89
139
  const maxAttempts = optionalPositive(budget.maxAttempts);
90
140
  if (!maxAttempts || !Number.isInteger(maxAttempts)) {
91
141
  throw new Error("control.budget.maxAttempts must be a positive integer");
@@ -94,9 +144,7 @@ export function parseTaskControl(raw) {
94
144
  if (deadline && !Number.isFinite(new Date(deadline).getTime())) {
95
145
  throw new Error("control.deadline must be a valid ISO8601 date");
96
146
  }
97
- const parent = optionalString(value.parent);
98
- validateTaskId(parent, "control.parent");
99
- const sideEffects = enumValue(value.sideEffects, SIDE_EFFECTS, "workspace");
147
+ const sideEffects = enumValue(canonicalEnumValue(value.sideEffects), SIDE_EFFECTS, "workspace");
100
148
  const externalApproval = enumValue(value.externalApproval, ["not-required", "required", "granted"], "not-required");
101
149
  const approvalBy = optionalString(value.approvalBy);
102
150
  const approvedAt = optionalString(value.approvedAt);
@@ -110,38 +158,22 @@ export function parseTaskControl(raw) {
110
158
  !/^[a-f0-9]{64}$/i.test(approvalBodyHash))) {
111
159
  throw new Error("granted external approval requires external side effects, approvalBy, approvedAt, and approvalBodyHash");
112
160
  }
113
- if (value.worktree !== undefined && (!worktree || !optionalString(worktree.path))) {
114
- throw new Error("control.worktree must contain a non-empty path");
115
- }
116
161
  return {
117
162
  version: 1,
118
163
  priority: enumValue(value.priority, PRIORITIES, "normal"),
119
164
  deadline,
120
165
  nextAction: optionalString(value.nextAction),
121
- lastOutcome: enumValue(value.lastOutcome, OUTCOMES, "pending"),
166
+ lastOutcome: enumValue(canonicalEnumValue(value.lastOutcome), OUTCOMES, "pending"),
122
167
  blockedReason: optionalString(value.blockedReason),
123
- parent,
124
- dependsOn: taskIds(value.dependsOn),
125
- isolation: enumValue(value.isolation, ISOLATIONS, "shared"),
126
168
  sideEffects,
127
169
  externalApproval,
128
170
  approvalBy,
129
171
  approvedAt,
130
172
  approvalBodyHash,
131
- budget: {
132
- maxAttempts: Math.max(1, Math.floor(maxAttempts)),
133
- maxTokens: optionalPositive(budget.maxTokens),
134
- maxCostUsd: optionalPositive(budget.maxCostUsd),
135
- maxWallTimeMinutes: optionalPositive(budget.maxWallTimeMinutes),
136
- },
137
- usage: {
138
- attempts: Math.floor(finiteNonNegative(usage.attempts)),
139
- tokens: Math.floor(finiteNonNegative(usage.tokens)),
140
- costUsd: finiteNonNegative(usage.costUsd),
141
- wallTimeMinutes: finiteNonNegative(usage.wallTimeMinutes),
142
- },
173
+ budget: { maxAttempts: Math.max(1, Math.floor(maxAttempts)) },
174
+ usage: parsedUsage,
143
175
  verification: {
144
- mode: enumValue(verification.mode, VERIFICATION_MODES, "independent"),
176
+ required: parseVerificationRequired(verification),
145
177
  status: enumValue(verification.status, VERIFICATION_STATUSES, "pending"),
146
178
  runId: optionalString(verification.runId),
147
179
  evidence: optionalString(verification.evidence),
@@ -149,9 +181,6 @@ export function parseTaskControl(raw) {
149
181
  checkedAt: optionalString(verification.checkedAt),
150
182
  subjectHash: optionalString(verification.subjectHash),
151
183
  },
152
- worktree: optionalString(worktree?.path)
153
- ? { path: optionalString(worktree?.path), branch: optionalString(worktree?.branch) }
154
- : undefined,
155
184
  lastStartedAt: optionalString(value.lastStartedAt),
156
185
  lastFinishedAt: optionalString(value.lastFinishedAt),
157
186
  cycleId: optionalString(value.cycleId),
@@ -176,9 +205,8 @@ export function resetTaskControlForCycle(control, cycleId) {
176
205
  approvalBy: undefined,
177
206
  approvedAt: undefined,
178
207
  approvalBodyHash: undefined,
179
- usage: { attempts: 0, tokens: 0, costUsd: 0, wallTimeMinutes: 0 },
180
- verification: { mode: control.verification.mode, status: "pending" },
181
- worktree: undefined,
208
+ usage: { attempts: 0, tokens: 0, costUsd: 0, costKnown: true, wallTimeMinutes: 0 },
209
+ verification: { required: control.verification.required, status: "pending" },
182
210
  lastStartedAt: undefined,
183
211
  lastFinishedAt: undefined,
184
212
  cycleId: normalizedCycleId,
@@ -190,13 +218,6 @@ function patchOptionalString(current, value) {
190
218
  return current;
191
219
  return value.trim() || undefined;
192
220
  }
193
- function patchPositive(current, value, field) {
194
- if (value === undefined)
195
- return current;
196
- if (!Number.isFinite(value) || value < 0)
197
- throw new Error(`${field} must be a non-negative number.`);
198
- return value === 0 ? undefined : value;
199
- }
200
221
  export function applyTaskControlPatch(control, patch) {
201
222
  const next = structuredClone(control);
202
223
  const invalidatesApproval = control.externalApproval === "granted" && Object.keys(patch).length > 0;
@@ -208,18 +229,7 @@ export function applyTaskControlPatch(control, patch) {
208
229
  }
209
230
  next.deadline = patchOptionalString(next.deadline, patch.deadline);
210
231
  next.nextAction = patchOptionalString(next.nextAction, patch.nextAction);
211
- if (patch.lastOutcome !== undefined)
212
- next.lastOutcome = patch.lastOutcome;
213
232
  next.blockedReason = patchOptionalString(next.blockedReason, patch.blockedReason);
214
- next.parent = patchOptionalString(next.parent, patch.parent);
215
- validateTaskId(next.parent, "parent");
216
- if (patch.dependsOn !== undefined) {
217
- for (const dependency of patch.dependsOn)
218
- validateTaskId(dependency.trim(), "dependsOn");
219
- next.dependsOn = taskIds(patch.dependsOn);
220
- }
221
- if (patch.isolation !== undefined)
222
- next.isolation = patch.isolation;
223
233
  if (patch.sideEffects !== undefined)
224
234
  next.sideEffects = patch.sideEffects;
225
235
  if (patch.externalApproval !== undefined)
@@ -230,16 +240,8 @@ export function applyTaskControlPatch(control, patch) {
230
240
  }
231
241
  next.budget.maxAttempts = patch.maxAttempts;
232
242
  }
233
- next.budget.maxTokens = patchPositive(next.budget.maxTokens, patch.maxTokens, "maxTokens");
234
- next.budget.maxCostUsd = patchPositive(next.budget.maxCostUsd, patch.maxCostUsd, "maxCostUsd");
235
- next.budget.maxWallTimeMinutes = patchPositive(next.budget.maxWallTimeMinutes, patch.maxWallTimeMinutes, "maxWallTimeMinutes");
236
- if (patch.verificationMode !== undefined && patch.verificationMode !== next.verification.mode) {
237
- next.verification = { mode: patch.verificationMode, status: "pending" };
238
- }
239
- if (patch.worktreePath !== undefined || patch.worktreeBranch !== undefined) {
240
- const path = patchOptionalString(next.worktree?.path, patch.worktreePath);
241
- const branch = patchOptionalString(next.worktree?.branch, patch.worktreeBranch);
242
- next.worktree = path ? { path, branch } : undefined;
243
+ if (patch.verificationRequired !== undefined && patch.verificationRequired !== next.verification.required) {
244
+ next.verification = { required: patch.verificationRequired, status: "pending" };
243
245
  }
244
246
  if (next.sideEffects !== "external") {
245
247
  next.externalApproval = "not-required";
@@ -250,6 +252,15 @@ export function applyTaskControlPatch(control, patch) {
250
252
  if (control.sideEffects !== "external" && next.sideEffects === "external" && !explicitlySetsExternalApproval) {
251
253
  next.externalApproval = "required";
252
254
  }
255
+ // Spec 036 D5: a task that changes an outside system is exactly the one nobody is watching
256
+ // under unattended operation, so it defaults to requiring independent acceptance. An explicit
257
+ // `verificationRequired: false` still wins.
258
+ if (control.sideEffects !== "external" &&
259
+ next.sideEffects === "external" &&
260
+ patch.verificationRequired === undefined &&
261
+ !next.verification.required) {
262
+ next.verification = { required: true, status: "pending" };
263
+ }
253
264
  if (invalidatesApproval && next.sideEffects === "external" && !explicitlySetsExternalApproval) {
254
265
  next.externalApproval = "required";
255
266
  }
@@ -272,22 +283,12 @@ export function taskBudgetViolation(control, nowMs) {
272
283
  if (control.usage.attempts >= control.budget.maxAttempts) {
273
284
  return `attempt budget exhausted (${control.usage.attempts}/${control.budget.maxAttempts})`;
274
285
  }
275
- if (control.budget.maxTokens !== undefined && control.usage.tokens >= control.budget.maxTokens) {
276
- return `token budget exhausted (${control.usage.tokens}/${control.budget.maxTokens})`;
277
- }
278
- if (control.budget.maxCostUsd !== undefined && control.usage.costUsd >= control.budget.maxCostUsd) {
279
- return `cost budget exhausted ($${control.usage.costUsd.toFixed(4)}/$${control.budget.maxCostUsd.toFixed(4)})`;
280
- }
281
- if (control.budget.maxWallTimeMinutes !== undefined &&
282
- control.usage.wallTimeMinutes >= control.budget.maxWallTimeMinutes) {
283
- return `wall-time budget exhausted (${control.usage.wallTimeMinutes.toFixed(1)}/${control.budget.maxWallTimeMinutes}m)`;
284
- }
285
286
  return undefined;
286
287
  }
287
288
  export function invalidateTaskVerification(control) {
288
289
  if (control.verification.status === "pending")
289
290
  return control;
290
- return { ...control, verification: { mode: control.verification.mode, status: "pending" } };
291
+ return { ...control, verification: { required: control.verification.required, status: "pending" } };
291
292
  }
292
293
  export function invalidateTaskApproval(control) {
293
294
  if (control.sideEffects !== "external" || control.externalApproval !== "granted")