@oyasmi/pipiclaw 0.9.3-beta.5 → 0.9.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 (144) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/agent/channel-runner.d.ts +4 -8
  4. package/dist/agent/channel-runner.js +14 -34
  5. package/dist/agent/job-manager.d.ts +12 -0
  6. package/dist/agent/job-manager.js +42 -1
  7. package/dist/agent/prompt/sections.js +2 -2
  8. package/dist/agent/runner-factory.d.ts +2 -2
  9. package/dist/agent/types.d.ts +11 -7
  10. package/dist/channel/channel-index.d.ts +9 -2
  11. package/dist/channel/channel-index.js +25 -6
  12. package/dist/channel/project-scope-store.d.ts +20 -0
  13. package/dist/channel/project-scope-store.js +22 -7
  14. package/dist/commands/catalog.js +6 -12
  15. package/dist/events/event-commands.js +2 -2
  16. package/dist/events/events.d.ts +51 -30
  17. package/dist/events/events.js +70 -98
  18. package/dist/memory/journal.d.ts +2 -3
  19. package/dist/memory/journal.js +2 -3
  20. package/dist/memory/maintenance-tuning.d.ts +0 -1
  21. package/dist/memory/maintenance-tuning.js +0 -1
  22. package/dist/memory/scheduler.js +8 -16
  23. package/dist/memory/search.js +2 -3
  24. package/dist/memory/session-search.js +3 -9
  25. package/dist/memory/store.d.ts +1 -1
  26. package/dist/memory/store.js +9 -1
  27. package/dist/memory/task-digest.js +10 -11
  28. package/dist/memory/tombstones.js +2 -4
  29. package/dist/models/provider-login.d.ts +1 -1
  30. package/dist/models/provider-login.js +1 -1
  31. package/dist/playbooks/agent-delegation.md +6 -6
  32. package/dist/playbooks/background-jobs.md +1 -1
  33. package/dist/playbooks/event-scheduling.md +22 -13
  34. package/dist/playbooks/memory-and-learning.md +2 -2
  35. package/dist/playbooks/outbound-media.md +1 -1
  36. package/dist/playbooks/runtime-orientation.md +3 -3
  37. package/dist/playbooks/task-lead.md +82 -0
  38. package/dist/runtime/bootstrap.js +94 -187
  39. package/dist/runtime/durable-dispatch.js +30 -3
  40. package/dist/runtime/report-commands.d.ts +30 -0
  41. package/dist/runtime/report-commands.js +71 -0
  42. package/dist/runtime/subagent-commands.js +1 -1
  43. package/dist/runtime/task-commands.d.ts +0 -8
  44. package/dist/runtime/task-commands.js +48 -85
  45. package/dist/runtime/task-driver.d.ts +15 -10
  46. package/dist/runtime/task-driver.js +36 -41
  47. package/dist/runtime/task-migration.d.ts +23 -29
  48. package/dist/runtime/task-migration.js +364 -183
  49. package/dist/runtime/task-spawn.d.ts +24 -0
  50. package/dist/runtime/task-spawn.js +49 -0
  51. package/dist/runtime/task-wake.d.ts +33 -46
  52. package/dist/runtime/task-wake.js +15 -90
  53. package/dist/security/network.js +44 -9
  54. package/dist/settings.d.ts +1 -8
  55. package/dist/settings.js +1 -8
  56. package/dist/subagents/discovery.js +3 -15
  57. package/dist/subagents/external/run.d.ts +3 -1
  58. package/dist/subagents/external/run.js +2 -20
  59. package/dist/subagents/external/settlement.d.ts +4 -16
  60. package/dist/subagents/external/settlement.js +16 -67
  61. package/dist/subagents/runs.d.ts +15 -29
  62. package/dist/subagents/runs.js +70 -158
  63. package/dist/subagents/tool.d.ts +20 -4
  64. package/dist/subagents/tool.js +63 -87
  65. package/dist/subagents/verification-outcome.d.ts +13 -19
  66. package/dist/subagents/verification-outcome.js +8 -22
  67. package/dist/subagents/workspace-summary.d.ts +8 -0
  68. package/dist/subagents/workspace-summary.js +29 -0
  69. package/dist/tasks/board.d.ts +43 -0
  70. package/dist/tasks/board.js +134 -0
  71. package/dist/tasks/brief.d.ts +10 -5
  72. package/dist/tasks/brief.js +78 -26
  73. package/dist/tasks/budget.d.ts +13 -14
  74. package/dist/tasks/budget.js +21 -40
  75. package/dist/tasks/contract-input.d.ts +19 -0
  76. package/dist/tasks/contract-input.js +55 -0
  77. package/dist/tasks/create.d.ts +17 -0
  78. package/dist/tasks/create.js +36 -0
  79. package/dist/tasks/frontmatter.d.ts +20 -27
  80. package/dist/tasks/frontmatter.js +18 -31
  81. package/dist/tasks/ledger.d.ts +61 -117
  82. package/dist/tasks/ledger.js +78 -223
  83. package/dist/tasks/log.d.ts +62 -35
  84. package/dist/tasks/log.js +51 -29
  85. package/dist/tasks/session-path.d.ts +3 -3
  86. package/dist/tasks/session-path.js +4 -5
  87. package/dist/tasks/store.d.ts +27 -28
  88. package/dist/tasks/store.js +89 -83
  89. package/dist/tasks/ticket.d.ts +33 -66
  90. package/dist/tasks/ticket.js +31 -120
  91. package/dist/tasks/work-log.d.ts +20 -0
  92. package/dist/tasks/work-log.js +42 -0
  93. package/dist/tools/bash.d.ts +1 -1
  94. package/dist/tools/bash.js +1 -1
  95. package/dist/tools/event-manage.d.ts +16 -2
  96. package/dist/tools/event-manage.js +30 -12
  97. package/dist/tools/index.d.ts +5 -3
  98. package/dist/tools/index.js +5 -5
  99. package/dist/tools/registry.d.ts +6 -4
  100. package/dist/tools/registry.js +1 -4
  101. package/dist/tools/subagent-manage.js +4 -2
  102. package/dist/tools/task-manage/create.js +11 -27
  103. package/dist/tools/task-manage/lifecycle.d.ts +6 -7
  104. package/dist/tools/task-manage/lifecycle.js +23 -106
  105. package/dist/tools/task-manage/log-view.d.ts +3 -2
  106. package/dist/tools/task-manage/log-view.js +6 -6
  107. package/dist/tools/task-manage/schema.d.ts +10 -30
  108. package/dist/tools/task-manage/schema.js +33 -49
  109. package/dist/tools/task-manage/shared.d.ts +35 -42
  110. package/dist/tools/task-manage/shared.js +53 -192
  111. package/dist/tools/task-manage/step-end.d.ts +6 -6
  112. package/dist/tools/task-manage/step-end.js +61 -98
  113. package/dist/tools/task-manage/types.d.ts +8 -9
  114. package/dist/tools/task-manage.js +5 -5
  115. package/dist/tui/app.js +11 -38
  116. package/dist/tui/commands.d.ts +18 -8
  117. package/dist/tui/commands.js +2 -9
  118. package/dist/tui/turn-controller.d.ts +2 -14
  119. package/dist/tui/turn-controller.js +1 -17
  120. package/dist/web/client.js +9 -1
  121. package/examples/sub-agents/README.md +7 -4
  122. package/examples/sub-agents/agents/codex-flash.md +2 -2
  123. package/examples/sub-agents/agents/codex-high.md +1 -1
  124. package/examples/sub-agents/agents/codex-main.md +1 -1
  125. package/examples/sub-agents/agents/codex-review.md +23 -0
  126. package/examples/sub-agents/roles/verifier.md +1 -1
  127. package/package.json +1 -1
  128. package/dist/memory/maintenance-migration.d.ts +0 -5
  129. package/dist/memory/maintenance-migration.js +0 -91
  130. package/dist/memory/migrate.d.ts +0 -15
  131. package/dist/memory/migrate.js +0 -364
  132. package/dist/playbooks/task-loop.md +0 -90
  133. package/dist/tasks/artifact-subject.d.ts +0 -40
  134. package/dist/tasks/artifact-subject.js +0 -334
  135. package/dist/tasks/cycle.d.ts +0 -48
  136. package/dist/tasks/cycle.js +0 -94
  137. package/dist/tasks/rounds.d.ts +0 -41
  138. package/dist/tasks/rounds.js +0 -53
  139. package/dist/tasks/task-events.d.ts +0 -6
  140. package/dist/tasks/task-events.js +0 -14
  141. package/dist/tasks/task-schedule.d.ts +0 -18
  142. package/dist/tasks/task-schedule.js +0 -50
  143. package/dist/tasks/verification.d.ts +0 -114
  144. package/dist/tasks/verification.js +0 -226
@@ -19,6 +19,7 @@ declare const subagentSchema: Type.TObject<{
19
19
  workingDirectory: Type.TOptional<Type.TString>;
20
20
  purpose: Type.TOptional<Type.TUnion<[Type.TLiteral<"work">, Type.TLiteral<"verify">]>>;
21
21
  taskId: Type.TOptional<Type.TString>;
22
+ item: Type.TOptional<Type.TString>;
22
23
  }>;
23
24
  /**
24
25
  * Inline delegation (spec 046, D2.1): a one-off executor for when no configured role fits.
@@ -36,6 +37,7 @@ declare const subagentInlineSchema: Type.TObject<{
36
37
  workingDirectory: Type.TOptional<Type.TString>;
37
38
  purpose: Type.TOptional<Type.TUnion<[Type.TLiteral<"work">, Type.TLiteral<"verify">]>>;
38
39
  taskId: Type.TOptional<Type.TString>;
40
+ item: Type.TOptional<Type.TString>;
39
41
  }>;
40
42
  /**
41
43
  * Fields the `subagent` tool itself constructs. `kind` is not among them: `withToolDetails`
@@ -106,6 +108,16 @@ export interface SubAgentToolOptions {
106
108
  syncGraceMs?: number;
107
109
  /** Channel manager owned by the application; also a seam for admission failures. */
108
110
  getRunManager: (channelId: string) => SubAgentRunManager;
111
+ /** Present only inside a task session: every delegation is bound to this task automatically (spec 052, D4). */
112
+ boundTaskId?: string;
113
+ }
114
+ /** The delegation parameters both invocation surfaces share (`task` plus routing). */
115
+ export interface DelegationParams {
116
+ task: string;
117
+ workingDirectory?: string;
118
+ purpose?: "work" | "verify";
119
+ taskId?: string;
120
+ item?: string;
109
121
  }
110
122
  interface SubAgentWorker {
111
123
  state: {
@@ -136,6 +148,7 @@ export interface SubAgentRunContext {
136
148
  runId: string;
137
149
  purpose: "work" | "verify";
138
150
  taskId?: string;
151
+ item?: string;
139
152
  workingDirectory: string;
140
153
  artifactDir: string;
141
154
  }
@@ -155,12 +168,16 @@ export declare function assertWithinProjectBoundary(target: string, base: string
155
168
  * (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
156
169
  */
157
170
  declare function buildSubagentTools(executor: Executor, bashTimeoutSec: number, options: SubAgentToolOptions, runContext: SubAgentRunContext): AgentTool<any>[];
158
- /** Shared by both runtimes' task envelopes and `subagent_run`'s verify follow-up (spec 040, D9). */
159
- export declare function buildVerificationProtocol(taskPath: string): string;
171
+ /**
172
+ * Shared by both runtimes' task envelopes and `subagent_run`'s verify follow-up (spec 040, D9).
173
+ * A check bound to a Work Item covers that item only: holding it to the whole DoD would fail it
174
+ * for the items still in progress.
175
+ */
176
+ export declare function buildVerificationProtocol(taskPath: string | undefined, item?: string): string;
160
177
  /**
161
178
  * D9 verify admission — `exec` has no protocol terminal to prove it even ran to completion, and a
162
179
  * target with an active write lease is refused up front. A write-capable verifier is allowed: it
163
- * takes the same exclusive lease as a work writer and receives an advisory attestation.
180
+ * takes the same exclusive lease as a work writer.
164
181
  * Spec 042 D7: exported so `subagent_run op=follow_up` runs the exact same checks the initial
165
182
  * dispatch does, including the remaining `exec` restriction.
166
183
  */
@@ -173,7 +190,6 @@ export declare function assertVerifyAdmissible(config: Pick<ResolvedSubAgentConf
173
190
  * `model`/`modelRef`/`thinkingLevel` just to satisfy a wider type it never touches.
174
191
  */
175
192
  export declare function buildSubAgentTask(task: string, config: Pick<SubAgentConfig, "name">, runtimeContext: SubAgentToolOptions["runtimeContext"], contextBlocks: string[], runContext: SubAgentRunContext): string;
176
- /** Exported for `subagent_run op=follow_up` (spec 042 D7) — same reason as `buildSubAgentTask`. */
177
193
  /** The slice of `SubAgentToolOptions` `buildContextualBlocks` actually reads — narrowed (spec 042
178
194
  * D7) so `subagent_run op=follow_up` only needs to wire these three fields, not the full tool
179
195
  * option surface (executor, discovery, web config, etc. that a context-block build never touches). */
@@ -13,30 +13,34 @@ import { renderMemoryBootstrap } from "../memory/render.js";
13
13
  import { getChannelMemoryDir, getChannelMemoryIndexPath, listMemoryEntries } from "../memory/store.js";
14
14
  import { formatModelReference } from "../models/utils.js";
15
15
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
16
- import { formatLocalTime, localDayKey } from "../shared/local-time.js";
16
+ import { localDayKey } from "../shared/local-time.js";
17
17
  import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
18
18
  import { RecoverableToolError } from "../shared/recoverable-error.js";
19
19
  import { errorMessage, extractAssistantText } from "../shared/text-utils.js";
20
20
  import { addUsage, createEmptyUsageTotals } from "../shared/types.js";
21
21
  import { sleepUnref } from "../shared/with-timeout.js";
22
- import { workspaceSubjectHash, workspaceSubjectSnapshot } from "../tasks/artifact-subject.js";
22
+ import { findTaskItem, parseTaskItems } from "../tasks/ledger.js";
23
23
  import { readStoredTask } from "../tasks/store.js";
24
- import { writeVerificationAttestation } from "../tasks/verification.js";
25
24
  import { describeToolCall } from "../tools/presentation.js";
26
25
  import { buildToolSet } from "../tools/registry.js";
27
26
  import { DEFAULT_THINKING_LEVEL, externalRoleFingerprint, formatSubAgentList, resolveConfiguredRole, resolveInlineAgent, validateSubAgentTask, withSubAgentsDirWriteDeny, } from "./discovery.js";
28
27
  import { launchExternalRun } from "./external/run.js";
29
28
  import { resolveSyncGraceMs } from "./runs.js";
30
- import { resolveVerificationOutcome } from "./verification-outcome.js";
29
+ import { resolveVerificationVerdict } from "./verification-outcome.js";
31
30
  import { acquireWorkspaceLease, findWorkspaceLeaseHolder, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "./workspace-lease.js";
32
31
  /** Shared by both invocation surfaces (spec 046, D2.1). */
33
32
  const workingDirectoryField = Type.Optional(Type.String({
34
33
  description: "Optional existing directory to run the sub-agent in (its shell cwd and relative-path root). Use it to work on another checkout — e.g. a `git worktree add`ed one. Defaults to this runtime's own working directory.",
35
34
  }));
36
35
  const purposeField = Type.Optional(Type.Union([Type.Literal("work"), Type.Literal("verify")], {
37
- description: 'Use "verify" for an independent task acceptance check. A write-capable verifier may run tests/builds; its attestation is advisory.',
36
+ description: 'Use "verify" for an independent check: the sub-agent is given the checker protocol and ends with VERDICT: PASS|FAIL. The verdict is information for you to weigh, not a gate.',
37
+ }));
38
+ const taskIdField = Type.Optional(Type.String({
39
+ description: "Persistent task this work belongs to. Inside a task session it is bound automatically — omit it. In chat, pass it to have the result recorded on that task's board.",
40
+ }));
41
+ const itemField = Type.Optional(Type.String({
42
+ description: 'The task\'s Work Item this delegation is for, e.g. "W2". Requires a task (bound automatically in a task session).',
38
43
  }));
39
- const taskIdField = Type.Optional(Type.String({ description: "Persistent task id, required when purpose=verify." }));
40
44
  /**
41
45
  * Role-based delegation (spec 046, D2.1): the common path. No override fields beyond routing
42
46
  * ones — tools, model, effort, context, thinkingLevel and mutates all live in the role file, so
@@ -48,6 +52,7 @@ const subagentSchema = Type.Object({
48
52
  workingDirectory: workingDirectoryField,
49
53
  purpose: purposeField,
50
54
  taskId: taskIdField,
55
+ item: itemField,
51
56
  });
52
57
  /**
53
58
  * Inline delegation (spec 046, D2.1): a one-off executor for when no configured role fits.
@@ -82,6 +87,7 @@ const subagentInlineSchema = Type.Object({
82
87
  workingDirectory: workingDirectoryField,
83
88
  purpose: purposeField,
84
89
  taskId: taskIdField,
90
+ item: itemField,
85
91
  });
86
92
  const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
87
93
  /**
@@ -190,21 +196,35 @@ function resolveRunWorkingDirectory(requested, options) {
190
196
  }
191
197
  async function prepareRunContext(runId, params, options) {
192
198
  const purpose = params.purpose ?? "work";
193
- const taskId = params.taskId?.trim() || undefined;
194
- if (purpose === "verify" && !taskId)
195
- throw new RecoverableToolError("purpose=verify requires taskId.");
199
+ let taskId = params.taskId?.trim() || undefined;
200
+ // Inside a task session the binding is automatic, like `bash`'s: a delegation from a task step
201
+ // belongs to that task, so the leader never has to remember to pass it (spec 052, D4).
202
+ if (options.boundTaskId) {
203
+ if (taskId && taskId !== options.boundTaskId) {
204
+ throw new RecoverableToolError(`This is task ${options.boundTaskId}'s session — drop taskId (it is bound automatically); "${taskId}" does not belong here.`);
205
+ }
206
+ taskId = options.boundTaskId;
207
+ }
208
+ const item = params.item?.trim() || undefined;
209
+ if (item && !taskId)
210
+ throw new RecoverableToolError("item names a Work Item of a task; pass taskId too.");
196
211
  if (taskId && !TASK_ID_PATTERN.test(taskId))
197
212
  throw new RecoverableToolError(`Invalid taskId: ${taskId}`);
198
- if (taskId && !(await readStoredTask(options.channelDir, taskId))) {
199
- throw new RecoverableToolError(`Task ${taskId} does not exist. Create it with task_create before delegating task-owned work.`);
213
+ if (taskId) {
214
+ const task = await readStoredTask(options.channelDir, taskId);
215
+ if (!task) {
216
+ throw new RecoverableToolError(`Task ${taskId} does not exist. Create it with task_create before delegating task-owned work.`);
217
+ }
218
+ if (item && !findTaskItem(task.body, item)) {
219
+ const known = parseTaskItems(task.body)
220
+ ?.items.map((entry) => entry.id)
221
+ .join(", ");
222
+ throw new RecoverableToolError(`Task ${taskId} has no Work Item "${item}"${known ? ` (known: ${known})` : " (it has no Work Items yet — add one with task_update first)"}.`);
223
+ }
200
224
  }
201
225
  const artifactDir = await prepareArtifactDir(options.channelDir, runId);
202
226
  const workingDirectory = resolveRunWorkingDirectory(params.workingDirectory, options);
203
- return { runId, purpose, taskId, workingDirectory, artifactDir };
204
- }
205
- async function gitWorkspaceState(executor) {
206
- const result = await executor.exec("git status --porcelain=v1 --untracked-files=all", { timeout: 30 });
207
- return result.code === 0 ? result.stdout : undefined;
227
+ return { runId, purpose, taskId, item, workingDirectory, artifactDir };
208
228
  }
209
229
  function isAssistantMessage(message) {
210
230
  return typeof message === "object" && message !== null && "role" in message && message.role === "assistant";
@@ -231,7 +251,7 @@ function buildDispatchedText(runId, agentName, runtimeLabel, workingDirectory) {
231
251
  return (`[Dispatched] runId=${runId}, agent ${agentName} (${runtimeLabel}), working directory ${workingDirectory}.\n` +
232
252
  "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
233
253
  "Finish independent work and dispatches, then end the turn when only waiting remains; do not re-dispatch or poll to wait. " +
234
- "Inside a task step, use task_step_end outcome=park with this run id.");
254
+ 'Inside a task step, use task_step_end outcome=park with ticket {"kind":"work"}.');
235
255
  }
236
256
  /**
237
257
  * `buildContextualBlocks` shared by the external dispatch path and `runToCompletion`'s internal
@@ -338,14 +358,22 @@ function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
338
358
  bashDefaultTimeoutSeconds: bashTimeoutSec,
339
359
  }, { forSubagent: true }).filter((tool) => runContext.purpose !== "verify" || (tool.name !== "write" && tool.name !== "edit"));
340
360
  }
341
- /** Shared by both runtimes' task envelopes and `subagent_run`'s verify follow-up (spec 040, D9). */
342
- export function buildVerificationProtocol(taskPath) {
361
+ /**
362
+ * Shared by both runtimes' task envelopes and `subagent_run`'s verify follow-up (spec 040, D9).
363
+ * A check bound to a Work Item covers that item only: holding it to the whole DoD would fail it
364
+ * for the items still in progress.
365
+ */
366
+ export function buildVerificationProtocol(taskPath, item) {
367
+ const scope = !taskPath
368
+ ? "- Independently inspect the work described in the task above and verify it against concrete evidence."
369
+ : item
370
+ ? `- Independently inspect Work Item ${item} in ${taskPath} — its text and the DoD items it references (\`→ dod:N\`) — and verify it against concrete evidence. Other Work Items are out of scope; do not fail this check because they are unfinished.`
371
+ : `- Independently inspect ${taskPath} and verify every DoD item against concrete evidence.`;
343
372
  return [
344
373
  "Verification protocol:",
345
- `- Independently inspect ${taskPath} and verify every DoD/Verification item against concrete evidence.`,
374
+ scope,
346
375
  "- You are the checker, not the maker. Do not modify the implementation or fix failures to make a check pass; report them.",
347
- "- You may run npm tests/builds and other deterministic checks. Newly created outputs under recognized transient artifact paths (for example .run/, coverage/, build/, dist/ or caches) are allowed, but do not change tracked files or pre-existing untracked product files.",
348
- "- This verification is advisory when the verifier can write or use bash: runtime cannot structurally prove that every write was harmless. Review the diff and evidence before trusting PASS.",
376
+ "- You may run npm tests/builds and other deterministic checks; keep any generated output out of tracked files and product directories.",
349
377
  "- Run deterministic checks when available and distinguish observed evidence from assumptions.",
350
378
  "- End the response with exactly one final line: VERDICT: PASS or VERDICT: FAIL.",
351
379
  ].join("\n");
@@ -353,7 +381,7 @@ export function buildVerificationProtocol(taskPath) {
353
381
  /**
354
382
  * D9 verify admission — `exec` has no protocol terminal to prove it even ran to completion, and a
355
383
  * target with an active write lease is refused up front. A write-capable verifier is allowed: it
356
- * takes the same exclusive lease as a work writer and receives an advisory attestation.
384
+ * takes the same exclusive lease as a work writer.
357
385
  * Spec 042 D7: exported so `subagent_run op=follow_up` runs the exact same checks the initial
358
386
  * dispatch does, including the remaining `exec` restriction.
359
387
  */
@@ -394,8 +422,10 @@ export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, r
394
422
  }
395
423
  lines.push("", `Task:`, taskText);
396
424
  if (runContext.purpose === "verify") {
397
- const taskPath = join(getChannelDir(runtimeContext.workspaceDir, runtimeContext.channelId), "tasks", `${runContext.taskId}.md`);
398
- lines.push("", buildVerificationProtocol(taskPath));
425
+ const taskPath = runContext.taskId
426
+ ? join(getChannelDir(runtimeContext.workspaceDir, runtimeContext.channelId), "tasks", `${runContext.taskId}.md`)
427
+ : undefined;
428
+ lines.push("", buildVerificationProtocol(taskPath, runContext.item));
399
429
  }
400
430
  return lines.join("\n");
401
431
  }
@@ -484,7 +514,7 @@ function createDetails(input) {
484
514
  /**
485
515
  * Shared dispatch path for both `subagent` and `subagent_inline` (spec 046, D2.5): everything
486
516
  * after a role has been resolved into a `ResolvedSubAgentConfig` — workspace lease admission,
487
- * the internal/external fork, budget/turn/tool-call enforcement, verification attestation, and
517
+ * the internal/external fork, budget/turn/tool-call enforcement, the verification verdict, and
488
518
  * the sync-grace/detached-placeholder split — is identical regardless of which schema the model
489
519
  * called through.
490
520
  */
@@ -569,6 +599,7 @@ async function dispatchExternalRun(input) {
569
599
  artifactDir: runContext.artifactDir,
570
600
  purpose: runContext.purpose,
571
601
  taskId: runContext.taskId,
602
+ item: runContext.item,
572
603
  leaseKey,
573
604
  mutates: config.mutates,
574
605
  roleFingerprint: externalRoleFingerprint(config),
@@ -656,6 +687,7 @@ async function dispatchInternalRun(input) {
656
687
  model: formatModelReference(config.model),
657
688
  purpose: runContext.purpose,
658
689
  taskId: runContext.taskId,
690
+ item: runContext.item,
659
691
  workingDirectory: runContext.workingDirectory,
660
692
  artifactDir: runContext.artifactDir,
661
693
  channelDir: options.channelDir,
@@ -703,19 +735,8 @@ async function dispatchInternalRun(input) {
703
735
  };
704
736
  let wallClockTimer;
705
737
  let unsubscribe;
706
- let verifierGitStateBefore;
707
- let verifierSubjectBefore;
708
- let verifierSubjectBaseCommit;
709
- let verifierSubjectBaselineUntrackedPaths;
710
738
  try {
711
739
  const availableTools = (options.buildTools ?? buildSubagentTools)(scopedExecutor, config.bashTimeoutSec, options, runContext);
712
- verifierGitStateBefore = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
713
- if (runContext.purpose === "verify") {
714
- const subjectSnapshot = await workspaceSubjectSnapshot(runContext.workingDirectory);
715
- verifierSubjectBefore = subjectSnapshot?.hash;
716
- verifierSubjectBaseCommit = subjectSnapshot?.baseCommit;
717
- verifierSubjectBaselineUntrackedPaths = subjectSnapshot?.baselineUntrackedPaths;
718
- }
719
740
  worker =
720
741
  options.createWorker?.({
721
742
  subAgent: config,
@@ -861,56 +882,12 @@ async function dispatchInternalRun(input) {
861
882
  (lastAssistantMessage.stopReason === "error" || lastAssistantMessage.stopReason === "aborted"
862
883
  ? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
863
884
  : undefined);
864
- const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
865
- const verifierSubjectAfter = runContext.purpose === "verify"
866
- ? await workspaceSubjectHash(runContext.workingDirectory, verifierSubjectBaseCommit
867
- ? {
868
- baseCommit: verifierSubjectBaseCommit,
869
- baselineUntrackedPaths: verifierSubjectBaselineUntrackedPaths,
870
- }
871
- : {})
872
- : undefined;
873
- // Spec 042 D1: the pass/fail judgment rule is shared with the external verify path
874
- // (`resolveVerificationOutcome`) so there is exactly one place deciding what a verify
875
- // run's own output does and does not prove. Only the attestation write and the
876
- // strength label stay here, since only the internal path can structurally remove
877
- // write/edit from the verifier's tool set.
878
- const verification = runContext.purpose === "verify"
879
- ? resolveVerificationOutcome({
880
- subjectBefore: verifierSubjectBefore,
881
- subjectAfter: verifierSubjectAfter,
882
- gitStateBefore: verifierGitStateBefore,
883
- gitStateAfter: verifierGitStateAfter,
884
- finalText,
885
- runFailed: Boolean(effectiveFailureReason),
886
- })
885
+ // The pass/fail rule is shared with the external verify path (spec 042 D1): one place
886
+ // deciding what a verify run's own output proves. Spec 052, D6: it is the checker's declared
887
+ // verdict, recorded for the leader to weigh — not a runtime-enforced gate.
888
+ const verificationVerdict = runContext.purpose === "verify"
889
+ ? resolveVerificationVerdict({ finalText, runFailed: Boolean(effectiveFailureReason) })
887
890
  : undefined;
888
- const verificationVerdict = verification?.verdict;
889
- // Internal verify always keeps write/edit structurally removed from the verifier's
890
- // tool set (buildSubagentTools above), but `bash` stays available by default and can
891
- // write files just as well. A role that declares mutates: write is advisory even when
892
- // its effective tool list happens not to contain bash: the declaration says this run is
893
- // not structurally read-only. Computed once so the attestation and run record — the
894
- // latter is what the completion wake and `subagent_list` display — cannot disagree.
895
- const internalVerificationStrength = config.mutates === "write" || config.tools.includes("bash") ? "advisory" : "enforced";
896
- if (runContext.purpose === "verify" && runContext.taskId && verification) {
897
- const baseSubjectAvailable = verifierSubjectBaseCommit !== undefined && verifierSubjectBaselineUntrackedPaths !== undefined;
898
- const subjectAvailable = !verification.workspaceChanged && verifierSubjectAfter !== undefined && baseSubjectAvailable;
899
- await writeVerificationAttestation(options.channelDir, {
900
- runId: runContext.runId,
901
- taskId: runContext.taskId,
902
- verdict: verification.verdict,
903
- checkedAt: formatLocalTime(),
904
- evidence: verification.evidence,
905
- workspaceChanged: verification.workspaceChanged,
906
- subjectHash: subjectAvailable ? verifierSubjectAfter : undefined,
907
- subjectDir: subjectAvailable ? runContext.workingDirectory : undefined,
908
- subjectMode: subjectAvailable ? "base-relative" : undefined,
909
- subjectBaseCommit: subjectAvailable ? verifierSubjectBaseCommit : undefined,
910
- subjectBaselineUntrackedPaths: subjectAvailable ? verifierSubjectBaselineUntrackedPaths : undefined,
911
- verificationStrength: internalVerificationStrength,
912
- });
913
- }
914
891
  // Internal runs always report full usage; cost is "unknown" only for the shape a
915
892
  // free/local model produces (tokens spent, nothing billed) — external harnesses
916
893
  // override both explicitly once they land (D4/D9).
@@ -923,7 +900,6 @@ async function dispatchInternalRun(input) {
923
900
  toolCalls,
924
901
  durationMs,
925
902
  verificationVerdict,
926
- verificationStrength: runContext.purpose === "verify" ? internalVerificationStrength : undefined,
927
903
  };
928
904
  if (effectiveFailureReason) {
929
905
  if (!finalText.trim()) {
@@ -1,26 +1,20 @@
1
1
  /**
2
- * The `purpose=verify` judgment rule, shared by the internal verifier path (`tool.ts`) and the
3
- * external one (`external/settlement.ts`) — spec 042 D1. Internal and external verify differ in
4
- * how "did the workspace change" is observed (subject hash vs. a git-status fallback for
5
- * internal; subject hash only for external, since it has no `Executor` to run `git status`
6
- * through), which is why both inputs are accepted here rather than picking one. This function
7
- * does no I/O; writing the attestation itself stays with each caller because `verificationStrength`
8
- * ("enforced" internal vs. "advisory" external) is a fact only the caller knows.
2
+ * The `purpose=verify` verdict rule, shared by the internal verifier path (`tool.ts`) and the
3
+ * external one (`external/settlement.ts`).
4
+ *
5
+ * Spec 052, D6: a verifier's verdict is information for the leader, not a gate the runtime
6
+ * enforces. The runtime no longer snapshots the workspace or writes attestations; it reads the
7
+ * checker's declared `VERDICT:` line, records it on the run and on the task's board, and the
8
+ * leader decides whether to trust it. The only thing the runtime still refuses to believe is a
9
+ * run that did not finish cleanly or did not say anything verdict-shaped.
9
10
  */
10
- export interface ResolveVerificationOutcomeInput {
11
- subjectBefore?: string;
12
- subjectAfter?: string;
13
- /** Internal-only fallback, used when a subject hash could not be computed on either side. */
14
- gitStateBefore?: string;
15
- gitStateAfter?: string;
11
+ export type VerificationVerdict = "pass" | "fail";
12
+ /** The final `VERDICT: PASS|FAIL` line of a checker's output, if there is one. */
13
+ export declare function parseVerificationVerdict(output: string): VerificationVerdict | undefined;
14
+ export interface ResolveVerificationVerdictInput {
16
15
  finalText: string;
17
16
  /** Whether the underlying run itself failed or aborted — a verifier that never finished cleanly
18
17
  * cannot produce a trustworthy PASS regardless of what it printed. */
19
18
  runFailed: boolean;
20
19
  }
21
- export interface VerificationOutcome {
22
- verdict: "pass" | "fail";
23
- workspaceChanged: boolean;
24
- evidence: string;
25
- }
26
- export declare function resolveVerificationOutcome(input: ResolveVerificationOutcomeInput): VerificationOutcome;
20
+ export declare function resolveVerificationVerdict(input: ResolveVerificationVerdictInput): VerificationVerdict;
@@ -1,23 +1,9 @@
1
- import { parseVerificationVerdict } from "../tasks/verification.js";
2
- export function resolveVerificationOutcome(input) {
3
- const subjectComparable = input.subjectBefore !== undefined && input.subjectAfter !== undefined;
4
- const gitComparable = input.gitStateBefore !== undefined && input.gitStateAfter !== undefined;
5
- // Neither pair could be computed — a non-Git checkout, or `git status` itself failing — means
6
- // there is no evidence either way that the verifier left the workspace untouched. Fail closed
7
- // rather than trusting the verifier's own say-so (review 2026-08-23 §2.2): the weakest evidence
8
- // must not carry the same verdict as the strongest.
9
- const comparable = subjectComparable || gitComparable;
10
- const workspaceChanged = subjectComparable
11
- ? input.subjectBefore !== input.subjectAfter
12
- : gitComparable && input.gitStateBefore !== input.gitStateAfter;
13
- const declaredVerdict = parseVerificationVerdict(input.finalText);
14
- const verdict = comparable && declaredVerdict === "pass" && !input.runFailed && !workspaceChanged ? "pass" : "fail";
15
- const evidence = !comparable
16
- ? "Could not determine whether the workspace changed (not a Git checkout, or `git status` failed); refusing to record a PASS without that evidence."
17
- : workspaceChanged
18
- ? "Verifier changed protected workspace content; the attestation is invalid."
19
- : !declaredVerdict
20
- ? "Verifier did not emit the required final VERDICT marker."
21
- : input.finalText.trim().slice(0, 8_000);
22
- return { verdict, workspaceChanged, evidence };
1
+ /** The final `VERDICT: PASS|FAIL` line of a checker's output, if there is one. */
2
+ export function parseVerificationVerdict(output) {
3
+ const value = /(?:^|\n)VERDICT:\s*(PASS|FAIL)\s*$/i.exec(output.trim())?.[1]?.toLowerCase();
4
+ return value === "pass" || value === "fail" ? value : undefined;
5
+ }
6
+ export function resolveVerificationVerdict(input) {
7
+ const declared = parseVerificationVerdict(input.finalText);
8
+ return declared === "pass" && !input.runFailed ? "pass" : "fail";
23
9
  }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * P2-2: a plain-language "what changed" line for a completion wake, so the agent that reads it
3
+ * does not have to spend its own first tool call finding out. `git status --porcelain` only — a
4
+ * convenience for the reader, not evidence of anything. Returns `undefined` on any failure (not a
5
+ * git repo, `git` unavailable) or when nothing changed; a caller with nothing to show should
6
+ * simply omit the line.
7
+ */
8
+ export declare function changedPathsSummary(workingDirectory: string, limit?: number): Promise<string | undefined>;
@@ -0,0 +1,29 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ const execFileAsync = promisify(execFile);
4
+ /**
5
+ * P2-2: a plain-language "what changed" line for a completion wake, so the agent that reads it
6
+ * does not have to spend its own first tool call finding out. `git status --porcelain` only — a
7
+ * convenience for the reader, not evidence of anything. Returns `undefined` on any failure (not a
8
+ * git repo, `git` unavailable) or when nothing changed; a caller with nothing to show should
9
+ * simply omit the line.
10
+ */
11
+ export async function changedPathsSummary(workingDirectory, limit = 20) {
12
+ let statusOutput;
13
+ try {
14
+ const args = ["-C", workingDirectory, "status", "--porcelain=v1", "--untracked-files=all"];
15
+ statusOutput = (await execFileAsync("git", args, { maxBuffer: 4 * 1024 * 1024 })).stdout;
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ const lines = statusOutput
21
+ .split("\n")
22
+ .map((line) => line.trim())
23
+ .filter(Boolean);
24
+ if (lines.length === 0)
25
+ return undefined;
26
+ const shown = lines.slice(0, limit).join(", ");
27
+ const overflow = lines.length > limit ? ` (+${lines.length - limit} more)` : "";
28
+ return `${shown}${overflow}`;
29
+ }
@@ -0,0 +1,43 @@
1
+ import { type TaskItem } from "./ledger.js";
2
+ import { type TaskSettleRecord } from "./log.js";
3
+ /**
4
+ * The team board (spec 052, D5): what the leader's delegations and jobs are doing right now.
5
+ *
6
+ * It is derived from the loop log, never from the run registry — settled runs are garbage
7
+ * collected after a week, while a project can outlive that (INV-5). Every row is one `ref`
8
+ * (a run or job id) with its latest state; rows are grouped under the Work Item they were
9
+ * dispatched for. The board itself carries status and output *paths*; only results that came back
10
+ * since the previous step also carry their tail, in `renderNewResults`.
11
+ */
12
+ export interface BoardRef {
13
+ ref: string;
14
+ item?: string;
15
+ agent?: string;
16
+ purpose?: "work" | "verify";
17
+ dispatchedAtMs: number;
18
+ settled?: TaskSettleRecord;
19
+ /** Settled since the previous step ended — i.e. what this step was (probably) woken for. */
20
+ isNew: boolean;
21
+ }
22
+ export interface TaskBoard {
23
+ items: Array<{
24
+ item: TaskItem;
25
+ refs: BoardRef[];
26
+ }>;
27
+ /** Dispatches that named no Work Item (or one that no longer exists). */
28
+ unlinked: BoardRef[];
29
+ /** Settled, already-seen refs left out to respect the line budget. */
30
+ hiddenSettled: number;
31
+ }
32
+ /** Ref lines the board renders before folding old, already-seen results away. */
33
+ export declare const BOARD_REF_LINE_BUDGET = 12;
34
+ export declare function buildTaskBoard(channelDir: string, taskId: string, body: string): Promise<TaskBoard | undefined>;
35
+ /** Render the `<task_board>` block body. */
36
+ export declare function renderTaskBoard(board: TaskBoard, nowMs?: number): string;
37
+ /**
38
+ * The `<task_results>` block body: what came back since the previous step, as the completion wake
39
+ * showed it — the output's tail and, for a run, what it left changed. A task step's brief replaces
40
+ * the wake text, so without this block a task step would see less of a result than a chat turn.
41
+ * Returns `undefined` when nothing new settled.
42
+ */
43
+ export declare function renderNewResults(board: TaskBoard): string | undefined;
@@ -0,0 +1,134 @@
1
+ import { parseLocalTime } from "../shared/local-time.js";
2
+ import { parseTaskItems } from "./ledger.js";
3
+ import { readTaskLog } from "./log.js";
4
+ /** Ref lines the board renders before folding old, already-seen results away. */
5
+ export const BOARD_REF_LINE_BUDGET = 12;
6
+ export async function buildTaskBoard(channelDir, taskId, body) {
7
+ const records = await readTaskLog(channelDir, taskId, { kinds: ["dispatch", "settle", "step"] });
8
+ const dispatches = new Map();
9
+ const settles = new Map();
10
+ let lastStepIndex = -1;
11
+ records.forEach((record, index) => {
12
+ if (record.kind === "dispatch")
13
+ dispatches.set(record.ref, record);
14
+ else if (record.kind === "settle")
15
+ settles.set(record.ref, { record, index });
16
+ else if (record.kind === "step")
17
+ lastStepIndex = index;
18
+ });
19
+ const refs = [];
20
+ for (const [ref, dispatch] of dispatches) {
21
+ const settle = settles.get(ref);
22
+ refs.push({
23
+ ref,
24
+ item: dispatch.item,
25
+ agent: dispatch.agent,
26
+ purpose: dispatch.purpose,
27
+ dispatchedAtMs: parseLocalTime(dispatch.ts) ?? 0,
28
+ settled: settle?.record,
29
+ isNew: settle !== undefined && settle.index > lastStepIndex,
30
+ });
31
+ }
32
+ // A settle with no dispatch record (a run bound before this version) still belongs on the board.
33
+ for (const [ref, settle] of settles) {
34
+ if (dispatches.has(ref))
35
+ continue;
36
+ refs.push({
37
+ ref,
38
+ item: settle.record.item,
39
+ dispatchedAtMs: parseLocalTime(settle.record.ts) ?? 0,
40
+ settled: settle.record,
41
+ isNew: settle.index > lastStepIndex,
42
+ });
43
+ }
44
+ if (refs.length === 0)
45
+ return undefined;
46
+ // Fold: running and new results always show; then the newest settled ones, up to the budget.
47
+ const mandatory = new Set(refs.filter((entry) => !entry.settled || entry.isNew).map((entry) => entry.ref));
48
+ const room = Math.max(0, BOARD_REF_LINE_BUDGET - mandatory.size);
49
+ const optional = refs
50
+ .filter((entry) => !mandatory.has(entry.ref))
51
+ .sort((a, b) => b.dispatchedAtMs - a.dispatchedAtMs)
52
+ .slice(0, room);
53
+ const shown = new Set([...mandatory, ...optional.map((entry) => entry.ref)]);
54
+ const visible = refs.filter((entry) => shown.has(entry.ref)).sort((a, b) => a.dispatchedAtMs - b.dispatchedAtMs);
55
+ const parsed = parseTaskItems(body)?.items ?? [];
56
+ const known = new Set(parsed.map((item) => item.id.toUpperCase()));
57
+ return {
58
+ items: parsed.map((item) => ({
59
+ item,
60
+ refs: visible.filter((entry) => entry.item?.toUpperCase() === item.id.toUpperCase()),
61
+ })),
62
+ unlinked: visible.filter((entry) => !entry.item || !known.has(entry.item.toUpperCase())),
63
+ hiddenSettled: refs.length - visible.length,
64
+ };
65
+ }
66
+ function formatDuration(ms) {
67
+ const seconds = Math.max(0, Math.round(ms / 1000));
68
+ if (seconds < 90)
69
+ return `${seconds}s`;
70
+ const minutes = Math.round(seconds / 60);
71
+ if (minutes < 90)
72
+ return `${minutes}m`;
73
+ return `${Math.round(minutes / 60)}h`;
74
+ }
75
+ function renderRef(entry, nowMs) {
76
+ const who = [entry.agent, entry.purpose === "verify" ? "verify" : undefined].filter(Boolean).join(", ");
77
+ const label = `${entry.ref}${who ? ` ${who}` : ""}`;
78
+ if (!entry.settled)
79
+ return `${label} running ${formatDuration(nowMs - entry.dispatchedAtMs)}`;
80
+ const settle = entry.settled;
81
+ const parts = [settle.status];
82
+ if (settle.verdict)
83
+ parts.push(`VERDICT ${settle.verdict.toUpperCase()}`);
84
+ if (settle.exitCode !== undefined)
85
+ parts.push(`exit ${settle.exitCode}`);
86
+ if (settle.durationMs !== undefined)
87
+ parts.push(formatDuration(settle.durationMs));
88
+ const tail = [entry.isNew ? "★新" : undefined, settle.output ? `output: ${settle.output}` : undefined]
89
+ .filter(Boolean)
90
+ .join(" · ");
91
+ return `${label} ${parts.join(" ")}${tail ? ` ${tail}` : ""}`;
92
+ }
93
+ const ITEM_MARKER = { todo: " ", done: "x", blocked: "!", dropped: "~" };
94
+ /** Render the `<task_board>` block body. */
95
+ export function renderTaskBoard(board, nowMs = Date.now()) {
96
+ const lines = [];
97
+ for (const { item, refs } of board.items) {
98
+ const head = `- [${ITEM_MARKER[item.status]}] ${item.id} ${item.text}`;
99
+ if (refs.length === 0) {
100
+ lines.push(head);
101
+ continue;
102
+ }
103
+ lines.push(`${head} — ${renderRef(refs[0], nowMs)}`);
104
+ for (const extra of refs.slice(1))
105
+ lines.push(` ↳ ${renderRef(extra, nowMs)}`);
106
+ }
107
+ for (const entry of board.unlinked)
108
+ lines.push(`- (未关联工作项)${renderRef(entry, nowMs)}`);
109
+ if (board.hiddenSettled > 0)
110
+ lines.push(`- (另有 ${board.hiddenSettled} 项已结算且已看过,见 task_log)`);
111
+ return lines.join("\n");
112
+ }
113
+ /**
114
+ * The `<task_results>` block body: what came back since the previous step, as the completion wake
115
+ * showed it — the output's tail and, for a run, what it left changed. A task step's brief replaces
116
+ * the wake text, so without this block a task step would see less of a result than a chat turn.
117
+ * Returns `undefined` when nothing new settled.
118
+ */
119
+ export function renderNewResults(board) {
120
+ const fresh = [...board.items.flatMap((entry) => entry.refs), ...board.unlinked].filter((entry) => entry.isNew && entry.settled);
121
+ if (fresh.length === 0)
122
+ return undefined;
123
+ return fresh
124
+ .map((entry) => {
125
+ const settle = entry.settled;
126
+ const head = [entry.ref, entry.item, entry.agent, settle.status].filter(Boolean).join(" · ");
127
+ const lines = [`[${head}]`];
128
+ if (settle.changed)
129
+ lines.push(`改动(git status):${settle.changed}`);
130
+ lines.push(`<untrusted_agent_output>\n${settle.tail ?? "(无输出)"}\n</untrusted_agent_output>`);
131
+ return lines.join("\n");
132
+ })
133
+ .join("\n\n");
134
+ }