@oyasmi/pipiclaw 0.9.3-beta.5 → 0.9.3-beta.6

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 (142) 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/project-scope-store.d.ts +20 -0
  11. package/dist/channel/project-scope-store.js +22 -7
  12. package/dist/commands/catalog.js +6 -12
  13. package/dist/events/event-commands.js +2 -2
  14. package/dist/events/events.d.ts +51 -30
  15. package/dist/events/events.js +70 -98
  16. package/dist/memory/journal.d.ts +2 -3
  17. package/dist/memory/journal.js +2 -3
  18. package/dist/memory/maintenance-tuning.d.ts +0 -1
  19. package/dist/memory/maintenance-tuning.js +0 -1
  20. package/dist/memory/scheduler.js +8 -16
  21. package/dist/memory/search.js +2 -3
  22. package/dist/memory/session-search.js +3 -9
  23. package/dist/memory/store.d.ts +1 -1
  24. package/dist/memory/store.js +9 -1
  25. package/dist/memory/task-digest.js +10 -11
  26. package/dist/memory/tombstones.js +2 -4
  27. package/dist/models/provider-login.d.ts +1 -1
  28. package/dist/models/provider-login.js +1 -1
  29. package/dist/playbooks/agent-delegation.md +6 -6
  30. package/dist/playbooks/background-jobs.md +1 -1
  31. package/dist/playbooks/event-scheduling.md +22 -13
  32. package/dist/playbooks/memory-and-learning.md +2 -2
  33. package/dist/playbooks/outbound-media.md +1 -1
  34. package/dist/playbooks/runtime-orientation.md +3 -3
  35. package/dist/playbooks/task-lead.md +82 -0
  36. package/dist/runtime/bootstrap.js +95 -187
  37. package/dist/runtime/durable-dispatch.js +30 -3
  38. package/dist/runtime/report-commands.d.ts +30 -0
  39. package/dist/runtime/report-commands.js +71 -0
  40. package/dist/runtime/subagent-commands.js +1 -1
  41. package/dist/runtime/task-commands.d.ts +0 -8
  42. package/dist/runtime/task-commands.js +48 -85
  43. package/dist/runtime/task-driver.d.ts +13 -9
  44. package/dist/runtime/task-driver.js +34 -39
  45. package/dist/runtime/task-migration.d.ts +18 -29
  46. package/dist/runtime/task-migration.js +195 -183
  47. package/dist/runtime/task-spawn.d.ts +24 -0
  48. package/dist/runtime/task-spawn.js +49 -0
  49. package/dist/runtime/task-wake.d.ts +33 -46
  50. package/dist/runtime/task-wake.js +15 -90
  51. package/dist/security/network.js +44 -9
  52. package/dist/settings.d.ts +1 -8
  53. package/dist/settings.js +1 -8
  54. package/dist/subagents/discovery.js +3 -15
  55. package/dist/subagents/external/run.d.ts +3 -1
  56. package/dist/subagents/external/run.js +2 -20
  57. package/dist/subagents/external/settlement.d.ts +4 -16
  58. package/dist/subagents/external/settlement.js +16 -67
  59. package/dist/subagents/runs.d.ts +15 -29
  60. package/dist/subagents/runs.js +70 -158
  61. package/dist/subagents/tool.d.ts +20 -4
  62. package/dist/subagents/tool.js +63 -87
  63. package/dist/subagents/verification-outcome.d.ts +13 -19
  64. package/dist/subagents/verification-outcome.js +8 -22
  65. package/dist/subagents/workspace-summary.d.ts +8 -0
  66. package/dist/subagents/workspace-summary.js +29 -0
  67. package/dist/tasks/board.d.ts +43 -0
  68. package/dist/tasks/board.js +134 -0
  69. package/dist/tasks/brief.d.ts +10 -5
  70. package/dist/tasks/brief.js +78 -26
  71. package/dist/tasks/budget.d.ts +13 -14
  72. package/dist/tasks/budget.js +21 -40
  73. package/dist/tasks/contract-input.d.ts +19 -0
  74. package/dist/tasks/contract-input.js +55 -0
  75. package/dist/tasks/create.d.ts +17 -0
  76. package/dist/tasks/create.js +36 -0
  77. package/dist/tasks/frontmatter.d.ts +20 -27
  78. package/dist/tasks/frontmatter.js +18 -31
  79. package/dist/tasks/ledger.d.ts +61 -117
  80. package/dist/tasks/ledger.js +78 -223
  81. package/dist/tasks/log.d.ts +62 -35
  82. package/dist/tasks/log.js +51 -29
  83. package/dist/tasks/session-path.d.ts +3 -3
  84. package/dist/tasks/session-path.js +4 -5
  85. package/dist/tasks/store.d.ts +11 -29
  86. package/dist/tasks/store.js +39 -83
  87. package/dist/tasks/ticket.d.ts +33 -66
  88. package/dist/tasks/ticket.js +31 -120
  89. package/dist/tasks/work-log.d.ts +20 -0
  90. package/dist/tasks/work-log.js +42 -0
  91. package/dist/tools/bash.d.ts +1 -1
  92. package/dist/tools/bash.js +1 -1
  93. package/dist/tools/event-manage.d.ts +16 -2
  94. package/dist/tools/event-manage.js +30 -12
  95. package/dist/tools/index.d.ts +5 -3
  96. package/dist/tools/index.js +5 -5
  97. package/dist/tools/registry.d.ts +6 -4
  98. package/dist/tools/registry.js +1 -4
  99. package/dist/tools/subagent-manage.js +4 -2
  100. package/dist/tools/task-manage/create.js +11 -27
  101. package/dist/tools/task-manage/lifecycle.d.ts +6 -7
  102. package/dist/tools/task-manage/lifecycle.js +23 -106
  103. package/dist/tools/task-manage/log-view.d.ts +3 -2
  104. package/dist/tools/task-manage/log-view.js +6 -6
  105. package/dist/tools/task-manage/schema.d.ts +10 -30
  106. package/dist/tools/task-manage/schema.js +33 -49
  107. package/dist/tools/task-manage/shared.d.ts +35 -42
  108. package/dist/tools/task-manage/shared.js +53 -192
  109. package/dist/tools/task-manage/step-end.d.ts +6 -6
  110. package/dist/tools/task-manage/step-end.js +61 -98
  111. package/dist/tools/task-manage/types.d.ts +8 -9
  112. package/dist/tools/task-manage.js +5 -5
  113. package/dist/tui/app.js +11 -38
  114. package/dist/tui/commands.d.ts +18 -8
  115. package/dist/tui/commands.js +2 -9
  116. package/dist/tui/turn-controller.d.ts +2 -14
  117. package/dist/tui/turn-controller.js +1 -17
  118. package/dist/web/client.js +9 -1
  119. package/examples/sub-agents/README.md +7 -4
  120. package/examples/sub-agents/agents/codex-flash.md +2 -2
  121. package/examples/sub-agents/agents/codex-high.md +1 -1
  122. package/examples/sub-agents/agents/codex-main.md +1 -1
  123. package/examples/sub-agents/agents/codex-review.md +23 -0
  124. package/examples/sub-agents/roles/verifier.md +1 -1
  125. package/package.json +1 -1
  126. package/dist/memory/maintenance-migration.d.ts +0 -5
  127. package/dist/memory/maintenance-migration.js +0 -91
  128. package/dist/memory/migrate.d.ts +0 -15
  129. package/dist/memory/migrate.js +0 -364
  130. package/dist/playbooks/task-loop.md +0 -90
  131. package/dist/tasks/artifact-subject.d.ts +0 -40
  132. package/dist/tasks/artifact-subject.js +0 -334
  133. package/dist/tasks/cycle.d.ts +0 -48
  134. package/dist/tasks/cycle.js +0 -94
  135. package/dist/tasks/rounds.d.ts +0 -41
  136. package/dist/tasks/rounds.js +0 -53
  137. package/dist/tasks/task-events.d.ts +0 -6
  138. package/dist/tasks/task-events.js +0 -14
  139. package/dist/tasks/task-schedule.d.ts +0 -18
  140. package/dist/tasks/task-schedule.js +0 -50
  141. package/dist/tasks/verification.d.ts +0 -114
  142. package/dist/tasks/verification.js +0 -226
package/README.en.md CHANGED
@@ -22,7 +22,7 @@ In DingTalk daemon mode, external tasks keep running in the background after dis
22
22
 
23
23
  ### Work does not end when a conversation ends
24
24
 
25
- Every session has its own current state, long-term memory, and history summary. The task ledger persists goals, done criteria, progress, next steps, and verification records to Markdown files; the built-in task driver resumes work from waiting tickets and schedules, and stops with a notice when a budget, idle-loop, or repeated-expiry boundary is reached.
25
+ Every channel has its own persistent conversation, long-term memory index, and daily journal. The task ledger stores goals, done criteria, and plans in Markdown contracts, with steps and verification records in JSONL loop logs; the built-in task driver resumes work from waiting tickets and schedules, and stops with a notice when a budget, idle-loop, or repeated-expiry boundary is reached.
26
26
 
27
27
  ### Natively at home in DingTalk
28
28
 
package/README.md CHANGED
@@ -22,7 +22,7 @@ Pipiclaw 同时支持两类委派:内置子智能体在进程内完成检索
22
22
 
23
23
  ### 工作不会随着一次对话结束
24
24
 
25
- 每个会话都有独立的当前状态、长期记忆和历史摘要。任务台账把目标、完成标准、进度、下一步和验收记录持久化到 Markdown 文件;内建 task driver 根据等待票和周期调度恢复工作,预算耗尽、空转或连续无法兑现等待时会停止并告诉你。
25
+ 每个频道都有独立的持久会话、长期记忆索引和按天日志。任务台账用 Markdown 保存目标、完成标准和计划,用 JSONL 循环日志记录步骤与验收;内建 task driver 根据等待票和周期调度恢复工作,预算耗尽、空转或连续无法兑现等待时会停止并告诉你。
26
26
 
27
27
  ### 原生工作在钉钉里
28
28
 
@@ -217,9 +217,6 @@ export declare class ChannelRunner implements AgentRunner {
217
217
  private reloadSessionResources;
218
218
  private bindSessionExtensions;
219
219
  private ensureSessionReady;
220
- /** Spec 050 §5: migrate this channel's memory to v2 on first use, before any turn reads it. */
221
- private memoryMigrationChecked;
222
- private ensureMemoryMigrated;
223
220
  private maybeRunPreventiveCompactionForIncomingText;
224
221
  private refreshSubAgentDiscovery;
225
222
  private reportSettingsDiagnostics;
@@ -261,10 +258,10 @@ export declare class ChannelRunner implements AgentRunner {
261
258
  * Task work must not accumulate in the channel's chat transcript: the one real channel on the
262
259
  * author's machine had grown to 7.4 MB and been compacted six times because chat and two daily
263
260
  * tasks shared it, so every compaction damaged all three at once. Swapping the bound session
264
- * per turn gives each cycle its own bounded context while leaving turn state, `/stop`, and
261
+ * per turn gives each task its own bounded context while leaving turn state, `/stop`, and
265
262
  * delivery exactly where they already are.
266
263
  */
267
- bindTaskSession(taskId: string, cycleId: string): Promise<void>;
264
+ bindTaskSession(taskId: string): Promise<void>;
268
265
  /** Return to the channel's chat session after a task step. Safe to call when already bound. */
269
266
  bindChatSession(): Promise<void>;
270
267
  /**
@@ -286,7 +283,6 @@ export declare class ChannelRunner implements AgentRunner {
286
283
  /** Which task loop this runner is currently bound to, if any. */
287
284
  getTaskLoop(): {
288
285
  taskId: string;
289
- cycleId: string;
290
286
  } | undefined;
291
287
  private buildRuntimeTools;
292
288
  private rebuildSessionTools;
@@ -295,8 +291,8 @@ export declare class ChannelRunner implements AgentRunner {
295
291
  private buildTaskDigestForTurn;
296
292
  /**
297
293
  * Spec 050, D1: assemble `<memory_bootstrap>` for the first turn of a session — workspace
298
- * MEMORY.md (whole H2 sections, budgeted) + the channel index (full, or budget-tiered). The
299
- * journal subsection is added in P2.
294
+ * MEMORY.md (whole H2 sections, budgeted) + the channel index (full, or budget-tiered) +
295
+ * today's journal tail.
300
296
  */
301
297
  private buildFirstTurnMemoryBootstrap;
302
298
  }
@@ -13,7 +13,6 @@ import { buildChannelIndexForBootstrap, clipJournalTailForBootstrap, clipWorkspa
13
13
  import { readJournalDay } from "../memory/journal.js";
14
14
  import { MemoryLifecycle } from "../memory/lifecycle.js";
15
15
  import { createMemoryActivityRecorder, } from "../memory/maintenance-state.js";
16
- import { isChannelMigratedToV2, migrateChannelMemoryToV2 } from "../memory/migrate.js";
17
16
  import { hasMemoryBootstrapBlock, renderMemoryBootstrap } from "../memory/render.js";
18
17
  import { listMemoryEntries } from "../memory/store.js";
19
18
  import { buildTaskDigest, TASK_AGENDA_MAX_UNITS } from "../memory/task-digest.js";
@@ -28,7 +27,6 @@ import { errorMessage } from "../shared/text-utils.js";
28
27
  import { isRecord } from "../shared/type-guards.js";
29
28
  import { withTimeout } from "../shared/with-timeout.js";
30
29
  import { discoverSubAgents } from "../subagents/discovery.js";
31
- import { SubAgentRunManager } from "../subagents/runs.js";
32
30
  import { TASK_SESSIONS_DIRNAME, taskSessionPath } from "../tasks/session-path.js";
33
31
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
34
32
  import { createPipiclawTools } from "../tools/index.js";
@@ -36,7 +34,6 @@ import { formatSize } from "../tools/truncate.js";
36
34
  import { getUsageLedger } from "../usage/ledger.js";
37
35
  import { createCommandExtension } from "./command-extension.js";
38
36
  import { estimateIncomingMessageTokens, getPreventiveCompactionDecision } from "./context-budget.js";
39
- import { ChannelJobManager } from "./job-manager.js";
40
37
  import { PRIMARY_COOLDOWN_MS, runPromptWithFallback, shouldRestorePrimary, } from "./model-fallback.js";
41
38
  import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
42
39
  import { buildPipiclawSystemPrompt } from "./prompt/builder.js";
@@ -113,8 +110,6 @@ export class ChannelRunner {
113
110
  this.primaryFailedAt = null;
114
111
  // --- Per run ---
115
112
  this.runState = createEmptyRunState();
116
- /** Spec 050 §5: migrate this channel's memory to v2 on first use, before any turn reads it. */
117
- this.memoryMigrationChecked = false;
118
113
  this.channelId = channelId;
119
114
  this.channelDir = channelDir;
120
115
  this.appHomeDir = paths.appHomeDir;
@@ -123,8 +118,8 @@ export class ChannelRunner {
123
118
  this.onSessionEvent = paths.onSessionEvent;
124
119
  this.mediaSender = paths.mediaSender;
125
120
  this.executor = deps.executor;
126
- this.jobManager = paths.jobManager ?? new ChannelJobManager(channelId, deps.executor);
127
- this.runManager = paths.runManager ?? new SubAgentRunManager(channelId, {});
121
+ this.jobManager = paths.jobManager;
122
+ this.runManager = paths.runManager;
128
123
  this.fileStore = deps.fileStore;
129
124
  this.loadSecurityConfig = deps.loadSecurityConfig;
130
125
  this.workspaceDir = resolve(dirname(channelDir));
@@ -235,7 +230,6 @@ export class ChannelRunner {
235
230
  let bootstrapPrepared = false;
236
231
  try {
237
232
  await this.ensureSessionReady();
238
- await this.ensureMemoryMigrated();
239
233
  await this.maybeRestorePrimaryModel();
240
234
  this.memoryLifecycle.noteUserTurnStarted();
241
235
  const normalizedInputLength = ctx.message.text.replace(/\r/g, "").trim().length;
@@ -260,8 +254,9 @@ export class ChannelRunner {
260
254
  // Settled into a result object rather than left as a bare promise: if the bootstrap
261
255
  // throws first we would otherwise leave a rejection unobserved, which Node's default
262
256
  // policy turns into a process exit. Rethrown at the await, so a digest failure still
263
- // fails the turn exactly as it did when this ran inline.
264
- const taskDigestPromise = (this.tasksEnabled ? this.buildTaskDigestForTurn() : Promise.resolve("")).then((text) => ({ text }), (error) => ({ error }));
257
+ // fails the turn exactly as it did when this ran inline. A task step gets none: its brief
258
+ // already carries its own task, and the channel's other tasks are noise there.
259
+ const taskDigestPromise = (this.tasksEnabled && !this.taskLoop ? this.buildTaskDigestForTurn() : Promise.resolve("")).then((text) => ({ text }), (error) => ({ error }));
265
260
  // Spec 050, D1: the memory index is injected in full on the first turn of a session
266
261
  // (and the first turn after compaction — see `subscribeToSessionEvents`), never per
267
262
  // turn. Mid-session, the model uses `memory_search` to look things up.
@@ -1084,24 +1079,6 @@ export class ChannelRunner {
1084
1079
  async ensureSessionReady() {
1085
1080
  await this.sessionReady;
1086
1081
  }
1087
- async ensureMemoryMigrated() {
1088
- if (this.memoryMigrationChecked) {
1089
- return;
1090
- }
1091
- this.memoryMigrationChecked = true;
1092
- if (isChannelMigratedToV2(this.channelDir)) {
1093
- return;
1094
- }
1095
- try {
1096
- const result = await migrateChannelMemoryToV2(this.channelDir);
1097
- if (result.migrated) {
1098
- log.logInfo(`[${this.channelId}] Migrated channel memory to v2 (${result.entries} entries, ${result.journalDays} journal days)`);
1099
- }
1100
- }
1101
- catch (error) {
1102
- log.logWarning(`[${this.channelId}] Channel memory v2 migration failed`, errorMessage(error));
1103
- }
1104
- }
1105
1082
  async maybeRunPreventiveCompactionForIncomingText(incomingText, imageCount = 0) {
1106
1083
  const currentModel = this.session.model ?? this.activeModel;
1107
1084
  const contextUsage = this.session.getContextUsage();
@@ -1328,14 +1305,14 @@ export class ChannelRunner {
1328
1305
  * Task work must not accumulate in the channel's chat transcript: the one real channel on the
1329
1306
  * author's machine had grown to 7.4 MB and been compacted six times because chat and two daily
1330
1307
  * tasks shared it, so every compaction damaged all three at once. Swapping the bound session
1331
- * per turn gives each cycle its own bounded context while leaving turn state, `/stop`, and
1308
+ * per turn gives each task its own bounded context while leaving turn state, `/stop`, and
1332
1309
  * delivery exactly where they already are.
1333
1310
  */
1334
- async bindTaskSession(taskId, cycleId) {
1311
+ async bindTaskSession(taskId) {
1335
1312
  await this.sessionReady;
1336
- const path = taskSessionPath(this.channelDir, taskId, cycleId);
1313
+ const path = taskSessionPath(this.channelDir, taskId);
1337
1314
  await mkdir(dirname(path), { recursive: true });
1338
- this.taskLoop = { taskId, cycleId };
1315
+ this.taskLoop = { taskId };
1339
1316
  await this.sessionRuntime.switchSession(path);
1340
1317
  this.syncMemoryBootstrapPendingFromSession();
1341
1318
  }
@@ -1401,6 +1378,9 @@ export class ChannelRunner {
1401
1378
  mediaSender: this.mediaSender,
1402
1379
  taskLoop: this.taskLoop,
1403
1380
  getToolsUsed: () => this.runState.toolsUsed,
1381
+ // Assistant usage only: an internal sub-agent's cost is also in `totalUsage`, and a bound
1382
+ // one is already credited to the task when it settles.
1383
+ getStepCost: () => ({ usd: this.runState.assistantUsage.cost.total, estimated: !this.runState.costKnown }),
1404
1384
  });
1405
1385
  this.currentTools = tools;
1406
1386
  // Tool schemas are billed with the system prompt and, unlike it, nothing trims them.
@@ -1477,8 +1457,8 @@ export class ChannelRunner {
1477
1457
  }
1478
1458
  /**
1479
1459
  * Spec 050, D1: assemble `<memory_bootstrap>` for the first turn of a session — workspace
1480
- * MEMORY.md (whole H2 sections, budgeted) + the channel index (full, or budget-tiered). The
1481
- * journal subsection is added in P2.
1460
+ * MEMORY.md (whole H2 sections, budgeted) + the channel index (full, or budget-tiered) +
1461
+ * today's journal tail.
1482
1462
  */
1483
1463
  async buildFirstTurnMemoryBootstrap() {
1484
1464
  const readOptionalFile = async (path) => {
@@ -26,6 +26,8 @@ export interface JobSnapshot {
26
26
  startedAt: number;
27
27
  durationMs: number;
28
28
  exitCode?: number;
29
+ /** The job's own wall-clock limit; a task's `work` ticket derives its backstop from it. */
30
+ timeoutSeconds: number;
29
31
  /** The task this job's completion wake belongs to, if any — lets a caller verify that a
30
32
  * `[JOB:<id>] ... belongs to task <taskId>.` wake actually names the job it claims to (T9). */
31
33
  taskId?: string;
@@ -55,6 +57,8 @@ interface JobRecord extends JobSnapshot {
55
57
  finishedAt?: number;
56
58
  /** Set once the completion wake has been dispatched, so a restart cannot re-announce it. */
57
59
  notified?: boolean;
60
+ /** Set once the owning task's log has this job's settlement (spec 052, D4); guards against a second record. */
61
+ taskLogged?: boolean;
58
62
  /**
59
63
  * A cancel or timeout whose kill could not be *confirmed* yet: the job stays `running` and
60
64
  * manageable, and every sweep re-attempts the kill until the process is proven gone, at which
@@ -80,6 +84,8 @@ export interface JobManagerOptions {
80
84
  /** Directory the full-output spill (and its `.exit`/`.ready`/`.meta` siblings) is written to.
81
85
  * Defaults to the OS temp dir; the runtime passes `<channelDir>/logs` so the model can read it. */
82
86
  spillDir?: string;
87
+ /** This channel's directory, where a task-bound job logs its dispatch and settlement (spec 052, D4). */
88
+ channelDir?: string;
83
89
  }
84
90
  /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
85
91
  export declare const MAX_RUNNING_JOBS = 5;
@@ -198,6 +204,12 @@ export declare class ChannelJobManager {
198
204
  private applyProbe;
199
205
  /** Move a job to a terminal status: record it, persist it, and wake the channel once. */
200
206
  private finish;
207
+ /**
208
+ * Tell the owning task this job settled (spec 052, D4). Runs before the completion wake is
209
+ * dispatched, so the step the wake starts already finds the result on its board. Best-effort and
210
+ * once-only: a task that no longer exists, or a replayed finish, writes nothing.
211
+ */
212
+ private logSettlementToTask;
201
213
  /**
202
214
  * Wake the channel for a finished job. `dispatch()` durably persists its own pending record
203
215
  * (and is idempotent on dispatch id) before this call can be interrupted, so it is safe to call
@@ -11,6 +11,7 @@ import { createSerialQueue } from "../shared/serial-queue.js";
11
11
  import { errorMessage } from "../shared/text-utils.js";
12
12
  import { isRecord } from "../shared/type-guards.js";
13
13
  import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
14
+ import { logTaskDispatch, logTaskSettlement } from "../tasks/work-log.js";
14
15
  function jobArtifacts(spillFile) {
15
16
  return {
16
17
  spillFile,
@@ -193,6 +194,7 @@ function toSnapshot(record) {
193
194
  startedAt: record.startedAt,
194
195
  durationMs: record.status === "running" ? Date.now() - record.startedAt : record.durationMs,
195
196
  exitCode: record.exitCode,
197
+ timeoutSeconds: record.timeoutSeconds,
196
198
  taskId: record.contract.taskId,
197
199
  };
198
200
  }
@@ -408,6 +410,15 @@ export class ChannelJobManager {
408
410
  });
409
411
  throw failure;
410
412
  }
413
+ if (options.taskId && this.options.channelDir) {
414
+ await logTaskDispatch(this.options.channelDir, options.taskId, {
415
+ ref: id,
416
+ agent: "job",
417
+ label,
418
+ }).catch((error) => {
419
+ log.logWarning(`Failed to log dispatch of job ${id} to task ${options.taskId}`, errorMessage(error));
420
+ });
421
+ }
411
422
  this.ensureSweeper();
412
423
  return toSnapshot(record);
413
424
  }
@@ -678,9 +689,34 @@ export class ChannelJobManager {
678
689
  record.notified = true;
679
690
  }
680
691
  await this.persist(record);
692
+ await this.logSettlementToTask(record);
681
693
  await this.announce(record, signal);
682
694
  this.scheduleGarbageCollection();
683
695
  }
696
+ /**
697
+ * Tell the owning task this job settled (spec 052, D4). Runs before the completion wake is
698
+ * dispatched, so the step the wake starts already finds the result on its board. Best-effort and
699
+ * once-only: a task that no longer exists, or a replayed finish, writes nothing.
700
+ */
701
+ async logSettlementToTask(record) {
702
+ const taskId = record.contract.taskId;
703
+ const channelDir = this.options.channelDir;
704
+ if (!taskId || !channelDir || record.taskLogged)
705
+ return;
706
+ record.taskLogged = true;
707
+ const output = await this.readOutput(record.id).catch(() => undefined);
708
+ await logTaskSettlement(channelDir, taskId, {
709
+ ref: record.id,
710
+ status: record.status,
711
+ exitCode: record.exitCode,
712
+ output: record.spillFile,
713
+ tail: output?.text.slice(-WAKE_OUTPUT_TAIL_BYTES).trim() || undefined,
714
+ durationMs: record.durationMs,
715
+ }).catch((error) => {
716
+ log.logWarning(`Failed to log settlement of job ${record.id} to task ${taskId}`, errorMessage(error));
717
+ });
718
+ await this.persist(record);
719
+ }
684
720
  /**
685
721
  * Wake the channel for a finished job. `dispatch()` durably persists its own pending record
686
722
  * (and is idempotent on dispatch id) before this call can be interrupted, so it is safe to call
@@ -990,7 +1026,12 @@ export function createJobRuntime(executor, options = {}) {
990
1026
  if (!manager) {
991
1027
  manager = new ChannelJobManager(channelId, executor, {
992
1028
  ...(config.jobsStateDir ? { stateDir: join(config.jobsStateDir, channelId) } : {}),
993
- ...(config.workspaceDir ? { spillDir: join(getChannelDir(config.workspaceDir, channelId), "logs") } : {}),
1029
+ ...(config.workspaceDir
1030
+ ? {
1031
+ spillDir: join(getChannelDir(config.workspaceDir, channelId), "logs"),
1032
+ channelDir: getChannelDir(config.workspaceDir, channelId),
1033
+ }
1034
+ : {}),
994
1035
  ...(config.dispatch ? { dispatch: config.dispatch } : {}),
995
1036
  ...(config.sweepIntervalMs ? { sweepIntervalMs: config.sweepIntervalMs } : {}),
996
1037
  });
@@ -91,7 +91,7 @@ export const TASK_CORE_SECTION = {
91
91
  overflow: "error",
92
92
  render: () => [
93
93
  "## Persistent Work",
94
- "Use a task only when work must survive this turn. Chat creates or manages tasks; the runtime drives them in task sessions. Follow the task's contract and runtime guide without expanding its scope or bypassing verification.",
94
+ "Use a task when work must survive this turn, has several pieces to delegate, or needs to wait on results; you lead it — split, delegate, check, report. Recurring or scheduled work is an event with a task template. Chat creates or manages tasks; the runtime drives them in task sessions. Follow the task's contract and runtime guide without expanding its scope.",
95
95
  ].join("\n"),
96
96
  };
97
97
  export const PLAYBOOKS_SECTION = {
@@ -178,7 +178,7 @@ function renderSubAgentDirectory(subAgents) {
178
178
  lines.push(`- ${agent.name} — ${agent.description}${suffix}`);
179
179
  }
180
180
  }
181
- lines.push("", "Read agent-delegation.md before non-trivial delegation, and task-loop.md before independent verification.");
181
+ lines.push("", "Read agent-delegation.md before non-trivial delegation, and task-lead.md before leading a multi-item task.");
182
182
  return lines.join("\n");
183
183
  }
184
184
  const WORKSPACE_PREAMBLE = "The files below are workspace policy chosen by the user or the team. They direct how you work; they do not override the runtime facts and hard invariants above.";
@@ -7,8 +7,8 @@ import type { SubAgentRunManager } from "../subagents/runs.js";
7
7
  import type { ChannelJobManager } from "./job-manager.js";
8
8
  import type { AgentRunner } from "./types.js";
9
9
  export interface RunnerFactoryPaths {
10
- jobManager?: ChannelJobManager;
11
- runManager?: SubAgentRunManager;
10
+ jobManager: ChannelJobManager;
11
+ runManager: SubAgentRunManager;
12
12
  appHomeDir: string;
13
13
  authConfigPath: string;
14
14
  modelsConfigPath: string;
@@ -58,17 +58,21 @@ export interface AgentRunner {
58
58
  getSubAgentDiscoverySnapshot(): SubAgentDiscoveryResult;
59
59
  abort(): Promise<void>;
60
60
  /** True when the SDK is currently summarizing context. */
61
- isCompacting?(): boolean;
61
+ isCompacting(): boolean;
62
62
  /** Cancel context summarization synchronously; returns whether one was active. */
63
- interruptCompaction?(): boolean;
63
+ interruptCompaction(): boolean;
64
64
  /**
65
- * Bind this runner to a task cycle's own session for the next turn, and back afterwards
66
- * (spec 051, D3). Optional: the TUI runs one session per process and never routes task steps.
65
+ * Bind this runner to a task's own session for the next turn, and back afterwards
66
+ * (spec 051, D3).
67
67
  */
68
- bindTaskSession?(taskId: string, cycleId: string): Promise<void>;
69
- bindChatSession?(): Promise<void>;
68
+ bindTaskSession(taskId: string): Promise<void>;
69
+ bindChatSession(): Promise<void>;
70
+ /** The task whose session this runner is bound to right now, if a task step is running. */
71
+ getTaskLoop(): {
72
+ taskId: string;
73
+ } | undefined;
70
74
  /** Permanently retire this runner generation after an out-of-band `/new`. */
71
- retireForNewSession?(): void;
75
+ retireForNewSession(): void;
72
76
  /**
73
77
  * Synchronously reserve the turn for a message. Transports MUST call this in
74
78
  * the same tick they dequeue the message, before any await, so a concurrent
@@ -8,6 +8,26 @@ export interface PersistedProjectSelectionV1 {
8
8
  updatedBy: "migration" | "dingtalk-command" | "tui-command";
9
9
  }
10
10
  export declare function getProjectSelectionPath(channelDir: string): string;
11
+ /**
12
+ * `missing` (never selected — a plain default) and `corrupt` (a selection existed but the file
13
+ * cannot be read back) must not collapse into the same "nothing here" signal (R7a):
14
+ * `resolveProjectScope` used to treat both as "never selected" and silently overwrite a corrupt
15
+ * file with the app default, which moved a channel to a different project root without the user
16
+ * ever choosing that.
17
+ */
18
+ export type ReadProjectSelectionResult = {
19
+ kind: "missing";
20
+ } | {
21
+ kind: "corrupt";
22
+ } | {
23
+ kind: "valid";
24
+ selection: PersistedProjectSelectionV1;
25
+ };
26
+ export declare function readProjectSelectionResult(channelDir: string): ReadProjectSelectionResult;
27
+ /** Collapses `corrupt` into `undefined` alongside `missing`, for display-only callers (`/project
28
+ * show`) that already have their own "not chosen yet" wording and do not make a resolution
29
+ * decision. `resolveProjectScope` uses {@link readProjectSelectionResult} directly instead,
30
+ * because it must not conflate the two. */
11
31
  export declare function readProjectSelection(channelDir: string): PersistedProjectSelectionV1 | undefined;
12
32
  export declare function commitProjectSelection(channelDir: string, projectRoot: string, updatedBy: PersistedProjectSelectionV1["updatedBy"]): Promise<PersistedProjectSelectionV1>;
13
33
  export type ProjectScopeOutcome = {
@@ -6,17 +6,17 @@ const SELECTION_FILENAME = "project.json";
6
6
  export function getProjectSelectionPath(channelDir) {
7
7
  return join(channelDir, SELECTION_FILENAME);
8
8
  }
9
- export function readProjectSelection(channelDir) {
9
+ export function readProjectSelectionResult(channelDir) {
10
10
  const path = getProjectSelectionPath(channelDir);
11
11
  if (!existsSync(path)) {
12
- return undefined;
12
+ return { kind: "missing" };
13
13
  }
14
14
  let raw;
15
15
  try {
16
16
  raw = JSON.parse(readFileSync(path, "utf-8"));
17
17
  }
18
18
  catch {
19
- return undefined;
19
+ return { kind: "corrupt" };
20
20
  }
21
21
  if (!raw ||
22
22
  typeof raw !== "object" ||
@@ -24,9 +24,17 @@ export function readProjectSelection(channelDir) {
24
24
  typeof raw.projectRoot !== "string" ||
25
25
  typeof raw.updatedAt !== "string" ||
26
26
  typeof raw.updatedBy !== "string") {
27
- return undefined;
27
+ return { kind: "corrupt" };
28
28
  }
29
- return raw;
29
+ return { kind: "valid", selection: raw };
30
+ }
31
+ /** Collapses `corrupt` into `undefined` alongside `missing`, for display-only callers (`/project
32
+ * show`) that already have their own "not chosen yet" wording and do not make a resolution
33
+ * decision. `resolveProjectScope` uses {@link readProjectSelectionResult} directly instead,
34
+ * because it must not conflate the two. */
35
+ export function readProjectSelection(channelDir) {
36
+ const result = readProjectSelectionResult(channelDir);
37
+ return result.kind === "valid" ? result.selection : undefined;
30
38
  }
31
39
  /** Used only for the one-time, in-constructor migration write (D3.3); every explicit mutation
32
40
  * (`/project set|reset`) goes through the async `writeFileAtomically` in `commitProjectSelection`
@@ -54,8 +62,14 @@ export async function commitProjectSelection(channelDir, projectRoot, updatedBy)
54
62
  export function resolveProjectScope(channelDir, resolution) {
55
63
  const sandbox = currentProjectSandboxStatus();
56
64
  const boundary = resolution.configured ? "project" : "unbounded";
57
- const existing = readProjectSelection(channelDir);
58
- if (!existing) {
65
+ const result = readProjectSelectionResult(channelDir);
66
+ if (result.kind === "corrupt") {
67
+ return {
68
+ kind: "blocked",
69
+ reason: `项目选择文件已损坏:${getProjectSelectionPath(channelDir)}。请检查该文件,或在频道空闲时执行 /project set <path> 或 /project reset 重新选择——不会自动回退到默认项目。`,
70
+ };
71
+ }
72
+ if (result.kind === "missing") {
59
73
  const selection = {
60
74
  version: 1,
61
75
  projectRoot: resolution.policy.defaultRoot,
@@ -65,6 +79,7 @@ export function resolveProjectScope(channelDir, resolution) {
65
79
  writeProjectSelectionSync(channelDir, selection);
66
80
  return { kind: "ready", scope: { projectRoot: resolution.policy.defaultRoot, boundary, sandbox }, selection };
67
81
  }
82
+ const existing = result.selection;
68
83
  if (!existsSync(existing.projectRoot)) {
69
84
  return {
70
85
  kind: "blocked",
@@ -72,7 +72,7 @@ export const BUILT_IN_COMMANDS = [
72
72
  },
73
73
  {
74
74
  name: "tasks",
75
- argumentHint: "[show <id>|log <id>|steer <id> <内容>|reply <id> <内容>|pause <id>|resume <id> [+steps N]|run <id>|archive|doctor]",
75
+ argumentHint: "[show <id>|log <id>|steer <id> <内容>|reply <id> <内容>|pause <id>|resume <id> [+steps N|+usd X]|archive|doctor]",
76
76
  description: "查看、指挥并诊断本频道的长程任务;pause 只停用执行,保留阶段与等待票",
77
77
  availableWhileBusy: true,
78
78
  subcommands: [
@@ -80,13 +80,13 @@ export const BUILT_IN_COMMANDS = [
80
80
  {
81
81
  name: "show",
82
82
  args: "<id>",
83
- description: "查看契约、最近日志、返工轮次与成本",
83
+ description: "查看契约、团队看板、最近日志与用量",
84
84
  example: "/tasks show weekly-report",
85
85
  },
86
86
  {
87
87
  name: "log",
88
- args: "<id> [cycle]",
89
- description: "翻看该任务的循环日志",
88
+ args: "<id>",
89
+ description: "翻看该任务的循环日志(含派发与结算记录)",
90
90
  example: "/tasks log weekly-report",
91
91
  },
92
92
  { name: "archive", description: "列出已归档(已关闭)的任务", example: "/tasks archive" },
@@ -98,16 +98,10 @@ export const BUILT_IN_COMMANDS = [
98
98
  },
99
99
  {
100
100
  name: "resume",
101
- args: "<id> [+steps N|+rounds N|+usd X]",
102
- description: "重新启用该任务,可同时追加本周期预算",
101
+ args: "<id> [+steps N|+usd X]",
102
+ description: "重新启用该任务,可同时追加预算",
103
103
  example: "/tasks resume weekly-report +steps 20",
104
104
  },
105
- {
106
- name: "run",
107
- args: "<id>",
108
- description: "恢复并立即排入一次执行(需要运行时可用)",
109
- example: "/tasks run weekly-report",
110
- },
111
105
  {
112
106
  name: "steer",
113
107
  args: "<id> <内容>",
@@ -5,7 +5,7 @@ import { renderSubcommandUsage } from "../commands/catalog.js";
5
5
  import { capReply } from "../commands/reply-limits.js";
6
6
  import { normalizeSafeId, resolveSafeIdPath } from "../shared/safe-id.js";
7
7
  import { errorMessage, eventNameFromFilename, clipText as sharedClipText } from "../shared/text-utils.js";
8
- import { parseScheduledEventContent } from "./events.js";
8
+ import { describeEventPayload, parseScheduledEventContent, } from "./events.js";
9
9
  const EVENT_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
10
10
  const DEFAULT_HISTORY_LIMIT = 20;
11
11
  const TEXT_PREVIEW_MAX_CHARS = 100;
@@ -63,7 +63,7 @@ function formatEventSummary(name, event) {
63
63
  if (event.type === "periodic") {
64
64
  lines.push(`- schedule:${event.schedule}`);
65
65
  }
66
- lines.push(`- 内容:${clipText(event.text)}`);
66
+ lines.push(`- 内容:${clipText(describeEventPayload(event))}`);
67
67
  return lines.join("\n");
68
68
  }
69
69
  async function listEvents(workspaceDir) {