@oyasmi/pipiclaw 0.9.5-beta.2 → 0.9.5-beta.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 (272) hide show
  1. package/README.en.md +9 -11
  2. package/README.md +9 -11
  3. package/dist/agent/channel-runner.d.ts +12 -24
  4. package/dist/agent/channel-runner.js +74 -30
  5. package/dist/agent/maintenance-context.d.ts +2 -0
  6. package/dist/agent/maintenance-context.js +15 -0
  7. package/dist/agent/prompt/sections.js +8 -6
  8. package/dist/agent/prompt/types.d.ts +1 -1
  9. package/dist/agent/runner-factory.js +1 -1
  10. package/dist/agent/session/command-extension.js +11 -0
  11. package/dist/agent/session/compaction-summary.js +6 -2
  12. package/dist/agent/session/execution-trace.d.ts +14 -0
  13. package/dist/agent/session/execution-trace.js +57 -0
  14. package/dist/agent/session/session-events.d.ts +2 -7
  15. package/dist/agent/session/session-events.js +35 -12
  16. package/dist/agent/session/session-host.d.ts +12 -22
  17. package/dist/agent/session/session-host.js +46 -65
  18. package/dist/agent/turn/task-digest.d.ts +1 -2
  19. package/dist/agent/turn/task-digest.js +33 -33
  20. package/dist/agent/turn/turn-context.d.ts +1 -1
  21. package/dist/agent/turn/turn-context.js +1 -1
  22. package/dist/agent/turn/turn-finish.d.ts +2 -2
  23. package/dist/agent/turn/turn-finish.js +3 -2
  24. package/dist/agent/turn/turn-pipeline.d.ts +4 -2
  25. package/dist/agent/turn/turn-pipeline.js +33 -5
  26. package/dist/agent/types.d.ts +64 -14
  27. package/dist/agent/types.js +3 -0
  28. package/dist/app/home.js +3 -4
  29. package/dist/channel/channel-event.d.ts +4 -12
  30. package/dist/channel/ingress.d.ts +1 -9
  31. package/dist/channel/store.d.ts +1 -1
  32. package/dist/commands/catalog.js +25 -19
  33. package/dist/commands/router.d.ts +5 -2
  34. package/dist/commands/router.js +9 -4
  35. package/dist/config/settings.d.ts +5 -12
  36. package/dist/config/settings.js +0 -7
  37. package/dist/config/tools.d.ts +2 -2
  38. package/dist/config/tools.js +2 -2
  39. package/dist/dingtalk/bot.d.ts +2 -0
  40. package/dist/dingtalk/bot.js +4 -0
  41. package/dist/dingtalk/cards.d.ts +7 -0
  42. package/dist/dingtalk/cards.js +32 -2
  43. package/dist/dingtalk/delivery.d.ts +5 -1
  44. package/dist/dingtalk/delivery.js +157 -142
  45. package/dist/dingtalk/progress.d.ts +55 -6
  46. package/dist/dingtalk/progress.js +195 -16
  47. package/dist/file-store.d.ts +4 -0
  48. package/dist/file-store.js +6 -1
  49. package/dist/jobs/completion-observer.d.ts +20 -0
  50. package/dist/jobs/completion-observer.js +107 -0
  51. package/dist/jobs/completion-signal.d.ts +9 -0
  52. package/dist/jobs/completion-signal.js +32 -0
  53. package/dist/jobs/completion-wake.d.ts +1 -1
  54. package/dist/jobs/completion-wake.js +2 -13
  55. package/dist/jobs/manager.d.ts +11 -29
  56. package/dist/jobs/manager.js +103 -176
  57. package/dist/jobs/probe.d.ts +3 -0
  58. package/dist/jobs/probe.js +42 -0
  59. package/dist/jobs/record.d.ts +3 -6
  60. package/dist/jobs/runtime.d.ts +28 -0
  61. package/dist/jobs/runtime.js +69 -0
  62. package/dist/memory/boundary-work.d.ts +2 -0
  63. package/dist/memory/boundary-work.js +79 -37
  64. package/dist/memory/commands.js +4 -1
  65. package/dist/memory/index-budget.js +18 -15
  66. package/dist/memory/journal.js +2 -1
  67. package/dist/memory/lifecycle.d.ts +4 -8
  68. package/dist/memory/lifecycle.js +21 -51
  69. package/dist/memory/reflect-job.d.ts +0 -6
  70. package/dist/memory/reflect-job.js +13 -34
  71. package/dist/memory/reflect.d.ts +4 -0
  72. package/dist/memory/reflect.js +32 -5
  73. package/dist/memory/review-log.d.ts +13 -0
  74. package/dist/memory/review-log.js +49 -0
  75. package/dist/memory/search.js +7 -4
  76. package/dist/memory/source-window.d.ts +18 -1
  77. package/dist/memory/source-window.js +59 -9
  78. package/dist/memory/store.d.ts +2 -0
  79. package/dist/memory/store.js +45 -13
  80. package/dist/playbooks/agent-delegation.md +10 -4
  81. package/dist/playbooks/background-jobs.md +4 -4
  82. package/dist/playbooks/event-scheduling.md +2 -2
  83. package/dist/playbooks/memory-and-learning.md +3 -3
  84. package/dist/playbooks/outbound-media.md +2 -2
  85. package/dist/playbooks/runtime-orientation.md +10 -6
  86. package/dist/playbooks/task-lead.md +54 -33
  87. package/dist/runtime/bootstrap.d.ts +11 -24
  88. package/dist/runtime/bootstrap.js +92 -59
  89. package/dist/runtime/channel-queue.d.ts +2 -0
  90. package/dist/runtime/channel-queue.js +5 -1
  91. package/dist/runtime/durable-dispatch.d.ts +7 -0
  92. package/dist/runtime/durable-dispatch.js +66 -7
  93. package/dist/runtime/ingress-busy.d.ts +1 -2
  94. package/dist/runtime/ingress-busy.js +2 -35
  95. package/dist/runtime/ingress-commands.d.ts +1 -1
  96. package/dist/runtime/ingress-commands.js +28 -20
  97. package/dist/runtime/ingress-deps.d.ts +4 -7
  98. package/dist/runtime/ingress.js +23 -13
  99. package/dist/runtime/shutdown.d.ts +1 -1
  100. package/dist/runtime/shutdown.js +2 -2
  101. package/dist/runtime/task-close.d.ts +4 -0
  102. package/dist/runtime/task-close.js +102 -0
  103. package/dist/runtime/task-control.d.ts +34 -0
  104. package/dist/runtime/task-control.js +225 -0
  105. package/dist/runtime/task-input.d.ts +13 -0
  106. package/dist/runtime/task-input.js +129 -0
  107. package/dist/runtime/task-lane-types.d.ts +123 -0
  108. package/dist/runtime/task-lane-types.js +14 -0
  109. package/dist/runtime/task-lane.d.ts +99 -0
  110. package/dist/runtime/task-lane.js +703 -0
  111. package/dist/runtime/task-pending.d.ts +8 -0
  112. package/dist/runtime/task-pending.js +40 -0
  113. package/dist/runtime/task-spawn.d.ts +4 -4
  114. package/dist/runtime/task-spawn.js +4 -4
  115. package/dist/runtime/task-step.d.ts +32 -0
  116. package/dist/runtime/task-step.js +276 -0
  117. package/dist/runtime/turn-run.d.ts +4 -16
  118. package/dist/runtime/turn-run.js +17 -155
  119. package/dist/runtime/wake-coalescing.d.ts +1 -3
  120. package/dist/runtime/wake-coalescing.js +2 -4
  121. package/dist/shared/format.d.ts +0 -6
  122. package/dist/shared/format.js +0 -17
  123. package/dist/shared/host-process.d.ts +2 -0
  124. package/dist/shared/host-process.js +16 -1
  125. package/dist/shared/jsonl-appender.d.ts +5 -0
  126. package/dist/shared/jsonl-appender.js +25 -2
  127. package/dist/skills/catalog.d.ts +9 -0
  128. package/dist/skills/catalog.js +34 -0
  129. package/dist/skills/commands.d.ts +3 -12
  130. package/dist/skills/commands.js +36 -22
  131. package/dist/skills/loader.d.ts +2 -31
  132. package/dist/skills/loader.js +101 -68
  133. package/dist/skills/roots.d.ts +12 -0
  134. package/dist/skills/roots.js +18 -0
  135. package/dist/skills/types.d.ts +24 -0
  136. package/dist/skills/types.js +1 -0
  137. package/dist/subagents/completion-wake.js +0 -10
  138. package/dist/subagents/discovery.d.ts +1 -1
  139. package/dist/subagents/discovery.js +10 -16
  140. package/dist/subagents/dispatch.js +8 -16
  141. package/dist/subagents/external/cursor-cli.d.ts +2 -0
  142. package/dist/subagents/external/cursor-cli.js +256 -0
  143. package/dist/subagents/external/harness.d.ts +5 -5
  144. package/dist/subagents/external/reconciliation.d.ts +7 -0
  145. package/dist/subagents/external/reconciliation.js +105 -0
  146. package/dist/subagents/external/recovery.d.ts +20 -0
  147. package/dist/subagents/external/recovery.js +71 -0
  148. package/dist/subagents/external/registry.js +2 -0
  149. package/dist/subagents/external/role-warnings.d.ts +17 -0
  150. package/dist/subagents/external/role-warnings.js +42 -0
  151. package/dist/subagents/external/run.js +18 -22
  152. package/dist/subagents/format.d.ts +1 -1
  153. package/dist/subagents/format.js +1 -1
  154. package/dist/subagents/grace.d.ts +2 -2
  155. package/dist/subagents/grace.js +3 -3
  156. package/dist/subagents/internal/run.js +7 -5
  157. package/dist/subagents/internal/worker.js +31 -2
  158. package/dist/subagents/result.js +2 -3
  159. package/dist/subagents/run-record.d.ts +4 -7
  160. package/dist/subagents/run-record.js +2 -2
  161. package/dist/subagents/runs.d.ts +33 -46
  162. package/dist/subagents/runs.js +126 -245
  163. package/dist/subagents/task-settlement.d.ts +3 -0
  164. package/dist/subagents/task-settlement.js +20 -0
  165. package/dist/subagents/types.d.ts +1 -2
  166. package/dist/subagents/workspace-summary.js +5 -1
  167. package/dist/tasks/archive.d.ts +11 -0
  168. package/dist/tasks/archive.js +141 -0
  169. package/dist/tasks/board.d.ts +5 -12
  170. package/dist/tasks/board.js +4 -30
  171. package/dist/tasks/bound-work.d.ts +12 -6
  172. package/dist/tasks/bound-work.js +37 -24
  173. package/dist/tasks/brief.d.ts +38 -14
  174. package/dist/tasks/brief.js +128 -70
  175. package/dist/tasks/budget.d.ts +3 -3
  176. package/dist/tasks/budget.js +9 -4
  177. package/dist/tasks/commands.d.ts +14 -9
  178. package/dist/tasks/commands.js +190 -121
  179. package/dist/tasks/completion.d.ts +12 -0
  180. package/dist/tasks/completion.js +35 -0
  181. package/dist/tasks/contract.d.ts +8 -17
  182. package/dist/tasks/contract.js +41 -43
  183. package/dist/tasks/control.d.ts +138 -0
  184. package/dist/tasks/control.js +1 -0
  185. package/dist/tasks/create.d.ts +1 -1
  186. package/dist/tasks/create.js +3 -3
  187. package/dist/tasks/delivery.d.ts +24 -0
  188. package/dist/tasks/delivery.js +221 -0
  189. package/dist/tasks/file-mutation.d.ts +5 -0
  190. package/dist/tasks/file-mutation.js +38 -0
  191. package/dist/tasks/frontmatter.d.ts +43 -28
  192. package/dist/tasks/frontmatter.js +83 -40
  193. package/dist/tasks/input-receipts.d.ts +7 -0
  194. package/dist/tasks/input-receipts.js +60 -0
  195. package/dist/tasks/loop-log.d.ts +147 -28
  196. package/dist/tasks/loop-log.js +239 -28
  197. package/dist/tasks/receipts.d.ts +19 -0
  198. package/dist/tasks/receipts.js +48 -0
  199. package/dist/tasks/state.d.ts +93 -0
  200. package/dist/tasks/state.js +156 -0
  201. package/dist/tasks/store.d.ts +81 -49
  202. package/dist/tasks/store.js +244 -147
  203. package/dist/tools/bash.d.ts +3 -5
  204. package/dist/tools/bash.js +8 -22
  205. package/dist/tools/contract/details.d.ts +6 -6
  206. package/dist/tools/contract/details.js +6 -6
  207. package/dist/tools/contract/execution-trace.d.ts +4 -0
  208. package/dist/tools/contract/execution-trace.js +23 -0
  209. package/dist/tools/contract/presentation.js +6 -2
  210. package/dist/tools/edit.d.ts +1 -0
  211. package/dist/tools/edit.js +45 -42
  212. package/dist/tools/index.d.ts +8 -12
  213. package/dist/tools/index.js +16 -6
  214. package/dist/tools/memory-manage.js +8 -1
  215. package/dist/tools/registry.d.ts +7 -11
  216. package/dist/tools/registry.js +52 -25
  217. package/dist/tools/skill.d.ts +2 -2
  218. package/dist/tools/skill.js +24 -10
  219. package/dist/tools/subagent-manage.js +7 -4
  220. package/dist/tools/subagent.d.ts +0 -2
  221. package/dist/tools/subagent.js +2 -7
  222. package/dist/tools/task-manage/control-tools.d.ts +4 -0
  223. package/dist/tools/task-manage/control-tools.js +65 -0
  224. package/dist/tools/task-manage/create.js +2 -1
  225. package/dist/tools/task-manage/factory.d.ts +12 -6
  226. package/dist/tools/task-manage/factory.js +72 -57
  227. package/dist/tools/task-manage/lifecycle.d.ts +7 -12
  228. package/dist/tools/task-manage/lifecycle.js +118 -66
  229. package/dist/tools/task-manage/log-view.js +8 -5
  230. package/dist/tools/task-manage/schema.d.ts +21 -26
  231. package/dist/tools/task-manage/schema.js +29 -35
  232. package/dist/tools/task-manage/shared.d.ts +8 -39
  233. package/dist/tools/task-manage/shared.js +19 -68
  234. package/dist/tools/task-manage/step-tools.d.ts +5 -0
  235. package/dist/tools/task-manage/step-tools.js +103 -0
  236. package/dist/tools/task-manage/types.d.ts +25 -18
  237. package/dist/tools/write-content.d.ts +1 -0
  238. package/dist/tools/write-content.js +6 -1
  239. package/dist/tools/write.d.ts +1 -0
  240. package/dist/tools/write.js +1 -0
  241. package/dist/usage/ledger.d.ts +4 -4
  242. package/dist/usage/render.js +2 -2
  243. package/dist/web/search-providers.js +0 -33
  244. package/dist/webapi/request-policy.js +1 -1
  245. package/examples/sub-agents/README.md +23 -16
  246. package/examples/sub-agents/agents/claude-high.md +1 -1
  247. package/examples/sub-agents/agents/claude-main.md +1 -1
  248. package/examples/sub-agents/agents/codex-flash.md +1 -1
  249. package/examples/sub-agents/agents/codex-high.md +1 -1
  250. package/examples/sub-agents/agents/codex-main.md +4 -4
  251. package/examples/sub-agents/agents/cursor-high.md +22 -0
  252. package/examples/sub-agents/agents/cursor-main.md +22 -0
  253. package/examples/sub-agents/agents/glm-flash.md +1 -1
  254. package/examples/sub-agents/agents/glm-high.md +2 -2
  255. package/examples/sub-agents/agents/scout.md +30 -0
  256. package/package.json +6 -6
  257. package/dist/runtime/task-driver.d.ts +0 -116
  258. package/dist/runtime/task-driver.js +0 -443
  259. package/dist/runtime/task-wake.d.ts +0 -48
  260. package/dist/runtime/task-wake.js +0 -32
  261. package/dist/shared/wake-claim.d.ts +0 -23
  262. package/dist/shared/wake-claim.js +0 -26
  263. package/dist/skills/validation.d.ts +0 -8
  264. package/dist/skills/validation.js +0 -91
  265. package/dist/skills/workspace.d.ts +0 -33
  266. package/dist/skills/workspace.js +0 -116
  267. package/dist/tasks/steer.d.ts +0 -8
  268. package/dist/tasks/steer.js +0 -81
  269. package/dist/tasks/ticket.d.ts +0 -71
  270. package/dist/tasks/ticket.js +0 -138
  271. package/dist/tools/task-manage/step-end.d.ts +0 -11
  272. package/dist/tools/task-manage/step-end.js +0 -117
@@ -0,0 +1,69 @@
1
+ import { mkdir, readdir } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { getDeskDir, getDeskLogsDir, isDeskName } from "../desk/paths.js";
4
+ import * as log from "../log.js";
5
+ import { errorMessage } from "../shared/text-utils.js";
6
+ import { DeskJobManager } from "./manager.js";
7
+ /** One application's jobs; the executor and configuration cannot change after construction. */
8
+ export function createJobRuntime(executor, options = {}) {
9
+ const config = { ...options };
10
+ const managers = new Map();
11
+ let stopped = false;
12
+ function get(desk) {
13
+ let manager = managers.get(desk);
14
+ if (!manager) {
15
+ const deskDir = config.workspaceDir ? getDeskDir(config.workspaceDir, desk) : undefined;
16
+ manager = new DeskJobManager({ desk, deskDir }, executor, {
17
+ ...(config.jobsStateDir ? { stateDir: join(config.jobsStateDir, desk) } : {}),
18
+ ...(deskDir ? { spillDir: getDeskLogsDir(deskDir) } : {}),
19
+ ...(config.dispatch ? { dispatch: config.dispatch } : {}),
20
+ ...(config.isBoundTo ? { isBoundTo: config.isBoundTo } : {}),
21
+ ...(config.onTaskInput ? { onTaskInput: config.onTaskInput } : {}),
22
+ ...(config.fileStore ? { fileStore: config.fileStore } : {}),
23
+ ...(config.sweepIntervalMs ? { sweepIntervalMs: config.sweepIntervalMs } : {}),
24
+ });
25
+ managers.set(desk, manager);
26
+ if (stopped)
27
+ manager.stop();
28
+ }
29
+ return manager;
30
+ }
31
+ /**
32
+ * Re-adopt every desk's persisted jobs at startup. Desks are the record directories themselves,
33
+ * and restore does not depend on bindings (spec 058, D6): a job still running when its desk went
34
+ * dormant survives the restart too.
35
+ */
36
+ async function restore() {
37
+ const jobsStateDir = config.jobsStateDir;
38
+ if (!jobsStateDir)
39
+ return 0;
40
+ let desks;
41
+ try {
42
+ await mkdir(jobsStateDir, { recursive: true });
43
+ desks = (await readdir(jobsStateDir, { withFileTypes: true }))
44
+ .filter((entry) => entry.isDirectory() && isDeskName(entry.name))
45
+ .map((entry) => entry.name);
46
+ }
47
+ catch (error) {
48
+ log.logWarn("job.scan.failed", "Persisted background job scan failed", { reason: errorMessage(error) });
49
+ return 0;
50
+ }
51
+ let restored = 0;
52
+ for (const desk of desks) {
53
+ restored += await get(desk).restore();
54
+ }
55
+ if (restored > 0) {
56
+ log.logInfoEvent("job.restore.done", "Background job records restored", { fields: { count: restored } });
57
+ }
58
+ return restored;
59
+ }
60
+ return {
61
+ get,
62
+ restore,
63
+ stop: () => {
64
+ stopped = true;
65
+ for (const manager of managers.values())
66
+ manager.stop();
67
+ },
68
+ };
69
+ }
@@ -5,6 +5,8 @@ import { type DeskMemoryQueue } from "./desk-memory-queue.js";
5
5
  export declare function hasBoundaryReflectWork(conversation: DeskConversation): Promise<boolean>;
6
6
  /** Persist before context is replaced. No desk-memory queue/lock or model request on this path. */
7
7
  export declare function enqueueBoundaryReflectWork(conversation: DeskConversation, entries: SessionEntry[], firstKeptEntryId: string, signal: AbortSignal): Promise<void>;
8
+ /** Also used by /new: publishing a snapshot never takes the inference/desk-memory lock. */
9
+ export declare function enqueueBoundaryReflectEntries(conversation: DeskConversation, entries: SessionEntry[], signal?: AbortSignal): Promise<void>;
8
10
  export interface BoundaryReflectOptions {
9
11
  conversation: DeskConversation;
10
12
  workspaceDir: string;
@@ -1,10 +1,10 @@
1
1
  /** Durable pre-compaction reflect snapshots. Inference never holds up the compaction hook. */
2
2
  import { createHash } from "node:crypto";
3
- import { access, readdir, readFile, unlink } from "node:fs/promises";
3
+ import { access, link, readdir, readFile, unlink } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
  import { getMemoryWorkDir } from "../desk/paths.js";
6
6
  import * as log from "../log.js";
7
- import { writeFileAtomically } from "../shared/atomic-file.js";
7
+ import { createAtomicTempPath, syncDirectoryBestEffort, writeFileAtomically } from "../shared/atomic-file.js";
8
8
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
9
9
  import { isNodeError } from "../shared/os.js";
10
10
  import { errorMessage } from "../shared/text-utils.js";
@@ -12,7 +12,8 @@ import { isRecord } from "../shared/type-guards.js";
12
12
  import { getDeskMemoryQueue } from "./desk-memory-queue.js";
13
13
  import { readMemoryMaintenanceState, updateMemoryMaintenanceState } from "./maintenance-state.js";
14
14
  import { runReflect } from "./reflect.js";
15
- import { appendMemoryReviewLog } from "./review-log.js";
15
+ import { reviewLogEntryFor, tryAppendMemoryReviewLog } from "./review-log.js";
16
+ import { selectMemorySourceBatch } from "./source-window.js";
16
17
  import { sanitizeMessagesForMemory } from "./transcript.js";
17
18
  function workDir(conversation) {
18
19
  return join(getMemoryWorkDir(conversation.deskDir), conversation.conversation);
@@ -47,27 +48,44 @@ export async function enqueueBoundaryReflectWork(conversation, entries, firstKep
47
48
  const cut = entries.findIndex((entry) => entry.id === firstKeptEntryId);
48
49
  if (cut < 0)
49
50
  throw new Error("Cannot preserve compaction memory: kept entry is missing. Use /new to recover.");
50
- const prefix = entries.slice(0, cut);
51
- if (prefix.length === 0)
51
+ await enqueueBoundaryReflectEntries(conversation, entries.slice(0, cut), signal);
52
+ }
53
+ /** Also used by /new: publishing a snapshot never takes the inference/desk-memory lock. */
54
+ export async function enqueueBoundaryReflectEntries(conversation, entries, signal) {
55
+ signal?.throwIfAborted();
56
+ if (entries.length === 0)
52
57
  return;
53
58
  const id = createHash("sha256")
54
- .update(prefix.map((entry) => entry.id).join("\0"))
59
+ .update(entries.map((entry) => entry.id).join("\0"))
55
60
  .digest("hex")
56
61
  .slice(0, 32);
57
62
  if (await completed(conversation, id))
58
63
  return;
59
- signal.throwIfAborted();
60
64
  const work = {
61
65
  version: 1,
62
66
  id,
63
67
  createdAt: Date.now(),
64
- entryIds: prefix.map((entry) => entry.id),
65
- messages: prefix.flatMap((entry) => entry.type === "message"
68
+ entryIds: entries.map((entry) => entry.id),
69
+ messages: entries.flatMap((entry) => entry.type === "message"
66
70
  ? sanitizeMessagesForMemory([entry.message]).map((message) => ({ entryId: entry.id, message }))
67
71
  : []),
68
72
  };
69
- await writeFileAtomically(join(workDir(conversation), `${id}.json`), `${JSON.stringify(work)}\n`);
70
- signal.throwIfAborted();
73
+ const path = join(workDir(conversation), `${id}.json`);
74
+ const temporary = createAtomicTempPath(path);
75
+ try {
76
+ await writeFileAtomically(temporary, `${JSON.stringify(work)}\n`);
77
+ signal?.throwIfAborted();
78
+ // Publish once: a duplicate enqueue must never restore already-processed batches.
79
+ await link(temporary, path).catch((error) => {
80
+ if (!isNodeError(error) || error.code !== "EEXIST")
81
+ throw error;
82
+ });
83
+ syncDirectoryBestEffort(workDir(conversation));
84
+ }
85
+ finally {
86
+ await unlink(temporary).catch(() => undefined);
87
+ }
88
+ signal?.throwIfAborted();
71
89
  }
72
90
  /** Called by the live lifecycle and the startup/idle scheduler, including when idle maintenance is off. */
73
91
  export async function drainBoundaryReflectWork(options) {
@@ -110,42 +128,66 @@ export async function drainBoundaryReflectWork(options) {
110
128
  for (const item of work) {
111
129
  const state = await readMemoryMaintenanceState(appHomeDir, conversation);
112
130
  const cursor = state.lastReflectedEntryId ? item.entryIds.indexOf(state.lastReflectedEntryId) : -1;
113
- const remaining = new Set(item.entryIds.slice(cursor + 1));
114
- const messages = item.messages
115
- .filter((entry) => remaining.has(entry.entryId))
116
- .map((entry) => entry.message);
117
- // A crash after checkpointing but before removing the work must not repeat inference.
118
- if (cursor !== item.entryIds.length - 1) {
119
- const result = await runReflect({
131
+ const byId = new Map(item.messages.map((entry) => [entry.entryId, entry.message]));
132
+ const remaining = item.entryIds.slice(cursor + 1).map((id) => ({ id, message: byId.get(id) }));
133
+ const batch = selectMemorySourceBatch(remaining, true);
134
+ const throughEntryId = batch.entries.at(-1)?.id;
135
+ // A crash after checkpointing but before removing work need not repeat inference.
136
+ const result = batch.entries.length
137
+ ? await runReflect({
120
138
  channelId: conversation.channelId,
121
139
  deskDir: conversation.deskDir,
122
140
  workspaceDir: options.workspaceDir,
123
141
  model: options.model,
124
142
  resolveApiKey: options.resolveApiKey,
125
- messages,
126
- usageContext: { channelId: conversation.channelId, desk: conversation.desk, correlationId: item.id },
127
- });
128
- await appendMemoryReviewLog(conversation.deskDir, {
143
+ messages: batch.messages,
144
+ sourceClosed: true,
145
+ usageContext: {
146
+ channelId: conversation.channelId,
147
+ desk: conversation.desk,
148
+ correlationId: item.id,
149
+ },
150
+ })
151
+ : undefined;
152
+ if (throughEntryId) {
153
+ await updateMemoryMaintenanceState(appHomeDir, conversation, (current) => ({
154
+ ...current,
155
+ lastReflectedEntryId: !current.lastReflectedEntryId || item.entryIds.includes(current.lastReflectedEntryId)
156
+ ? throughEntryId
157
+ : current.lastReflectedEntryId,
158
+ failureBackoffUntil: null,
159
+ lastReflectAt: batch.hasMore ? current.lastReflectAt : formatLocalTime(),
160
+ }));
161
+ }
162
+ if (batch.hasMore) {
163
+ const ids = remaining.slice(batch.entries.length).map((entry) => entry.id);
164
+ const pending = new Set(ids);
165
+ await writeFileAtomically(join(workDir(conversation), `${item.id}.json`), `${JSON.stringify({
166
+ ...item,
167
+ entryIds: ids,
168
+ messages: item.messages.filter((entry) => pending.has(entry.entryId)),
169
+ })}\n`);
170
+ }
171
+ else {
172
+ await writeFileAtomically(join(workDir(conversation), `${item.id}.done`), `${item.id}\n`);
173
+ await unlink(join(workDir(conversation), `${item.id}.json`));
174
+ }
175
+ if (result)
176
+ await tryAppendMemoryReviewLog(conversation.deskDir, {
129
177
  timestamp: formatLocalTime(),
130
178
  channelId: conversation.channelId,
131
179
  reason: "reflect-boundary",
132
180
  correlationId: item.id,
133
- actions: [{ target: "memory", action: "reflect", added: result.added, updated: result.updated }],
181
+ ...reviewLogEntryFor(result, {
182
+ hasMore: batch.hasMore,
183
+ sampledChars: batch.sampledChars,
184
+ throughEntryId,
185
+ fromEntryId: state.lastReflectedEntryId,
186
+ }),
134
187
  });
135
- }
136
- await updateMemoryMaintenanceState(appHomeDir, conversation, (current) => ({
137
- ...current,
138
- // A later session/idle pass may already be ahead of this snapshot.
139
- lastReflectedEntryId: !current.lastReflectedEntryId || item.entryIds.includes(current.lastReflectedEntryId)
140
- ? item.entryIds.at(-1)
141
- : current.lastReflectedEntryId,
142
- }));
143
- await updateMemoryMaintenanceState(appHomeDir, conversation, (current) => ({
144
- ...current,
145
- failureBackoffUntil: null,
146
- }));
147
- await writeFileAtomically(join(workDir(conversation), `${item.id}.done`), `${item.id}\n`);
148
- await unlink(join(workDir(conversation), `${item.id}.json`));
188
+ // At most one model call per drain, including across queued snapshots.
189
+ if (result)
190
+ return;
149
191
  }
150
192
  });
151
193
  }
@@ -6,7 +6,7 @@ import { buildMemoryIndexForBootstrap, MEMORY_INDEX_MAX_UNITS } from "./index-bu
6
6
  import { listJournalDates, readJournalDay } from "./journal.js";
7
7
  import { readMemoryMaintenanceState } from "./maintenance-state.js";
8
8
  import { appendMemoryReviewLog } from "./review-log.js";
9
- import { applyMemoryOps, listMemoryEntries, MEMORY_TYPE_ORDER, readMemoryEntry, } from "./store.js";
9
+ import { applyMemoryOps, isValidMemoryName, listMemoryEntries, MEMORY_TYPE_ORDER, readMemoryEntry, } from "./store.js";
10
10
  import { hashMemoryContent } from "./tombstones.js";
11
11
  function renderUsage() {
12
12
  return renderSubcommandUsage("memory");
@@ -120,6 +120,9 @@ export async function handleMemoryCommand(options) {
120
120
  return handleStatus(options);
121
121
  if (action === "list")
122
122
  return handleList(options, argument);
123
+ if ((action === "show" || action === "forget") && argument && !isValidMemoryName(argument)) {
124
+ return "记忆名称格式不正确。请用 `/memory list` 查找名称,再查看或删除对应记忆。";
125
+ }
123
126
  if (action === "show")
124
127
  return handleShow(options, argument);
125
128
  if (action === "forget")
@@ -58,32 +58,35 @@ export function clipWorkspaceMemoryForBootstrap(workspaceMemory, maxUnits = WORK
58
58
  return text;
59
59
  }
60
60
  const sections = splitH2Sections(text);
61
+ const notice = "[... background omitted; read workspace/MEMORY.md ...]";
61
62
  if (sections.length === 0) {
62
63
  return clipTextByPromptUnits(text, maxUnits, {
63
64
  headRatio: 1,
64
65
  maxChars: WORKSPACE_MEMORY_MAX_CHARS,
65
- marker: "\n\n[... omitted for length ...]\n",
66
+ marker: `\n\n${notice}`,
66
67
  }).text;
67
68
  }
68
- const head = text.slice(0, text.indexOf("## ") === -1 ? 0 : text.indexOf("## ")).trim();
69
- const kept = head ? [head] : [];
70
- let used = countPromptUnits(kept.join("\n\n"));
71
- let omitted = 0;
69
+ if (countPromptUnits(notice) > maxUnits)
70
+ return "";
71
+ const head = text.slice(0, /^## /m.exec(text)?.index ?? 0).trim();
72
+ const kept = [];
73
+ if (head) {
74
+ const clipped = clipTextByPromptUnits(head, maxUnits - countPromptUnits(notice), {
75
+ headRatio: 1,
76
+ maxChars: WORKSPACE_MEMORY_MAX_CHARS - notice.length - 2,
77
+ marker: "\n[... omitted ...]",
78
+ }).text;
79
+ if (clipped)
80
+ kept.push(clipped);
81
+ }
72
82
  for (const section of sections) {
73
83
  const block = `## ${section.heading}\n\n${section.content}`;
74
- const cost = countPromptUnits(block);
75
- if (used + cost <= maxUnits && kept.join("\n\n").length + block.length <= WORKSPACE_MEMORY_MAX_CHARS) {
84
+ const candidate = [...kept, block, notice].join("\n\n");
85
+ if (countPromptUnits(candidate) <= maxUnits && candidate.length <= WORKSPACE_MEMORY_MAX_CHARS) {
76
86
  kept.push(block);
77
- used += cost;
78
- }
79
- else {
80
- omitted++;
81
87
  }
82
88
  }
83
- if (omitted > 0) {
84
- kept.push(`[... ${omitted} more section(s) omitted; read workspace/MEMORY.md ...]`);
85
- }
86
- return kept.join("\n\n");
89
+ return [...kept, notice].join("\n\n");
87
90
  }
88
91
  /** Tail of a journal day, clipped to the injection budget (head dropped, newest kept). */
89
92
  export function clipJournalTailForBootstrap(journalText, maxUnits = JOURNAL_TAIL_MAX_UNITS) {
@@ -3,6 +3,7 @@ import { join } from "node:path";
3
3
  import { writeFileAtomically } from "../shared/atomic-file.js";
4
4
  import { localDayKey } from "../shared/local-time.js";
5
5
  import { isNodeError, readOptionalTextFile } from "../shared/os.js";
6
+ import { redactSecrets } from "./secret-redaction.js";
6
7
  /**
7
8
  * Spec 050, D5: `journal/YYYY-MM-DD.md`, append-only, one file per local day — never folded or
8
9
  * rewritten, so it stays a plain, growing record.
@@ -87,7 +88,7 @@ function normalizeLine(line) {
87
88
  * hand-edited file too.
88
89
  */
89
90
  export async function appendJournalEntries(deskDir, date, lines) {
90
- const trimmedLines = lines.map((line) => line.trim()).filter(Boolean);
91
+ const trimmedLines = lines.map((line) => redactSecrets(line).trim()).filter(Boolean);
91
92
  if (trimmedLines.length === 0) {
92
93
  return { appended: 0, skippedDuplicate: 0 };
93
94
  }
@@ -5,7 +5,7 @@ import type { DeskConversation } from "../desk/types.js";
5
5
  import { type DeskMemoryQueue } from "./desk-memory-queue.js";
6
6
  import { type MemoryActivityEvent } from "./maintenance-state.js";
7
7
  /** Boundaries `MemoryLifecycle` reflects on directly, outside the scheduled idle job (spec 050, D7). */
8
- export type ConsolidationReason = "new-session" | "shutdown";
8
+ export type ConsolidationReason = "shutdown";
9
9
  export interface MemoryLifecycleOptions {
10
10
  /** Request-owned sessions must never reflect imported client history. */
11
11
  enabled?: boolean;
@@ -26,7 +26,7 @@ export declare class MemoryLifecycle {
26
26
  private durableRevision;
27
27
  private lastDurableConsolidationRevision;
28
28
  private readonly memoryQueue;
29
- private backgroundNewSessionReflect;
29
+ private boundaryReflect;
30
30
  constructor(options: MemoryLifecycleOptions);
31
31
  createExtensionFactory(): ExtensionFactory;
32
32
  noteUserTurnStarted(): void;
@@ -38,18 +38,14 @@ export declare class MemoryLifecycle {
38
38
  private markDurableConsolidationCheckpoint;
39
39
  private logReflectResult;
40
40
  private appendReviewLog;
41
- private runBoundaryReflect;
42
41
  private runBoundaryReflectNow;
43
42
  /** The agent's bounded compaction operation awaits only durable snapshot persistence. */
44
43
  prepareCompaction(event: SessionBeforeCompactEvent): Promise<void>;
45
44
  resumeBoundaryReflect(): Promise<void>;
46
45
  private startBoundaryReflect;
47
46
  private handleSessionCompact;
48
- private handleSessionBeforeSwitch;
49
- /** Snapshot the outgoing state for an out-of-band `/new` before its runner is retired. */
50
- noteNewSessionBoundary(): void;
51
- /** Await any in-flight detached new-session reflect run (shutdown/tests). */
52
- whenNewSessionReflectSettled(): Promise<void>;
47
+ /** Persist the outgoing branch before a switch; never wait for inference or the desk queue. */
48
+ prepareNewSession(): Promise<void>;
53
49
  private handleSessionStart;
54
50
  private recordActivity;
55
51
  }
@@ -1,12 +1,11 @@
1
1
  import * as log from "../log.js";
2
2
  import { formatLocalTime } from "../shared/local-time.js";
3
3
  import { errorMessage } from "../shared/text-utils.js";
4
- import { drainBoundaryReflectWork, enqueueBoundaryReflectWork } from "./boundary-work.js";
4
+ import { drainBoundaryReflectWork, enqueueBoundaryReflectEntries, enqueueBoundaryReflectWork, hasBoundaryReflectWork, } from "./boundary-work.js";
5
5
  import { getDeskMemoryQueue } from "./desk-memory-queue.js";
6
6
  import { readMemoryMaintenanceState, updateMemoryMaintenanceState, } from "./maintenance-state.js";
7
7
  import { runReflect } from "./reflect.js";
8
- import { reviewLogEntryFor } from "./reflect-job.js";
9
- import { appendMemoryReviewLog } from "./review-log.js";
8
+ import { appendMemoryReviewLog, reviewLogEntryFor } from "./review-log.js";
10
9
  import { buildIncrementalMemorySourceWindow } from "./source-window.js";
11
10
  export class MemoryLifecycle {
12
11
  constructor(options) {
@@ -14,8 +13,8 @@ export class MemoryLifecycle {
14
13
  this.durableDirty = false;
15
14
  this.durableRevision = 0;
16
15
  this.lastDurableConsolidationRevision = 0;
17
- // Tracks the detached new-session reflect run so shutdown/tests can await it.
18
- this.backgroundNewSessionReflect = Promise.resolve();
16
+ // Tracks the current durable-boundary drain so shutdown can await it.
17
+ this.boundaryReflect = Promise.resolve();
19
18
  this.memoryQueue = options.memoryQueue ?? getDeskMemoryQueue();
20
19
  }
21
20
  createExtensionFactory() {
@@ -28,8 +27,9 @@ export class MemoryLifecycle {
28
27
  pi.on("session_compact_failed", () => {
29
28
  this.startBoundaryReflect();
30
29
  });
31
- pi.on("session_before_switch", (event) => {
32
- this.handleSessionBeforeSwitch(event);
30
+ pi.on("session_before_switch", async (event) => {
31
+ if (event.reason === "new")
32
+ await this.prepareNewSession();
33
33
  });
34
34
  pi.on("session_start", async (event) => {
35
35
  this.handleSessionStart(event);
@@ -57,10 +57,9 @@ export class MemoryLifecycle {
57
57
  if (this.options.enabled === false)
58
58
  return;
59
59
  await this.resumeBoundaryReflect();
60
- // Let any detached new-session reflect run finish (and update the durable checkpoint)
61
- // before deciding whether a final flush is still needed.
62
- await this.whenNewSessionReflectSettled();
63
60
  await this.runDurableMemoryJobSerial(async () => {
61
+ if (await hasBoundaryReflectWork(this.options.conversation))
62
+ return;
64
63
  // Shutdown is the last chance to persist, so use a looser gate than the
65
64
  // idle/compaction path: reflect on any unconsolidated durable activity, including a
66
65
  // session that only produced tool output with no final assistant turn.
@@ -111,14 +110,6 @@ export class MemoryLifecycle {
111
110
  });
112
111
  }
113
112
  }
114
- async runBoundaryReflect(reason, messages, sessionEntries) {
115
- const messageSnapshot = [...(messages ?? this.options.getMessages())];
116
- const sessionEntrySnapshot = sessionEntries ? [...sessionEntries] : [...this.options.getSessionEntries()];
117
- const revisionSnapshot = this.durableRevision;
118
- await this.runDurableMemoryJobSerial(async () => {
119
- await this.runBoundaryReflectNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot);
120
- });
121
- }
122
113
  async runBoundaryReflectNow(reason, messageSnapshot, sessionEntrySnapshot = [], revisionSnapshot = this.durableRevision) {
123
114
  try {
124
115
  const maintenanceState = this.options.appHomeDir
@@ -129,6 +120,7 @@ export class MemoryLifecycle {
129
120
  entries: sessionEntrySnapshot,
130
121
  lastEntryId,
131
122
  sourceKind: reason,
123
+ closed: true,
132
124
  fallbackMessages: messageSnapshot,
133
125
  });
134
126
  log.logInfo(`[${this.options.conversation.channelId}] Memory reflect starting (${reason})`);
@@ -139,6 +131,7 @@ export class MemoryLifecycle {
139
131
  model: this.options.getModel(),
140
132
  resolveApiKey: this.options.resolveApiKey,
141
133
  messages: sourceWindow.messages,
134
+ sourceClosed: true,
142
135
  usageContext: {
143
136
  channelId: this.options.conversation.channelId,
144
137
  desk: this.options.conversation.desk,
@@ -149,16 +142,17 @@ export class MemoryLifecycle {
149
142
  await updateMemoryMaintenanceState(this.options.appHomeDir, this.options.conversation, (current) => ({
150
143
  ...current,
151
144
  lastReflectedEntryId: sourceWindow.throughEntryId,
152
- lastReflectAt: formatLocalTime(),
145
+ lastReflectAt: sourceWindow.hasMore ? current.lastReflectAt : formatLocalTime(),
153
146
  failureBackoffUntil: null,
154
147
  }));
155
148
  }
156
- this.markDurableConsolidationCheckpoint(revisionSnapshot);
149
+ if (!sourceWindow.hasMore)
150
+ this.markDurableConsolidationCheckpoint(revisionSnapshot);
157
151
  this.logReflectResult(reason, result);
158
152
  await this.appendReviewLog({
159
153
  reason: "reflect-boundary",
160
154
  correlationId: sourceWindow.windowId,
161
- ...reviewLogEntryFor(result),
155
+ ...reviewLogEntryFor(result, sourceWindow),
162
156
  });
163
157
  }
164
158
  catch (error) {
@@ -183,14 +177,14 @@ export class MemoryLifecycle {
183
177
  }
184
178
  resumeBoundaryReflect() {
185
179
  this.startBoundaryReflect();
186
- return this.backgroundNewSessionReflect;
180
+ return this.boundaryReflect;
187
181
  }
188
182
  startBoundaryReflect() {
189
183
  if (this.options.enabled === false)
190
184
  return;
191
185
  if (!this.options.appHomeDir)
192
186
  return;
193
- this.backgroundNewSessionReflect = drainBoundaryReflectWork({
187
+ this.boundaryReflect = drainBoundaryReflectWork({
194
188
  conversation: this.options.conversation,
195
189
  workspaceDir: this.options.workspaceDir,
196
190
  appHomeDir: this.options.appHomeDir,
@@ -203,43 +197,19 @@ export class MemoryLifecycle {
203
197
  this.recordActivity("boundary");
204
198
  this.startBoundaryReflect();
205
199
  }
206
- handleSessionBeforeSwitch(event) {
207
- if (event.reason !== "new") {
208
- return;
209
- }
210
- this.noteNewSessionBoundary();
211
- }
212
- /** Snapshot the outgoing state for an out-of-band `/new` before its runner is retired. */
213
- noteNewSessionBoundary() {
200
+ /** Persist the outgoing branch before a switch; never wait for inference or the desk queue. */
201
+ async prepareNewSession() {
214
202
  if (this.options.enabled === false)
215
203
  return;
216
- // Snapshot the outgoing session synchronously: the switch has not happened yet, so
217
- // getMessages()/getSessionEntries() still reference the session about to be replaced.
218
- // Once we yield, this.session is rebound to the new (empty) session and the snapshot
219
- // would be lost.
220
- const messageSnapshot = [...this.options.getMessages()];
221
- const sessionEntrySnapshot = [...this.options.getSessionEntries()];
222
- // Run the LLM-backed reflect pass in the background so /new returns immediately.
223
- // Failures are tolerated: runBoundaryReflectNow catches and logs its own errors, and the
224
- // serial queue keeps this from racing with idle/maintenance work on the same channel.
225
- this.backgroundNewSessionReflect = this.runBoundaryReflect("new-session", messageSnapshot, sessionEntrySnapshot).catch((error) => {
226
- const message = errorMessage(error);
227
- log.logWarn("memory.reflect.rejected", "Background new-session reflect rejected", {
228
- channelId: this.options.conversation.channelId,
229
- reason: message,
230
- });
231
- });
204
+ await enqueueBoundaryReflectEntries(this.options.conversation, [...this.options.getSessionEntries()]);
232
205
  this.recordActivity("boundary");
233
206
  }
234
- /** Await any in-flight detached new-session reflect run (shutdown/tests). */
235
- async whenNewSessionReflectSettled() {
236
- await this.backgroundNewSessionReflect;
237
- }
238
207
  handleSessionStart(event) {
239
208
  if (event.reason !== "new") {
240
209
  return;
241
210
  }
242
211
  this.recordActivity("boundary");
212
+ this.startBoundaryReflect();
243
213
  }
244
214
  recordActivity(kind) {
245
215
  if (this.options.enabled === false)
@@ -4,7 +4,6 @@ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
4
4
  import type { DeskConversation } from "../desk/types.js";
5
5
  import { type DeskMemoryQueue } from "./desk-memory-queue.js";
6
6
  import { type MemoryMaintenanceInput } from "./maintenance-tuning.js";
7
- import { runReflect } from "./reflect.js";
8
7
  /**
9
8
  * Spec 050, D7/D9: the scheduler's idle-tick entry point into the reflect pass. Boundary
10
9
  * triggers (compaction, `/new`, shutdown) bypass this job entirely and call `reflect.js`
@@ -29,8 +28,3 @@ export interface ReflectJobInput {
29
28
  queue?: DeskMemoryQueue;
30
29
  }
31
30
  export declare function runReflectJob(input: ReflectJobInput): Promise<void>;
32
- /** Shared by the idle job and `lifecycle.ts`'s boundary calls, so both write the same shape. */
33
- export declare function reviewLogEntryFor(result: Awaited<ReturnType<typeof runReflect>>): {
34
- actions?: unknown[];
35
- skipped?: unknown[];
36
- };