@oyasmi/pipiclaw 0.9.5 → 0.9.6-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/README.en.md +220 -126
  2. package/README.md +217 -123
  3. package/dist/agent/channel-runner.d.ts +1 -1
  4. package/dist/agent/channel-runner.js +1 -1
  5. package/dist/agent/prompt/sections.js +1 -1
  6. package/dist/agent/prompt/types.d.ts +2 -1
  7. package/dist/agent/session/compaction.d.ts +2 -0
  8. package/dist/agent/session/compaction.js +22 -14
  9. package/dist/agent/session/session-host.d.ts +1 -1
  10. package/dist/agent/session/session-host.js +3 -1
  11. package/dist/agent/stop-watchdog.js +5 -1
  12. package/dist/agent/turn/turn-state.d.ts +2 -0
  13. package/dist/agent/turn/turn-state.js +2 -1
  14. package/dist/agent/types.d.ts +3 -1
  15. package/dist/channel/attachments.d.ts +4 -0
  16. package/dist/channel/attachments.js +4 -0
  17. package/dist/channel/store.d.ts +1 -1
  18. package/dist/commands/catalog.js +25 -9
  19. package/dist/commands/router.js +5 -1
  20. package/dist/desk/commands.d.ts +14 -2
  21. package/dist/desk/commands.js +68 -20
  22. package/dist/desk/registry.d.ts +6 -2
  23. package/dist/desk/registry.js +70 -4
  24. package/dist/desk/types.d.ts +17 -0
  25. package/dist/dingtalk/bot.d.ts +1 -1
  26. package/dist/dingtalk/bot.js +4 -3
  27. package/dist/dingtalk/delivery.js +13 -8
  28. package/dist/dingtalk/inbound-media.d.ts +36 -14
  29. package/dist/dingtalk/inbound-media.js +71 -12
  30. package/dist/dingtalk/inbound.d.ts +9 -2
  31. package/dist/dingtalk/inbound.js +18 -2
  32. package/dist/dingtalk/media.d.ts +4 -10
  33. package/dist/dingtalk/media.js +58 -32
  34. package/dist/events/commands.d.ts +2 -0
  35. package/dist/events/commands.js +13 -8
  36. package/dist/events/history.d.ts +9 -0
  37. package/dist/events/history.js +66 -0
  38. package/dist/events/parse.js +7 -3
  39. package/dist/events/types.d.ts +3 -0
  40. package/dist/events/watcher.d.ts +3 -7
  41. package/dist/events/watcher.js +51 -56
  42. package/dist/jobs/kill.d.ts +23 -0
  43. package/dist/jobs/kill.js +65 -0
  44. package/dist/jobs/manager.d.ts +19 -18
  45. package/dist/jobs/manager.js +36 -103
  46. package/dist/memory/reflect.js +23 -3
  47. package/dist/memory/session-corpus.d.ts +1 -1
  48. package/dist/memory/session-corpus.js +70 -1
  49. package/dist/memory/session-search.js +13 -11
  50. package/dist/memory/store.d.ts +2 -0
  51. package/dist/memory/store.js +19 -9
  52. package/dist/playbooks/agent-delegation.md +5 -4
  53. package/dist/playbooks/memory-and-learning.md +1 -1
  54. package/dist/playbooks/task-lead.md +4 -4
  55. package/dist/runtime/bootstrap.d.ts +6 -0
  56. package/dist/runtime/bootstrap.js +11 -7
  57. package/dist/runtime/desk-runtime.d.ts +8 -2
  58. package/dist/runtime/desk-runtime.js +35 -4
  59. package/dist/runtime/durable-dispatch.d.ts +14 -2
  60. package/dist/runtime/durable-dispatch.js +207 -65
  61. package/dist/runtime/ingress-busy.js +17 -8
  62. package/dist/runtime/ingress-deps.d.ts +4 -1
  63. package/dist/runtime/ingress.js +6 -1
  64. package/dist/runtime/request-execution.js +7 -6
  65. package/dist/runtime/shutdown.d.ts +1 -0
  66. package/dist/runtime/shutdown.js +87 -35
  67. package/dist/runtime/task-control.d.ts +1 -0
  68. package/dist/runtime/task-control.js +25 -2
  69. package/dist/runtime/task-lane.d.ts +1 -0
  70. package/dist/runtime/task-lane.js +21 -6
  71. package/dist/runtime/task-step.js +11 -2
  72. package/dist/runtime/turn-run.js +103 -66
  73. package/dist/security/command-guard.d.ts +1 -1
  74. package/dist/security/command-guard.js +237 -314
  75. package/dist/security/path-guard.js +48 -7
  76. package/dist/security/shell-parse.d.ts +10 -0
  77. package/dist/security/shell-parse.js +224 -0
  78. package/dist/security/types.d.ts +2 -0
  79. package/dist/subagents/commands.d.ts +1 -1
  80. package/dist/subagents/detached-discovery.d.ts +1 -1
  81. package/dist/subagents/discovery.d.ts +18 -199
  82. package/dist/subagents/discovery.js +35 -289
  83. package/dist/subagents/dispatch.d.ts +1 -2
  84. package/dist/subagents/dispatch.js +39 -20
  85. package/dist/subagents/external/antigravity-cli.d.ts +2 -0
  86. package/dist/subagents/external/antigravity-cli.js +517 -0
  87. package/dist/subagents/external/claude-code.js +8 -17
  88. package/dist/subagents/external/codex-cli.js +8 -18
  89. package/dist/subagents/external/cursor-cli.js +34 -31
  90. package/dist/subagents/external/dispatch.d.ts +21 -7
  91. package/dist/subagents/external/dispatch.js +139 -11
  92. package/dist/subagents/external/exec.js +3 -0
  93. package/dist/subagents/external/harness.d.ts +57 -33
  94. package/dist/subagents/external/harness.js +69 -40
  95. package/dist/subagents/external/reconciliation.js +1 -0
  96. package/dist/subagents/external/registry.js +4 -1
  97. package/dist/subagents/external/role-warnings.d.ts +4 -13
  98. package/dist/subagents/external/role-warnings.js +4 -28
  99. package/dist/subagents/external/run.d.ts +1 -2
  100. package/dist/subagents/external/run.js +11 -11
  101. package/dist/subagents/external/settlement.d.ts +2 -0
  102. package/dist/subagents/external/settlement.js +8 -2
  103. package/dist/subagents/format.d.ts +1 -1
  104. package/dist/subagents/format.js +1 -1
  105. package/dist/subagents/internal/outcome.d.ts +1 -2
  106. package/dist/subagents/internal/provider-retry.d.ts +1 -2
  107. package/dist/subagents/internal/provider-retry.js +1 -1
  108. package/dist/subagents/internal/run.d.ts +1 -2
  109. package/dist/subagents/internal/state.d.ts +1 -2
  110. package/dist/subagents/internal/worker.d.ts +1 -2
  111. package/dist/subagents/internal/worker.js +3 -1
  112. package/dist/subagents/resolve.d.ts +56 -0
  113. package/dist/subagents/resolve.js +202 -0
  114. package/dist/subagents/result.d.ts +1 -2
  115. package/dist/subagents/result.js +7 -3
  116. package/dist/subagents/run-record.d.ts +33 -2
  117. package/dist/subagents/run-record.js +2 -0
  118. package/dist/subagents/runs.d.ts +2 -24
  119. package/dist/subagents/runs.js +6 -0
  120. package/dist/subagents/task-envelope.d.ts +1 -2
  121. package/dist/subagents/task-envelope.js +8 -4
  122. package/dist/subagents/types.d.ts +93 -4
  123. package/dist/subagents/types.js +16 -1
  124. package/dist/subagents/workspace-lease.d.ts +11 -21
  125. package/dist/subagents/workspace-lease.js +48 -21
  126. package/dist/subagents/worktree.d.ts +10 -0
  127. package/dist/subagents/worktree.js +77 -0
  128. package/dist/tasks/archive.js +4 -0
  129. package/dist/tasks/commands.d.ts +3 -0
  130. package/dist/tasks/commands.js +16 -2
  131. package/dist/tasks/control.d.ts +2 -0
  132. package/dist/tasks/delivery.d.ts +2 -0
  133. package/dist/tasks/delivery.js +141 -21
  134. package/dist/tasks/loop-log.d.ts +2 -0
  135. package/dist/tasks/loop-log.js +9 -0
  136. package/dist/tools/bash.js +2 -0
  137. package/dist/tools/contract/presentation.js +3 -4
  138. package/dist/tools/event-manage.d.ts +2 -0
  139. package/dist/tools/event-manage.js +20 -2
  140. package/dist/tools/index.d.ts +2 -1
  141. package/dist/tools/index.js +2 -0
  142. package/dist/tools/registry.js +3 -1
  143. package/dist/tools/send-media.js +9 -5
  144. package/dist/tools/session-search.js +1 -1
  145. package/dist/tools/subagent-manage.d.ts +1 -1
  146. package/dist/tools/subagent-manage.js +15 -149
  147. package/dist/tools/subagent.d.ts +2 -0
  148. package/dist/tools/subagent.js +6 -1
  149. package/dist/tools/task-manage/factory.js +2 -2
  150. package/dist/tools/task-manage/lifecycle.d.ts +3 -3
  151. package/dist/tools/task-manage/lifecycle.js +49 -9
  152. package/dist/tools/task-manage/schema.d.ts +4 -1
  153. package/dist/tools/task-manage/schema.js +4 -1
  154. package/dist/tools/task-manage/types.d.ts +4 -1
  155. package/dist/tui/cli.d.ts +1 -6
  156. package/dist/tui/cli.js +29 -3
  157. package/dist/tui/client.d.ts +2 -0
  158. package/dist/tui/client.js +13 -4
  159. package/dist/usage/ledger.d.ts +1 -1
  160. package/dist/usage/render.js +1 -1
  161. package/examples/sub-agents/README.md +39 -73
  162. package/examples/sub-agents/agents/agy-main.md +23 -0
  163. package/examples/sub-agents/agents/claude-high.md +9 -9
  164. package/examples/sub-agents/agents/claude-main.md +9 -9
  165. package/examples/sub-agents/agents/codex-flash.md +9 -9
  166. package/examples/sub-agents/agents/codex-high.md +9 -9
  167. package/examples/sub-agents/agents/codex-main.md +9 -9
  168. package/examples/sub-agents/agents/codex-review.md +9 -9
  169. package/examples/sub-agents/agents/cursor-high.md +9 -9
  170. package/examples/sub-agents/agents/cursor-main.md +9 -9
  171. package/examples/sub-agents/agents/glm-flash.md +9 -9
  172. package/examples/sub-agents/agents/glm-high.md +9 -9
  173. package/package.json +8 -8
  174. package/examples/sub-agents/agents/scout.md +0 -30
  175. package/examples/sub-agents/roles/builder-hard.md +0 -34
  176. package/examples/sub-agents/roles/builder.md +0 -34
  177. package/examples/sub-agents/roles/explorer.md +0 -39
  178. package/examples/sub-agents/roles/git-committer.md +0 -43
  179. package/examples/sub-agents/roles/planner.md +0 -33
  180. package/examples/sub-agents/roles/reviewer.md +0 -33
  181. package/examples/sub-agents/roles/verifier.md +0 -35
  182. package/examples/sub-agents/roles/worker.md +0 -34
@@ -292,13 +292,23 @@ export async function runReflect(options) {
292
292
  // entire automatic deletion phase unsafe; delaying unrelated cleanup is intentional.
293
293
  const writes = storeOps.filter((op) => op.op !== "delete");
294
294
  const deletes = storeOps.filter((op) => op.op === "delete");
295
- const updatedTargets = new Set(writes.flatMap((op) => (op.op === "update" ? [op.name] : [])));
296
295
  const applied = await applyMemoryOps(options.deskDir, writes, { today });
296
+ // A reused add can be the original itself. Protect actual identities, not requested slugs.
297
+ // Conflicting later writes also cannot serve as evidence for the earlier replacement.
298
+ const live = new Map((await listMemoryEntries(options.deskDir)).map((entry) => [entry.name, entry]));
299
+ const retainedNames = new Set(applied.retained.map((entry) => entry.name));
300
+ const lostReplacement = applied.retained.some((entry) => {
301
+ const current = live.get(entry.name);
302
+ return (!current ||
303
+ current.description !== entry.description ||
304
+ current.type !== entry.type ||
305
+ current.body !== entry.body);
306
+ });
297
307
  const unsafe = rejected.some((op) => op.op === "add" || op.op === "update") ||
298
308
  applied.skippedSecret > 0 ||
299
309
  applied.skippedTombstone > 0 ||
300
310
  applied.missingTarget > 0 ||
301
- deletes.some((op) => updatedTargets.has(op.name));
311
+ lostReplacement;
302
312
  if (unsafe) {
303
313
  rejected.push(...deletes.map((op) => ({
304
314
  op: "delete",
@@ -307,7 +317,17 @@ export async function runReflect(options) {
307
317
  })));
308
318
  }
309
319
  else {
310
- const removed = await applyMemoryOps(options.deskDir, deletes, { today });
320
+ const safeDeletes = deletes.filter((op) => {
321
+ if (!retainedNames.has(op.name))
322
+ return true;
323
+ rejected.push({
324
+ op: "delete",
325
+ name: op.name,
326
+ reason: "deletion deferred: live replacement identity must be retained",
327
+ });
328
+ return false;
329
+ });
330
+ const removed = await applyMemoryOps(options.deskDir, safeDeletes, { today });
311
331
  applied.deleted.push(...removed.deleted);
312
332
  }
313
333
  // Keep the accepted destructive decisions inspectable, not just a list of names.
@@ -1,4 +1,4 @@
1
- export type SessionSearchSource = "context" | "session" | "log";
1
+ export type SessionSearchSource = "context" | "session" | "log" | "task";
2
2
  export type SessionSearchRole = "user" | "assistant" | "tool" | "system" | "unknown";
3
3
  export interface SessionSearchDocument {
4
4
  id: string;
@@ -247,6 +247,71 @@ async function listSessionJsonlFiles(conversationDirs, maxFiles) {
247
247
  .slice(0, Math.max(0, maxFiles))
248
248
  .map(({ conversation, path }) => ({ conversation, path }));
249
249
  }
250
+ async function readArchivedTaskDocuments(deskDir, maxFiles, maxChars) {
251
+ const archiveDir = join(deskDir, "tasks", "archive");
252
+ let names;
253
+ try {
254
+ names = (await readdir(archiveDir)).filter((name) => name.endsWith(".md"));
255
+ }
256
+ catch (error) {
257
+ if (isNodeError(error) && error.code === "ENOENT")
258
+ return [];
259
+ throw error;
260
+ }
261
+ const stated = await Promise.all(names.map(async (name) => {
262
+ const path = join(archiveDir, name);
263
+ try {
264
+ const stats = await stat(path);
265
+ return stats.isFile() ? { name, path, mtimeMs: stats.mtimeMs } : null;
266
+ }
267
+ catch {
268
+ return null;
269
+ }
270
+ }));
271
+ const files = stated
272
+ .filter((entry) => entry !== null)
273
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
274
+ .slice(0, Math.min(200, Math.max(20, maxFiles * 10)));
275
+ const docs = [];
276
+ for (const file of files) {
277
+ const id = file.name.slice(0, -".md".length);
278
+ const markdown = await readOptionalTextFile(file.path);
279
+ if (!markdown.trim())
280
+ continue;
281
+ const logContent = await readOptionalTextFile(join(archiveDir, `${id}.jsonl`));
282
+ const logNotes = [];
283
+ let closedAt;
284
+ for (const line of logContent.split(/\r?\n/)) {
285
+ const parsed = parseJsonLine(line);
286
+ if (!isRecord(parsed))
287
+ continue;
288
+ if (parsed.kind === "report" && typeof parsed.text === "string" && parsed.text.trim()) {
289
+ logNotes.push(`[汇报] ${parsed.text.trim()}`);
290
+ }
291
+ else if (parsed.kind === "closed") {
292
+ closedAt = getStringField(parsed, "ts") ?? closedAt;
293
+ const outcome = getStringField(parsed, "outcome") ?? "closed";
294
+ const note = getStringField(parsed, "note");
295
+ logNotes.push(`[结项 ${outcome}]${note ? ` ${note}` : ""}`);
296
+ }
297
+ }
298
+ const frontmatterClosedAt = /^closedAt:\s*["']?([^"'\r\n]+)["']?\s*$/m.exec(markdown)?.[1]?.trim();
299
+ const timestamp = closedAt ?? frontmatterClosedAt ?? new Date(file.mtimeMs).toISOString();
300
+ const combined = logNotes.length > 0 ? `${markdown.trim()}\n\n${logNotes.join("\n")}` : markdown.trim();
301
+ const document = createDocument({
302
+ id: `tasks/archive/${file.name}`,
303
+ source: "task",
304
+ path: file.path,
305
+ timestamp,
306
+ role: "assistant",
307
+ text: `[归档任务 ${id}]\n${combined}`,
308
+ maxChars,
309
+ });
310
+ if (document)
311
+ docs.push(document);
312
+ }
313
+ return docs.reverse();
314
+ }
250
315
  export async function buildSessionCorpus(options) {
251
316
  const maxFiles = Math.max(1, Math.floor(options.maxFiles));
252
317
  const maxChars = options.maxCharsPerDocument ?? DEFAULT_MAX_CHARS_PER_DOCUMENT;
@@ -277,7 +342,11 @@ export async function buildSessionCorpus(options) {
277
342
  docs = docs.slice(-maxDocuments);
278
343
  byConversation.set(item.conversation, docs);
279
344
  }
280
- return shareBudget([...byConversation.values()].map(deduplicate), maxDocuments);
345
+ const archivedTasks = await readArchivedTaskDocuments(options.deskDir, maxFiles, maxChars);
346
+ const groups = [...byConversation.values()];
347
+ if (archivedTasks.length > 0)
348
+ groups.push(archivedTasks);
349
+ return shareBudget(groups.map(deduplicate), maxDocuments);
281
350
  }
282
351
  function deduplicate(docs) {
283
352
  const deduplicated = [];
@@ -44,6 +44,12 @@ function getDocumentTokens(document) {
44
44
  }
45
45
  function scoreDocument(document, lowerQuery, queryTokens) {
46
46
  const lowerText = document.text.toLowerCase();
47
+ const exactHit = Boolean(lowerQuery) && lowerText.includes(lowerQuery);
48
+ // Every token emitted by `tokenizeRecallText` is a contiguous substring of `lowerText`, so a
49
+ // document that contains neither `lowerQuery` nor any query token cannot match after tokenizing.
50
+ if (!exactHit && !queryTokens.some((token) => lowerText.includes(token))) {
51
+ return null;
52
+ }
47
53
  const documentTokens = getDocumentTokens(document);
48
54
  const matches = [];
49
55
  let matchedTokens = 0;
@@ -57,7 +63,6 @@ function scoreDocument(document, lowerQuery, queryTokens) {
57
63
  // dominant `matchedTokens * 1.4` term. Normalizing by query length alone would make detailed
58
64
  // queries score worse the more context they give, so it must stay a tiebreaker.
59
65
  const coverage = queryTokens.length > 0 ? matchedTokens / queryTokens.length : 0;
60
- const exactHit = Boolean(lowerQuery) && lowerText.includes(lowerQuery);
61
66
  const score = matchedTokens * 1.4 + coverage * 2 + (exactHit ? 1 : 0) + computeRecencyBoost(document.timestamp);
62
67
  return {
63
68
  document,
@@ -172,10 +177,10 @@ export async function searchDeskSessions(request) {
172
177
  const maxChunks = clampInteger(request.maxChunks, 1, 500);
173
178
  const query = request.query.trim();
174
179
  const roleFilter = normalizeRoleFilter(request.roleFilter);
175
- const documents = (await getCachedCorpus(request.deskDir, request.maxFiles, request.maxCharsPerChunk))
176
- .filter((document) => roleFilter.size === 0 || roleFilter.has(document.role))
177
- .sort(sortRecentDocuments)
178
- .slice(0, maxChunks);
180
+ const corpus = (await getCachedCorpus(request.deskDir, request.maxFiles, request.maxCharsPerChunk)).filter((document) => roleFilter.size === 0 || roleFilter.has(document.role));
181
+ // Score the full desk corpus when searching by query: slicing to `maxChunks` by recency before
182
+ // scoring made every message older than the newest ~80 turns permanently unreachable.
183
+ const documents = query ? corpus : [...corpus].sort(sortRecentDocuments).slice(0, maxChunks);
179
184
  // Both derived once, not per document: `tokenizeRecallText` is milliseconds on real input and
180
185
  // this loop runs over the whole corpus.
181
186
  const queryTokens = query ? tokenizeRecallText(query) : [];
@@ -186,13 +191,10 @@ export async function searchDeskSessions(request) {
186
191
  // Require actual match evidence: recency alone used to lift a completely unrelated
187
192
  // recent message above 0 and return it with an empty `matches` array — wasted tokens
188
193
  // and a misleading "hit". Recency now only ranks among documents that did match.
189
- .filter((entry) => entry.matches.length > 0 || entry.exactHit)
190
- .sort((a, b) => b.score - a.score)
191
- .slice(0, limit)
192
- : documents
193
- .sort(sortRecentDocuments)
194
+ .filter((entry) => entry !== null && (entry.matches.length > 0 || entry.exactHit))
195
+ .sort((a, b) => b.score - a.score || sortRecentDocuments(a.document, b.document))
194
196
  .slice(0, limit)
195
- .map((document) => ({
197
+ : documents.slice(0, limit).map((document) => ({
196
198
  document,
197
199
  score: computeRecencyBoost(document.timestamp),
198
200
  matches: [],
@@ -96,6 +96,8 @@ export type MemoryStoreOp = {
96
96
  };
97
97
  export interface ApplyMemoryOpsResult {
98
98
  added: string[];
99
+ /** Successful writes and exact-add reuses, with the actual on-disk identity. */
100
+ retained: MemoryEntry[];
99
101
  updated: string[];
100
102
  deleted: string[];
101
103
  touched: string[];
@@ -314,6 +314,7 @@ export async function applyMemoryOps(deskDir, ops, options = {}) {
314
314
  const today = options.today ?? localDayKey();
315
315
  const result = {
316
316
  added: [],
317
+ retained: [],
317
318
  updated: [],
318
319
  deleted: [],
319
320
  touched: [],
@@ -360,12 +361,15 @@ export async function applyMemoryOps(deskDir, ops, options = {}) {
360
361
  // Recording the tombstone before the delete means the worst case after a failure here is
361
362
  // the reverse — file still present, already tombstoned — which is recoverable: the file
362
363
  // is still there to retry deleting, and it is already protected from re-learning either way.
363
- await appendMemoryTombstoneRecord(deskDir, {
364
- name: op.name,
365
- contentHash: hashMemoryContent(entry.description),
366
- deletedAt: today,
367
- reason: op.reason?.trim() || "deleted",
368
- });
364
+ // Removing a redundant file must not forbid a fact that is still live elsewhere.
365
+ if (![...byName.values()].some((other) => other.name !== op.name &&
366
+ hashMemoryContent(other.description) === hashMemoryContent(entry.description)))
367
+ await appendMemoryTombstoneRecord(deskDir, {
368
+ name: op.name,
369
+ contentHash: hashMemoryContent(entry.description),
370
+ deletedAt: today,
371
+ reason: op.reason?.trim() || "deleted",
372
+ });
369
373
  await rm(getMemoryEntryPath(deskDir, op.name), { force: true });
370
374
  byName.delete(op.name);
371
375
  liveNames.delete(op.name);
@@ -403,6 +407,7 @@ export async function applyMemoryOps(deskDir, ops, options = {}) {
403
407
  await revokeMemoryTombstone(deskDir, description, today);
404
408
  byName.set(op.name, next);
405
409
  result.updated.push(op.name);
410
+ result.retained.push(next);
406
411
  continue;
407
412
  }
408
413
  // add
@@ -425,11 +430,15 @@ export async function applyMemoryOps(deskDir, ops, options = {}) {
425
430
  }
426
431
  // Background retries may revisit an already-applied add. Preserve the existing entry,
427
432
  // including its source/expiry; a replay is not independent confirmation or a touch.
428
- if (op.source === "agent" &&
429
- [...byName.values()].some((entry) => hashMemoryContent(entry.description) === hashMemoryContent(description) &&
433
+ const duplicate = op.source === "agent"
434
+ ? [...byName.values()].find((entry) => hashMemoryContent(entry.description) === hashMemoryContent(description) &&
430
435
  entry.type === (op.type ?? "project") &&
431
- entry.body.trim() === (op.details?.trim() ?? "")))
436
+ entry.body.trim() === (op.details?.trim() ?? ""))
437
+ : undefined;
438
+ if (duplicate) {
439
+ result.retained.push(duplicate);
432
440
  continue;
441
+ }
433
442
  const requested = op.name && isValidMemoryName(op.name) ? op.name : slugifyMemoryName(op.name || description);
434
443
  const name = dedupeMemoryName(requested, liveNames);
435
444
  if (name !== requested) {
@@ -453,6 +462,7 @@ export async function applyMemoryOps(deskDir, ops, options = {}) {
453
462
  byName.set(name, entry);
454
463
  liveNames.add(name);
455
464
  result.added.push(name);
465
+ result.retained.push(entry);
456
466
  }
457
467
  await rebuildMemoryIndex(deskDir);
458
468
  return result;
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: agent-delegation
3
3
  description: 判断是否值得委派内部子代理(subagent)或外部 AI Agent,按能力与成本选执行器、交代上下文、并行隔离、等待与续接时。
4
+ requires-tools: subagent
4
5
  order: 60
5
6
  ---
6
7
 
@@ -10,11 +11,11 @@ order: 60
10
11
 
11
12
  ## 选执行器与调用方式
12
13
 
13
- 按目录的 description、runtime、工具/模型、成本、mutates 和可用状态选条目。正文可能有部署者的岗位约束;名字、light/heavy 或档位不证明能力。已知的重复工作用低成本能力,常规实施用主力能力,确需新判断或专用输入才升级。条目 unavailable 时先判断自己或其他条目能否达标,缺必需能力才说明需要部署者补什么。
14
+ 按可用状态、输入与执行边界筛选,再按不确定性、错误代价和成本选条目。做法明确、易检查且易恢复的工作用低成本档,常规实施用主力档,关键取舍或难验证时考虑高档。名字与档位不证明能力;缺输入、权限或环境不靠升级模型解决。无合适条目先判断能否自己做,确缺能力才请部署者补齐。
14
15
 
15
16
  优先 `subagent {agent, task}`,可选 workingDirectory、purpose、item;工具、模型和预算由角色文件决定。没有合适条目才用 `subagent_inline`,自行提供完整 systemPrompt 和需要的工具、effort 等字段。外部角色只能由部署者配置,不能内联命令或改写 `sub-agents/` 来创建;也不要换 bash 绕过。
16
17
 
17
- 独立检查用 `purpose:"verify"`,普通工作用 `purpose:"work"`。verify 不要求 task;执行者最后写 `VERDICT: PASS|FAIL`,结论供你判断,不是关闭门禁。给检查者同一份要求、待检版本和入口,明确“只检查,不修实现,不把实现者总结当预期行为”;能选时用不同家的模型。`exec` 无协议终态,不能 verify。检查与返工的裁决方法见 `task-lead.md` 的“检查与返工”。
18
+ 独立检查用 `purpose:"verify"`,普通工作用 `purpose:"work"`。verify 不要求 task;最后写 `VERDICT: PASS|FAIL`,只是判断材料。给检查者原始要求或权威验收文件、待检版本与入口,明确“只检查,不修实现,不把实现者总结当预期行为”。优先独立取证,关键风险换检查方法,再考虑不同模型。`exec` 不能 verify;裁决见 `task-lead.md` 的“检查与返工”。
18
19
 
19
20
  ## 任务指令:执行者看不到本会话
20
21
 
@@ -27,7 +28,7 @@ order: 60
27
28
  | 独立检查 | 同一要求、待检产物、检查入口;不依赖成功声明 |
28
29
  | 返工或换人 | 已裁决失败、复现、已通过项、失败尝试、修复边界与重验方法 |
29
30
 
30
- 只带会改变方案、范围、验收或避免重复调查的信息。仓库细节给可读指针,适用的记忆正文直接写进 task;不要用“按上文”。同一用户要求要同时交给执行者与检查者,外部 sandbox 可能使主代理能读的路径对执行者不可读。
31
+ 只带影响方案、范围、验收或避免重复调查的信息。仓库细节给可读指针,适用记忆正文写进 task;不用“按上文”。同一要求同时给执行者与检查者。图片须给可读路径并确认 CLI/模型支持,不会自动继承聊天附件;外部 sandbox 也可能限制路径。
31
32
 
32
33
  ## 工作目录与写入边界
33
34
 
@@ -62,4 +63,4 @@ order: 60
62
63
 
63
64
  daemon 重启后内置 run 判 lost,外部通常继续;启动信息尚未落盘的外部 run 也可能 lost。lost 是结局未知,先查产物再重派;带 `≈` 的重连耗时是估算。
64
65
 
65
- `subagent_run op=follow_up` 只支持已结束且有 session id 的 claude-code/codex-cli/cursor-cli run,产生新 runId,归发起续接的频道。目标不变、反馈局部、旧上下文可靠时只发新增指令;换方向、反复陷入错误假设或需要独立判断时重开。内置/exec 不支持续接,角色 command/model/shell 改动后也须重开;带上仍有效的已有产出。
66
+ `subagent_run op=follow_up` 只支持已结束且有 session id 的 claude-code/codex-cli/cursor-cli/antigravity-cli run,产生新 runId,归发起续接的频道。目标不变、反馈局部、旧上下文可靠时只发新增指令;换方向、反复陷入错误假设或需要独立判断时重开。内置/exec 不支持续接,角色 command/model/shell 改动后也须重开;带上仍有效的已有产出。
@@ -42,7 +42,7 @@ order: 20
42
42
 
43
43
  先看当前上下文和首轮索引;有相关 `(+)` 条目才读正文。索引不会每轮刷新,中途怀疑记过就 `memory_search`。它查当前工位的 memory、workspace MEMORY 和最近的 journal;日志最多取最近 30 个日文件、每份末尾 64 KiB,超出时工具会给继续检索的路径。找更早记录用该路径定向 `grep` 或按日期 `read`,原始对话用 `session_search`。无命中不等于不存在。
44
44
 
45
- 使用偏好前确认适用范围,再转成执行与验收的同一要求(如“控制复杂度”落为“新增依赖或持久状态必须说明必要性”)。委派时把本轮适用要求同时给执行者和验收者;需要在所有工位都成立的共同背景属于 workspace `MEMORY.md`:由用户维护,只在用户明确要求时修改,不把工位记忆自动搬过去。
45
+ 使用前核对主人、范围和时效;永久保留不代表事实永久有效,易变事实须核实,记忆不扩大授权。适用偏好落实为执行与验收的同一要求(如“控制复杂度”→“新增依赖须说明必要性”)。跨工位背景属于用户维护的 workspace `MEMORY.md`,仅在用户明确要求时修改,不把工位记忆自动搬过去。
46
46
 
47
47
  ## 自动学习与 skill 晋升
48
48
 
@@ -7,7 +7,7 @@ order: 70
7
7
 
8
8
  # 负责人:立项、推进与交付
9
9
 
10
- task 是你跨回合负责的一个项目,可自行实施或按收益委派。几次工具调用能完成的请求、一次临时委派无需立项;需要保留目标、预算和进展,跨回合完成多项工作时才建 task。运行时负责调度、状态与记账,你负责目标、判断、检查和交付。
10
+ task 是需跨回合持续维护目标、验收、预算和多步进展的项目,可自行实施或按收益委派。几次工具调用能完成的请求、单次作业或临时委派不因异步而立项。运行时负责调度、状态与记账,你负责目标、判断、检查和交付。
11
11
 
12
12
  任务在当前工位自己的后台会话里执行,与聊天并行。同工位任一频道可管理;报告、提问与回执只发到任务的投递频道。该频道换绑离开工位时任务冻结,切回继续。
13
13
 
@@ -38,7 +38,7 @@ task 是你跨回合负责的一个项目,可自行实施或按收益委派。
38
38
 
39
39
  ## 每一步怎样推进
40
40
 
41
- 一步是任务会话里的一次回合,回合结束即结束本步。**最后一段回复写下做了什么、证据和下一步**,运行时存入任务记录;这段回复不发给用户。
41
+ 一步是任务会话的一次回合。**末段记本步新增的结论、证据、改动与检查、未决问题、下一步或实际等待来源**;不复抄目标和历史。运行时存入任务记录,不发给用户。
42
42
 
43
43
  | brief 中的块 | 怎样使用 |
44
44
  |---|---|
@@ -67,9 +67,9 @@ task 是你跨回合负责的一个项目,可自行实施或按收益委派。
67
67
 
68
68
  ## 检查与返工
69
69
 
70
- 看板 completed 和执行者总结都不能代替证据。对照 DoD 检查真实文件、diff、测试与外部目标状态。需要独立判断时派 `purpose:"verify"`,给同一要求、待检版本和检查入口,明确只检查不修实现,最后写 `VERDICT: PASS|FAIL`;尽量与实现者用不同家的模型。带 item 只检查该项和它引用的 DoD,终验不带 item。只读与写锁边界见 `agent-delegation.md`。
70
+ 看板 completed 和执行者总结不能代替证据。对照 DoD 核实产物、diff、检查输出与外部状态,说明证据对应的版本、覆盖项和未验证项。独立检查按 `agent-delegation.md` 用 `purpose:"verify"`;带 item 只查该项及引用的 DoD,终验不带 item。
71
71
 
72
- VERDICT 是判断材料,不是门禁:PASS 仍要核对产物,FAIL 也要审查理由。违反 DoD/明确约束且有证据才返工;疑点先窄查,范围外增强和风格建议不扩成本轮目标。
72
+ PASS 需有本次范围内的充分证据;FAIL 区分已证实缺陷与验证受阻。前者违反 DoD/明确约束才返工,后者补验证条件;疑点先窄查,风格建议不扩范围。完成必需检查后,相关产物和环境未变就复用已核实结果;有新改动、失败或具体未决风险才补查,不因换检查者重跑。
73
73
 
74
74
  返工指令写 **现象 → 证据 → 违反标准 → 修复边界与已通过项 → 重验办法**。同一问题连续两轮失败且无新证据,缩小复现、换调查方法或换执行者。达到标准且无未解决必修项就收尾,不因预算有余额继续润色。
75
75
 
@@ -1,3 +1,8 @@
1
+ /**
2
+ * The daemon's composition root: loads config and builds the transports, the ingress, durable
3
+ * dispatch, jobs, delegation runs, the events, memory and task services, then wires the ordered
4
+ * shutdown (`shutdown.ts`).
5
+ */
1
6
  import { type BootstrapIO, type BootstrapPaths } from "../app/home.js";
2
7
  import { ChannelStore } from "../channel/store.js";
3
8
  import type { Transport } from "../channel/transport.js";
@@ -63,6 +68,7 @@ interface RuntimeContextOptions {
63
68
  createEventsWatcher?: (target: {
64
69
  desk: string;
65
70
  deskDir: string;
71
+ cwd: string;
66
72
  }) => {
67
73
  start(): void;
68
74
  stop(): void;
@@ -116,7 +116,7 @@ async function buildRuntimeContext(options, daemonLock) {
116
116
  const sessionResetChains = new Map();
117
117
  const activeTasks = new Set();
118
118
  /** Channels with a `/stop` watchdog in flight, so a burst of `/stop` starts only one. */
119
- const stopWatchdogs = new Set();
119
+ const stopWatchdogs = new Map();
120
120
  let durableDispatch;
121
121
  let shuttingDown = false;
122
122
  const executor = options.executor ?? createExecutor();
@@ -162,15 +162,17 @@ async function buildRuntimeContext(options, daemonLock) {
162
162
  });
163
163
  }
164
164
  },
165
- createWatcher: (target) => options.createEventsWatcher
166
- ? options.createEventsWatcher(target)
167
- : createEventsWatcher({
165
+ createWatcher: (target) => {
166
+ if (options.createEventsWatcher)
167
+ return options.createEventsWatcher(target);
168
+ const security = loadSecurityConfigWithDiagnostics(appHomeDir).config;
169
+ return createEventsWatcher({
168
170
  ...target,
169
171
  isBound: (channelId) => deskRuntime.isBoundTo(channelId, target.desk),
170
172
  isReachable: (channelId) => transports.isReachable(channelId),
171
173
  sink: ingress,
172
174
  executor,
173
- commandGuardConfig: loadSecurityConfigWithDiagnostics(appHomeDir).config.commandGuard,
175
+ commandGuardConfig: security.enabled ? security.commandGuard : undefined,
174
176
  historyPath: options.paths.eventHistoryPath,
175
177
  dispatch,
176
178
  spawnTask: createTaskSpawner({
@@ -178,7 +180,8 @@ async function buildRuntimeContext(options, daemonLock) {
178
180
  wake: () => taskLane.notify(),
179
181
  notify: (desk, channelId, text) => deskRuntime.sendFromDesk(desk, channelId, text),
180
182
  }),
181
- }),
183
+ });
184
+ },
182
185
  send: (channelId, text) => pushTo(channelId, { text }),
183
186
  isChannelBusy: (channelId) => channelRunners.get(channelId)?.isBusy() ?? false,
184
187
  releaseRunner: (channelId) => releaseCachedRunner(channelRunners, channelId),
@@ -307,8 +310,9 @@ async function buildRuntimeContext(options, daemonLock) {
307
310
  deskPort: (channelId) => ({
308
311
  list: async () => buildDeskList(await listDesks(workspaceDir), deskRuntime.bindingTable(), deskRuntime.boundDesk(channelId), labelOf),
309
312
  channelIndexPath: join(workspaceDir, CHANNELS_INDEX_FILENAME),
310
- create: (name) => deskRuntime.create(name),
313
+ create: (name, cwd) => deskRuntime.create(name, cwd),
311
314
  bind: (name) => deskRuntime.bind(channelId, name),
315
+ cwd: (input) => deskRuntime.cwd(channelId, input),
312
316
  }),
313
317
  describeChannel,
314
318
  cliVersion,
@@ -1,5 +1,5 @@
1
1
  import type { BindOutcome } from "../desk/commands.js";
2
- import type { BindingsFile, ConversationKind, CreateDeskOutcome, DeskConversation } from "../desk/types.js";
2
+ import type { BindingsFile, ConversationKind, CreateDeskOutcome, DeskConversation, DeskCwdOutcome } from "../desk/types.js";
3
3
  export type ChannelResolution = {
4
4
  kind: "bound";
5
5
  conversation: DeskConversation;
@@ -41,6 +41,7 @@ export interface DeskRuntimeOptions {
41
41
  createWatcher: (target: {
42
42
  desk: string;
43
43
  deskDir: string;
44
+ cwd: string;
44
45
  }) => DeskWatcher;
45
46
  /** The transport's plain send, for background notices that pass the binding guard. */
46
47
  send: (channelId: string, text: string) => Promise<boolean>;
@@ -102,7 +103,12 @@ export declare class DeskRuntime {
102
103
  private startWatcher;
103
104
  private stopWatcher;
104
105
  /** `/desk new`: an empty desk, bound to nothing and therefore dormant (D5). */
105
- create(name: string): Promise<CreateDeskOutcome>;
106
+ create(name: string, cwd?: string): Promise<CreateDeskOutcome>;
107
+ /** `/desk cwd`: view or update the working directory of `channelId`'s bound desk. */
108
+ cwd(channelId: string, input: {
109
+ cwd?: string;
110
+ reset?: boolean;
111
+ }): Promise<DeskCwdOutcome>;
106
112
  /** `/desk bind` from `channelId`, in D5's order. Throws only when the bindings write itself fails. */
107
113
  bind(channelId: string, name: string): Promise<BindOutcome>;
108
114
  /**
@@ -12,7 +12,7 @@ import { readdir, readFile } from "node:fs/promises";
12
12
  import { join } from "node:path";
13
13
  import { loadBindings, writeBindings } from "../desk/bindings.js";
14
14
  import { getDeskDir, isDeskName, normalizeDeskName } from "../desk/paths.js";
15
- import { allocateConversation, createDeskRecord, findConversation, readDeskRecord } from "../desk/registry.js";
15
+ import { allocateConversation, createDeskRecord, findConversation, readDeskRecord, setDeskCwd, } from "../desk/registry.js";
16
16
  import { StartupRefusal } from "../desk/startup-error.js";
17
17
  import { parseScheduledEventContent } from "../events/parse.js";
18
18
  import * as log from "../log.js";
@@ -190,7 +190,9 @@ export class DeskRuntime {
190
190
  startWatcher(desk) {
191
191
  if (this.watchers.has(desk))
192
192
  return;
193
- const watcher = this.options.createWatcher({ desk, deskDir: getDeskDir(this.options.workspaceDir, desk) });
193
+ const deskDir = getDeskDir(this.options.workspaceDir, desk);
194
+ const cwd = this.records.get(desk)?.record?.cwd ?? deskDir;
195
+ const watcher = this.options.createWatcher({ desk, deskDir, cwd });
194
196
  this.watchers.set(desk, watcher);
195
197
  watcher.start();
196
198
  }
@@ -203,8 +205,37 @@ export class DeskRuntime {
203
205
  await watcher.flush?.().catch(() => undefined);
204
206
  }
205
207
  /** `/desk new`: an empty desk, bound to nothing and therefore dormant (D5). */
206
- create(name) {
207
- return Promise.resolve(createDeskRecord(this.options.workspaceDir, normalizeDeskName(name), new Date()));
208
+ create(name, cwd) {
209
+ return Promise.resolve(createDeskRecord(this.options.workspaceDir, normalizeDeskName(name), new Date(), cwd));
210
+ }
211
+ /** `/desk cwd`: view or update the working directory of `channelId`'s bound desk. */
212
+ async cwd(channelId, input) {
213
+ const resolution = this.resolve(channelId);
214
+ if (resolution.kind !== "bound") {
215
+ return { kind: "unavailable", desk: resolvedDesk(resolution) ?? "" };
216
+ }
217
+ const { desk, deskDir } = resolution.conversation;
218
+ if (!input.cwd && !input.reset) {
219
+ const summary = await this.refreshRecord(desk);
220
+ if (!summary.record)
221
+ return { kind: "unavailable", desk };
222
+ const effective = summary.record.cwd ?? deskDir;
223
+ return { kind: "ok", desk, cwd: effective, isDefault: summary.record.cwd === undefined };
224
+ }
225
+ const outcome = await setDeskCwd(this.options.workspaceDir, desk, input.reset ? null : (input.cwd ?? ""));
226
+ if (outcome.kind !== "ok")
227
+ return outcome;
228
+ await this.refreshRecord(desk);
229
+ if (this.active.has(desk) && this.servicesStarted) {
230
+ await this.stopWatcher(desk);
231
+ this.startWatcher(desk);
232
+ }
233
+ for (const boundChannel of this.boundChannelsOf(desk)) {
234
+ if (!this.options.isChannelBusy(boundChannel)) {
235
+ await this.options.releaseRunner(boundChannel).catch(() => undefined);
236
+ }
237
+ }
238
+ return outcome;
208
239
  }
209
240
  /** `/desk bind` from `channelId`, in D5's order. Throws only when the bindings write itself fails. */
210
241
  bind(channelId, name) {
@@ -11,6 +11,8 @@ export interface DurableDispatchRecord {
11
11
  /** Set by `markRetryable` to back off a repeatedly-failing structured wake instead of
12
12
  * redelivering on the very next drain tick (spec 031's redelivery has no such gate). */
13
13
  nextAttemptAt?: string;
14
+ /** Set when the record hits `MAX_DELIVERIES`; starts the dead-letter retention window. */
15
+ exhaustedAt?: string;
14
16
  }
15
17
  export interface DurableDispatchOptions {
16
18
  stateDir: string;
@@ -23,10 +25,12 @@ export interface DurableDispatchOptions {
23
25
  isReachable?: (channelId: string) => boolean;
24
26
  leaseMs?: number;
25
27
  intervalMs?: number;
28
+ /** Retention window for `exhausted` dead-letter records before `drainOnce` unlinks them (default 7 days). */
29
+ exhaustedRetentionMs?: number;
26
30
  /** Called once, at most, when a dispatch id hits `MAX_DELIVERIES` without ever completing —
27
31
  * e.g. a structured wake whose claim/finish step fails deterministically (disk full,
28
- * permissions). The record is left on disk (not deleted) so the failure is inspectable; the
29
- * caller is expected to notify the channel. */
32
+ * permissions). The record is kept on disk for the retention window so the failure is inspectable;
33
+ * the caller is expected to notify the channel. */
30
34
  onExhausted?: (record: DurableDispatchRecord) => void | Promise<void>;
31
35
  }
32
36
  /**
@@ -46,7 +50,13 @@ export declare class DurableDispatchService {
46
50
  private readonly capacityRejected;
47
51
  private readonly capacityDrains;
48
52
  private readonly queue;
53
+ private readonly pendingWrites;
54
+ private run;
55
+ /** stop() closes background admission; after active turns settle, wait for started writes
56
+ * before another process can acquire the daemon lock. A hung write keeps that lock retained. */
57
+ flush(): Promise<void>;
49
58
  private readonly leaseMs;
59
+ private readonly exhaustedRetentionMs;
50
60
  private timer;
51
61
  /**
52
62
  * Dispatch ids whose turn this process is still running (spec 031, D2).
@@ -123,6 +133,8 @@ export declare class DurableDispatchService {
123
133
  markRetryable(id: string | undefined): Promise<void>;
124
134
  drainOnce(now?: number): Promise<void>;
125
135
  private drainRecord;
136
+ private idFromFilename;
137
+ private reportRecordFault;
126
138
  private read;
127
139
  private write;
128
140
  }