@oyasmi/pipiclaw 0.9.1-beta.2 → 0.9.2-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 (189) hide show
  1. package/dist/agent/channel-runner.d.ts +9 -1
  2. package/dist/agent/channel-runner.js +51 -18
  3. package/dist/agent/command-extension.js +24 -27
  4. package/dist/agent/commands.d.ts +51 -7
  5. package/dist/agent/commands.js +199 -59
  6. package/dist/agent/effect-ledger.js +9 -2
  7. package/dist/agent/job-manager.d.ts +4 -0
  8. package/dist/agent/job-manager.js +17 -2
  9. package/dist/agent/prompt/manifest.d.ts +1 -1
  10. package/dist/agent/prompt/manifest.js +6 -7
  11. package/dist/agent/prompt/sections.js +9 -5
  12. package/dist/agent/reply-limits.d.ts +16 -0
  13. package/dist/agent/reply-limits.js +17 -0
  14. package/dist/agent/session-events.d.ts +2 -0
  15. package/dist/agent/session-events.js +29 -14
  16. package/dist/agent/status-render.js +12 -12
  17. package/dist/agent/turn-recovery.js +2 -2
  18. package/dist/agent/type-guards.js +5 -1
  19. package/dist/agent/workspace-resources.d.ts +2 -2
  20. package/dist/agent/workspace-resources.js +41 -3
  21. package/dist/executor.d.ts +28 -0
  22. package/dist/executor.js +120 -18
  23. package/dist/file-store.d.ts +96 -0
  24. package/dist/file-store.js +189 -0
  25. package/dist/main.js +3 -4
  26. package/dist/memory/commands.js +79 -38
  27. package/dist/memory/consolidation.d.ts +5 -1
  28. package/dist/memory/consolidation.js +35 -38
  29. package/dist/memory/extraction.d.ts +8 -1
  30. package/dist/memory/extraction.js +47 -4
  31. package/dist/memory/files.d.ts +0 -1
  32. package/dist/memory/files.js +31 -12
  33. package/dist/memory/lifecycle.js +9 -2
  34. package/dist/memory/maintenance-jobs.js +16 -38
  35. package/dist/memory/maintenance-state.js +2 -1
  36. package/dist/memory/metadata.d.ts +3 -0
  37. package/dist/memory/metadata.js +7 -0
  38. package/dist/memory/recall.d.ts +19 -0
  39. package/dist/memory/recall.js +116 -24
  40. package/dist/memory/review-log.d.ts +0 -2
  41. package/dist/memory/review-log.js +0 -0
  42. package/dist/memory/session-corpus.js +5 -0
  43. package/dist/memory/session-search.js +15 -22
  44. package/dist/memory/sidecar-worker.js +4 -0
  45. package/dist/memory/source-window.d.ts +0 -1
  46. package/dist/memory/source-window.js +0 -5
  47. package/dist/memory/transcript.d.ts +10 -0
  48. package/dist/memory/transcript.js +39 -0
  49. package/dist/playbooks/agent-delegation.md +34 -25
  50. package/dist/playbooks/background-jobs.md +8 -16
  51. package/dist/playbooks/catalog.d.ts +1 -1
  52. package/dist/playbooks/catalog.js +1 -1
  53. package/dist/playbooks/event-scheduling.md +15 -15
  54. package/dist/playbooks/memory-and-learning.md +30 -23
  55. package/dist/playbooks/outbound-media.md +15 -8
  56. package/dist/playbooks/runtime-orientation.md +40 -37
  57. package/dist/playbooks/task-driving.md +36 -38
  58. package/dist/playbooks/task-planning.md +21 -21
  59. package/dist/runtime/app-home.d.ts +6 -0
  60. package/dist/runtime/app-home.js +16 -7
  61. package/dist/runtime/bootstrap.js +54 -13
  62. package/dist/runtime/channel-context.d.ts +2 -1
  63. package/dist/runtime/delivery.js +3 -3
  64. package/dist/runtime/dingtalk.d.ts +9 -1
  65. package/dist/runtime/dingtalk.js +30 -15
  66. package/dist/runtime/durable-dispatch.d.ts +26 -1
  67. package/dist/runtime/durable-dispatch.js +51 -5
  68. package/dist/runtime/event-commands.d.ts +15 -0
  69. package/dist/runtime/event-commands.js +55 -56
  70. package/dist/runtime/events.d.ts +4 -2
  71. package/dist/runtime/events.js +15 -20
  72. package/dist/runtime/project-commands.d.ts +16 -0
  73. package/dist/runtime/project-commands.js +13 -17
  74. package/dist/runtime/subagent-commands.d.ts +20 -0
  75. package/dist/runtime/subagent-commands.js +61 -58
  76. package/dist/runtime/task-commands.d.ts +37 -0
  77. package/dist/runtime/task-commands.js +108 -66
  78. package/dist/runtime/task-driver.js +2 -2
  79. package/dist/security/block-message.d.ts +11 -0
  80. package/dist/security/block-message.js +12 -0
  81. package/dist/security/path-guard-check.d.ts +13 -0
  82. package/dist/security/path-guard-check.js +39 -0
  83. package/dist/security/path-guard.js +61 -12
  84. package/dist/security/types.d.ts +9 -0
  85. package/dist/settings.js +3 -2
  86. package/dist/shared/atomic-file.d.ts +17 -1
  87. package/dist/shared/atomic-file.js +50 -3
  88. package/dist/shared/duration.d.ts +2 -0
  89. package/dist/shared/duration.js +7 -0
  90. package/dist/shared/safe-id.d.ts +19 -0
  91. package/dist/shared/safe-id.js +24 -0
  92. package/dist/shared/text-utils.d.ts +1 -1
  93. package/dist/shared/text-utils.js +3 -8
  94. package/dist/shared/type-guards.d.ts +2 -0
  95. package/dist/shared/type-guards.js +4 -0
  96. package/dist/subagents/discovery.d.ts +51 -19
  97. package/dist/subagents/discovery.js +93 -98
  98. package/dist/subagents/external/claude-code.js +40 -2
  99. package/dist/subagents/external/harness.d.ts +1 -1
  100. package/dist/subagents/external/run.js +61 -8
  101. package/dist/subagents/format.d.ts +3 -2
  102. package/dist/subagents/format.js +3 -7
  103. package/dist/subagents/runs.d.ts +1 -1
  104. package/dist/subagents/runs.js +10 -9
  105. package/dist/subagents/tool.d.ts +31 -18
  106. package/dist/subagents/tool.js +592 -562
  107. package/dist/subagents/workspace-lease.js +1 -1
  108. package/dist/tasks/control.js +7 -9
  109. package/dist/tasks/ledger.d.ts +2 -2
  110. package/dist/tasks/ledger.js +3 -7
  111. package/dist/tasks/transitions.d.ts +5 -1
  112. package/dist/tasks/transitions.js +2 -2
  113. package/dist/tasks/verification.d.ts +7 -5
  114. package/dist/tools/bash.d.ts +1 -2
  115. package/dist/tools/bash.js +99 -76
  116. package/dist/tools/config.d.ts +6 -1
  117. package/dist/tools/config.js +9 -0
  118. package/dist/tools/edit.d.ts +2 -3
  119. package/dist/tools/edit.js +276 -75
  120. package/dist/tools/event-manage.d.ts +13 -7
  121. package/dist/tools/event-manage.js +52 -14
  122. package/dist/tools/glob-match.d.ts +11 -0
  123. package/dist/tools/glob-match.js +75 -0
  124. package/dist/tools/glob.d.ts +15 -0
  125. package/dist/tools/glob.js +113 -0
  126. package/dist/tools/grep.d.ts +0 -1
  127. package/dist/tools/grep.js +60 -44
  128. package/dist/tools/ignore-dirs.d.ts +6 -0
  129. package/dist/tools/ignore-dirs.js +15 -0
  130. package/dist/tools/index.d.ts +3 -0
  131. package/dist/tools/index.js +54 -40
  132. package/dist/tools/job.d.ts +0 -1
  133. package/dist/tools/job.js +3 -9
  134. package/dist/tools/line-index.d.ts +16 -0
  135. package/dist/tools/line-index.js +76 -0
  136. package/dist/tools/memory-manage.d.ts +21 -8
  137. package/dist/tools/memory-manage.js +114 -103
  138. package/dist/tools/presentation.d.ts +2 -0
  139. package/dist/tools/presentation.js +109 -0
  140. package/dist/tools/read.d.ts +2 -2
  141. package/dist/tools/read.js +100 -120
  142. package/dist/tools/registry.d.ts +4 -1
  143. package/dist/tools/registry.js +89 -22
  144. package/dist/tools/send-media.d.ts +6 -6
  145. package/dist/tools/send-media.js +21 -43
  146. package/dist/tools/session-search.d.ts +0 -1
  147. package/dist/tools/session-search.js +0 -1
  148. package/dist/tools/skill-security.d.ts +0 -2
  149. package/dist/tools/skill-security.js +1 -25
  150. package/dist/tools/skill.d.ts +31 -0
  151. package/dist/tools/skill.js +153 -0
  152. package/dist/tools/subagent-manage.d.ts +6 -5
  153. package/dist/tools/subagent-manage.js +47 -47
  154. package/dist/tools/task-manage/create.d.ts +2 -2
  155. package/dist/tools/task-manage/create.js +1 -3
  156. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  157. package/dist/tools/task-manage/lifecycle.js +49 -56
  158. package/dist/tools/task-manage/schema.d.ts +27 -15
  159. package/dist/tools/task-manage/schema.js +58 -74
  160. package/dist/tools/task-manage/shared.d.ts +11 -6
  161. package/dist/tools/task-manage/shared.js +30 -21
  162. package/dist/tools/task-manage/types.d.ts +14 -15
  163. package/dist/tools/task-manage/verification.d.ts +4 -4
  164. package/dist/tools/task-manage/verification.js +6 -8
  165. package/dist/tools/task-manage.d.ts +8 -11
  166. package/dist/tools/task-manage.js +63 -50
  167. package/dist/tools/tool-details.d.ts +17 -1
  168. package/dist/tools/tool-details.js +24 -0
  169. package/dist/tools/truncate.d.ts +8 -0
  170. package/dist/tools/truncate.js +8 -0
  171. package/dist/tools/web-fetch.d.ts +0 -1
  172. package/dist/tools/web-fetch.js +9 -2
  173. package/dist/tools/web-search.d.ts +0 -1
  174. package/dist/tools/web-search.js +0 -1
  175. package/dist/tools/write-content.d.ts +3 -3
  176. package/dist/tools/write-content.js +12 -41
  177. package/dist/tools/write.d.ts +2 -3
  178. package/dist/tools/write.js +3 -4
  179. package/dist/tui/app.js +1 -1
  180. package/dist/tui/commands.d.ts +1 -1
  181. package/dist/tui/commands.js +1 -1
  182. package/dist/tui/turn-controller.d.ts +1 -1
  183. package/dist/tui/turn-controller.js +14 -4
  184. package/dist/usage/ledger.js +7 -4
  185. package/dist/usage/render.js +10 -8
  186. package/examples/sub-agents/README.md +2 -0
  187. package/package.json +3 -2
  188. package/dist/tools/skill-manage.d.ts +0 -41
  189. package/dist/tools/skill-manage.js +0 -231
@@ -0,0 +1,189 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { stat as fsStat, mkdir, open, readdir, rename, unlink } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { Writable } from "node:stream";
5
+ import { createAtomicTempPath, writeFileAtomically } from "./shared/atomic-file.js";
6
+ export function fingerprintOf(stat) {
7
+ return { size: stat.size, mtimeMs: stat.mtimeMs, ino: stat.ino };
8
+ }
9
+ export function fingerprintsEqual(a, b) {
10
+ return a.size === b.size && a.mtimeMs === b.mtimeMs && a.ino === b.ino;
11
+ }
12
+ export function createFileStore() {
13
+ return new HostFileStore();
14
+ }
15
+ function toFileStat(raw) {
16
+ return {
17
+ size: raw.size,
18
+ mtimeMs: raw.mtimeMs,
19
+ ino: raw.ino,
20
+ mode: raw.mode,
21
+ isDirectory: raw.isDirectory(),
22
+ isFile: raw.isFile(),
23
+ };
24
+ }
25
+ function throwIfAborted(signal) {
26
+ if (signal?.aborted) {
27
+ throw new Error("Aborted");
28
+ }
29
+ }
30
+ /** Best-effort directory fsync after a rename; mirrors `shared/atomic-file.ts`'s own tolerance. */
31
+ async function fsyncDir(dir) {
32
+ await open(dir, "r")
33
+ .then(async (dirHandle) => {
34
+ try {
35
+ await dirHandle.sync();
36
+ }
37
+ finally {
38
+ await dirHandle.close();
39
+ }
40
+ })
41
+ .catch(() => undefined);
42
+ }
43
+ class HostFileStore {
44
+ async stat(path) {
45
+ try {
46
+ return toFileStat(await fsStat(path));
47
+ }
48
+ catch (error) {
49
+ if (error.code === "ENOENT") {
50
+ return undefined;
51
+ }
52
+ throw error;
53
+ }
54
+ }
55
+ async readBytes(path, opts = {}) {
56
+ throwIfAborted(opts.signal);
57
+ const handle = await open(path, "r");
58
+ try {
59
+ const stat = toFileStat(await handle.stat());
60
+ const start = Math.max(0, opts.start ?? 0);
61
+ const maxBytes = opts.maxBytes ?? Number.POSITIVE_INFINITY;
62
+ const available = Math.max(0, stat.size - start);
63
+ const toRead = Math.min(available, maxBytes);
64
+ const buffer = Buffer.alloc(toRead);
65
+ let readTotal = 0;
66
+ while (readTotal < toRead) {
67
+ throwIfAborted(opts.signal);
68
+ const { bytesRead } = await handle.read(buffer, readTotal, toRead - readTotal, start + readTotal);
69
+ if (bytesRead === 0) {
70
+ break;
71
+ }
72
+ readTotal += bytesRead;
73
+ }
74
+ const data = readTotal === buffer.length ? buffer : buffer.subarray(0, readTotal);
75
+ return { data, eof: start + readTotal >= stat.size, stat };
76
+ }
77
+ finally {
78
+ await handle.close();
79
+ }
80
+ }
81
+ openRead(path, opts = {}) {
82
+ return createReadStream(path, { start: opts.start, end: opts.end });
83
+ }
84
+ async writeAtomic(path, data, opts = {}) {
85
+ throwIfAborted(opts.signal);
86
+ if (opts.createParentDir) {
87
+ await mkdir(dirname(path), { recursive: true });
88
+ }
89
+ await writeFileAtomically(path, data, { preserveMode: opts.preserveMode });
90
+ }
91
+ async replaceViaTemp(path, produce, opts = {}) {
92
+ throwIfAborted(opts.signal);
93
+ const dir = dirname(path);
94
+ await mkdir(dir, { recursive: true });
95
+ const tempPath = createAtomicTempPath(path);
96
+ try {
97
+ const handle = await open(tempPath, "w");
98
+ try {
99
+ if (opts.preserveMode) {
100
+ const existing = await this.stat(path);
101
+ if (existing) {
102
+ await handle.chmod(existing.mode & 0o777);
103
+ }
104
+ }
105
+ // `handle.createWriteStream()` closes the underlying `FileHandle` itself once the stream
106
+ // ends, so a subsequent `handle.sync()`/`handle.close()` on the same handle would throw
107
+ // "file closed". Write through `handle.write()` directly instead, keeping the handle
108
+ // under our own control until the explicit `sync()` + `close()` below.
109
+ const out = new Writable({
110
+ write(chunk, _encoding, callback) {
111
+ handle.write(chunk).then(() => callback(), (error) => callback(error instanceof Error ? error : new Error(String(error))));
112
+ },
113
+ });
114
+ await produce(out);
115
+ await new Promise((resolve, reject) => {
116
+ out.once("error", reject);
117
+ out.end(() => resolve());
118
+ });
119
+ await handle.sync();
120
+ }
121
+ finally {
122
+ await handle.close();
123
+ }
124
+ await rename(tempPath, path);
125
+ await fsyncDir(dir);
126
+ }
127
+ catch (error) {
128
+ await unlink(tempPath).catch(() => undefined);
129
+ throw error;
130
+ }
131
+ }
132
+ async listDirectory(path, opts) {
133
+ const results = [];
134
+ const walk = async (currentDir, relPrefix, depth) => {
135
+ const entries = await readdir(currentDir, { withFileTypes: true });
136
+ for (const entry of entries) {
137
+ const relativePath = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
138
+ const isDirectory = entry.isDirectory();
139
+ results.push({ name: entry.name, relativePath, isDirectory });
140
+ if (isDirectory && depth < opts.maxDepth) {
141
+ await walk(join(currentDir, entry.name), relativePath, depth + 1);
142
+ }
143
+ }
144
+ };
145
+ await walk(path, "", 1);
146
+ return results;
147
+ }
148
+ async walkFiles(path, opts) {
149
+ const files = [];
150
+ let truncated = false;
151
+ const walk = async (currentDir, relPrefix) => {
152
+ if (truncated)
153
+ return;
154
+ throwIfAborted(opts.signal);
155
+ let entries;
156
+ try {
157
+ entries = await readdir(currentDir, { withFileTypes: true });
158
+ }
159
+ catch {
160
+ // An unreadable directory (permission, or removed mid-walk) is skipped rather than
161
+ // failing the whole discovery -- one bad subtree must not blank out every other match.
162
+ return;
163
+ }
164
+ for (const entry of entries) {
165
+ if (truncated)
166
+ return;
167
+ const relativePath = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
168
+ if (entry.isDirectory()) {
169
+ if (opts.prune?.(entry.name))
170
+ continue;
171
+ await walk(join(currentDir, entry.name), relativePath);
172
+ continue;
173
+ }
174
+ // Symlinks (to files or directories) report false from both checks and are skipped: a
175
+ // glob result must never resolve outside the guarded root through a link the walk never
176
+ // asked permission to follow.
177
+ if (!entry.isFile())
178
+ continue;
179
+ files.push(relativePath);
180
+ if (files.length >= opts.maxEntries) {
181
+ truncated = true;
182
+ return;
183
+ }
184
+ }
185
+ };
186
+ await walk(path, "");
187
+ return { files, truncated };
188
+ }
189
+ }
package/dist/main.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { runAuth } from "./models/auth-cli.js";
3
- import { isBootstrapExitError } from "./runtime/app-home.js";
3
+ import { formatCliCommandsHelp, isBootstrapExitError } from "./runtime/app-home.js";
4
4
  import { bootstrap } from "./runtime/bootstrap.js";
5
5
  import { runTui } from "./tui/cli.js";
6
6
  function handleError(error) {
@@ -31,9 +31,8 @@ else if (command === undefined || command === "run" || command.startsWith("-"))
31
31
  }
32
32
  else {
33
33
  console.error(`Unknown command: ${command}`);
34
- console.error("Usage: pipiclaw [run] [options] Run the DingTalk daemon (default)");
35
- console.error(" pipiclaw tui [options] [prompt] Chat with the agent in the terminal");
36
- console.error(" pipiclaw auth status|login|logout Manage provider credentials");
34
+ for (const line of formatCliCommandsHelp("pipiclaw"))
35
+ console.error(line);
37
36
  console.error("Run `pipiclaw --help` for options.");
38
37
  process.exit(1);
39
38
  }
@@ -1,6 +1,7 @@
1
- import { createHash } from "node:crypto";
1
+ import { renderSubcommandUsage } from "../agent/commands.js";
2
+ import { capReply } from "../agent/reply-limits.js";
2
3
  import { readOptionalTextFile } from "../shared/fs-utils.js";
3
- import { localDayKey } from "../shared/local-time.js";
4
+ import { localDayKey, parseLocalTime } from "../shared/local-time.js";
4
5
  import { clipText } from "../shared/text-utils.js";
5
6
  import { getChannelMemoryPath, parseChannelMemoryEntries, readChannelMemory } from "./files.js";
6
7
  import { syncMemoryMetadata } from "./metadata.js";
@@ -11,33 +12,41 @@ async function reconcile(options) {
11
12
  const metadata = await syncMemoryMetadata(options.channelDir, entries);
12
13
  return { entries, metadata };
13
14
  }
14
- async function readPendingSuggestions(channelDir) {
15
+ /**
16
+ * Flattens `memory-review.jsonl` action entries for `/memory recent` and the `status` summary —
17
+ * the only consumers of the review log's write history. `user-forget` actions carry `entryId`
18
+ * instead of `target`/`action`; both shapes are tolerated here.
19
+ */
20
+ async function readRecentMemoryActions(channelDir, sinceMs) {
15
21
  const raw = await readOptionalTextFile(getMemoryReviewLogPath(channelDir));
16
- const suggestions = [];
22
+ const actions = [];
17
23
  for (const line of raw.split("\n")) {
18
24
  if (!line.trim())
19
25
  continue;
20
26
  try {
21
27
  const entry = JSON.parse(line);
22
- for (const value of entry.suggestions ?? []) {
23
- const id = `p-${createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 8)}`;
24
- suggestions.push({ id, timestamp: entry.timestamp, value });
28
+ const entryMs = entry.timestamp ? (parseLocalTime(entry.timestamp) ?? 0) : 0;
29
+ if (entryMs < sinceMs)
30
+ continue;
31
+ for (const value of entry.actions ?? []) {
32
+ if (value && typeof value === "object") {
33
+ actions.push({ timestamp: entry.timestamp, reason: entry.reason, ...value });
34
+ }
25
35
  }
26
36
  }
27
37
  catch {
28
38
  // A torn audit line should not break the management surface.
29
39
  }
30
40
  }
31
- return suggestions.slice(-50);
41
+ return actions;
32
42
  }
33
43
  function renderUsage() {
34
- return "Use `/memory status`, `/memory list`, `/memory show <entry-id>`, or `/memory pending`.";
44
+ return renderSubcommandUsage("memory");
35
45
  }
36
46
  export async function handleMemoryCommand(options) {
37
47
  const [action = "status", argument] = options.args.trim().split(/\s+/, 2);
38
48
  const { entries, metadata } = await reconcile(options);
39
49
  if (action === "status") {
40
- const pending = await readPendingSuggestions(options.channelDir);
41
50
  const tombstones = await readMemoryTombstones(options.channelDir);
42
51
  const records = Object.values(metadata.entries);
43
52
  const active = records.filter((entry) => entry.status === "active");
@@ -49,70 +58,102 @@ export async function handleMemoryCommand(options) {
49
58
  const sinceDay = localDayKey(since);
50
59
  const recalls30d = active.reduce((sum, entry) => sum +
51
60
  Object.entries(entry.recallByDay ?? {}).reduce((entrySum, [day, count]) => entrySum + (day >= sinceDay ? count : 0), 0), 0);
61
+ const last7d = new Date();
62
+ last7d.setDate(last7d.getDate() - 7);
63
+ const recent = await readRecentMemoryActions(options.channelDir, last7d.getTime());
64
+ const written = recent
65
+ .filter((item) => item.target === "MEMORY.md" && item.action === "append")
66
+ .reduce((sum, item) => sum + (item.entries ?? 0), 0);
67
+ const dropped = recent.reduce((sum, item) => {
68
+ if (item.entryId)
69
+ return sum + 1;
70
+ if (item.target === "MEMORY.md" && item.action === "rewrite")
71
+ return sum + (item.droppedEntryIds?.length ?? 0);
72
+ return sum;
73
+ }, 0);
74
+ const expired = recent
75
+ .filter((item) => item.target === "MEMORY.md" && item.action === "expire")
76
+ .reduce((sum, item) => sum + (item.entries ?? 0), 0);
52
77
  const lastFailure = (await readOptionalTextFile(getMemoryReviewLogPath(options.channelDir)))
53
78
  .split("\n")
54
79
  .reverse()
55
80
  .find((line) => line.includes('"error"'));
56
81
  return [
57
- "# Memory Status",
82
+ "**记忆状态**",
58
83
  "",
59
- `- Active entries: \`${entries.length}\``,
60
- `- Metadata records: \`${records.length}\``,
61
- `- Probationary: \`${probationary.length}\`${probationary.length > 0 ? ` (earliest expiry \`${probationary[0].probationUntil}\`)` : ""}`,
62
- `- Pending suggestions: \`${pending.length}\``,
63
- `- Tombstones: \`${tombstones.length}\``,
64
- `- Total recalls: \`${active.reduce((sum, entry) => sum + entry.recallCount, 0)}\``,
65
- `- Recalls (30d): \`${recalls30d}\``,
66
- `- Query diversity: \`${new Set(active.flatMap((entry) => entry.queryFingerprints)).size}\``,
67
- `- Last recalled: \`${active
84
+ `- 生效条目:\`${entries.length}\``,
85
+ `- 元数据记录:\`${records.length}\``,
86
+ `- 观察期:\`${probationary.length}\`${probationary.length > 0 ? `(最早到期 \`${probationary[0].probationUntil}\`)` : ""}`,
87
+ `- 最近 7 天:+${written} 写入 / -${dropped} 丢弃 / -${expired} 过期`,
88
+ `- 墓碑:\`${tombstones.length}\``,
89
+ `- 累计召回:\`${active.reduce((sum, entry) => sum + entry.recallCount, 0)}\``,
90
+ `- 召回(30 天):\`${recalls30d}\``,
91
+ `- 查询多样性:\`${new Set(active.flatMap((entry) => entry.queryFingerprints)).size}\``,
92
+ `- 最近一次召回:\`${active
68
93
  .map((entry) => entry.lastRecalledAt)
69
94
  .filter(Boolean)
70
95
  .sort()
71
- .at(-1) ?? "never"}\``,
72
- `- Recent failure: ${lastFailure ? "yes; inspect memory-review.jsonl" : "none"}`,
73
- `- Active file: \`${getChannelMemoryPath(options.channelDir)}\``,
96
+ .at(-1) ?? "从未"}\``,
97
+ `- 近期失败:${lastFailure ? "有,查看 memory-review.jsonl" : "无"}`,
98
+ `- 生效文件:\`${getChannelMemoryPath(options.channelDir)}\``,
74
99
  ].join("\n");
75
100
  }
76
101
  if (action === "list") {
77
102
  if (entries.length === 0)
78
- return "# Memory Entries\n\nNo active channel memory entries.";
103
+ return "**记忆条目**\n\n暂无生效的频道记忆条目。";
79
104
  const visible = entries.slice(0, 50);
80
105
  const lines = visible.map((entry) => {
81
106
  const record = metadata.entries[entry.id];
82
- const probation = record?.probationUntil ? ` (probation until \`${record.probationUntil}\`)` : "";
107
+ const probation = record?.probationUntil ? `(观察期至 \`${record.probationUntil}\`)` : "";
83
108
  return `- \`${entry.id}\` [${record?.kind ?? "fact"}]${probation} ${clipText(entry.content, 180, { headRatio: 1 })}`;
84
109
  });
85
110
  if (entries.length > visible.length) {
86
- lines.push(`- ${entries.length - visible.length} more omitted; use \`/memory show <entry-id>\` after narrowing the file.`);
111
+ lines.push(`- 另有 ${entries.length - visible.length} 条已省略;缩小范围后用 \`/memory show <entry-id>\` 查看。`);
87
112
  }
88
- return `# Memory Entries\n\n${lines.join("\n")}`;
113
+ return capReply(`**记忆条目**\n\n${lines.join("\n")}`, {
114
+ nextStepHint: "用 `/memory show <entry-id>` 查看单条记忆",
115
+ }).text;
89
116
  }
90
117
  if (action === "show") {
91
118
  if (!argument)
92
- return `Missing entry id. ${renderUsage()}`;
119
+ return `缺少 entry id。${renderUsage()}`;
93
120
  const entry = entries.find((candidate) => candidate.id === argument);
94
121
  const record = metadata.entries[argument];
95
122
  if (!entry && !record)
96
- return `Memory entry \`${argument}\` was not found. Use \`/memory list\` to see ids.`;
123
+ return `未找到记忆条目 \`${argument}\`。用 \`/memory list\` 查看 id。`;
97
124
  return [
98
- `# Memory ${argument}`,
125
+ `**记忆 ${argument}**`,
99
126
  "",
100
- entry?.content ?? "(not active in MEMORY.md)",
127
+ entry?.content ?? "(未在 MEMORY.md 中生效)",
101
128
  "",
102
129
  "```json",
103
130
  JSON.stringify(record ?? { id: argument, status: "unknown" }, null, 2),
104
131
  "```",
105
132
  ].join("\n");
106
133
  }
107
- if (action === "pending") {
108
- const pending = await readPendingSuggestions(options.channelDir);
109
- if (pending.length === 0)
110
- return "# Pending Memory Suggestions\n\nNo pending suggestions.";
134
+ if (action === "recent") {
135
+ const last7d = new Date();
136
+ last7d.setDate(last7d.getDate() - 7);
137
+ const recent = (await readRecentMemoryActions(options.channelDir, last7d.getTime())).slice(-30).reverse();
138
+ if (recent.length === 0)
139
+ return "**近期记忆活动**\n\n最近 7 天没有记忆活动。";
111
140
  return [
112
- "# Pending Memory Suggestions",
141
+ "**近期记忆活动**",
113
142
  "",
114
- ...pending.map((item) => `- \`${item.id}\`${item.timestamp ? ` (${item.timestamp})` : ""}: ${clipText(JSON.stringify(item.value), 300)}`),
143
+ ...recent.map((item) => {
144
+ const when = item.timestamp ? `(${item.timestamp})` : "";
145
+ if (item.entryId)
146
+ return `- ${when}遗忘 \`${item.entryId}\`(${item.reason})`;
147
+ const detail = item.action === "append"
148
+ ? `新增 ${item.entries ?? 0} 条`
149
+ : item.action === "rewrite"
150
+ ? `重写${item.droppedEntryIds?.length ? `(丢弃 ${item.droppedEntryIds.join(", ")})` : ""}`
151
+ : item.action === "expire"
152
+ ? `过期 ${item.entries ?? 0} 条`
153
+ : (item.action ?? "unknown");
154
+ return `- ${when}${item.target ?? "?"}:${detail}(${item.reason})`;
155
+ }),
115
156
  ].join("\n");
116
157
  }
117
- return `Unknown memory command \`${action}\`. ${renderUsage()}`;
158
+ return `未知的 memory 命令 \`${action}\`。${renderUsage()}`;
118
159
  }
@@ -46,5 +46,9 @@ export type MemoryCleanupShrinkGuard = Pick<PipiclawMemoryMaintenanceSettings, "
46
46
  export declare class MemoryCleanupRejectedError extends Error {
47
47
  constructor(reason: string);
48
48
  }
49
- export declare function cleanupChannelMemory(options: ConsolidationRunOptions, currentMemory: string, guard?: MemoryCleanupShrinkGuard): Promise<boolean>;
49
+ export interface MemoryCleanupResult {
50
+ rewritten: boolean;
51
+ droppedEntryIds: string[];
52
+ }
53
+ export declare function cleanupChannelMemory(options: ConsolidationRunOptions, currentMemory: string, guard?: MemoryCleanupShrinkGuard): Promise<MemoryCleanupResult>;
50
54
  export declare function foldChannelHistory(options: ConsolidationRunOptions, currentHistory: string): Promise<boolean>;
@@ -1,12 +1,14 @@
1
1
  import { getLatestCompactionEntry } from "@earendil-works/pi-coding-agent";
2
2
  import { formatLocalTime } from "../shared/local-time.js";
3
3
  import { splitH2Sections } from "../shared/markdown-sections.js";
4
+ import { clipText } from "../shared/text-utils.js";
4
5
  import { runMemoryExtraction, toMemoryOp } from "./extraction.js";
5
6
  import { appendChannelHistoryArchive, appendChannelHistoryBlock, applyChannelMemoryOps, parseChannelMemoryEntries, rewriteChannelHistory, rewriteChannelMemory, } from "./files.js";
7
+ import { readMemoryMetadata } from "./metadata.js";
6
8
  import { classifyMemoryWrite, DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE, MAX_PROBATION_WRITES_PER_RUN, } from "./promotion.js";
7
9
  import { MEMORY_INPUT_SAFETY_RULES } from "./prompt-safety.js";
8
10
  import { runSidecarTask } from "./sidecar-worker.js";
9
- import { sanitizeMessagesForMemory } from "./transcript.js";
11
+ import { hasMeaningfulExchange, sanitizeMessagesForMemory } from "./transcript.js";
10
12
  const INLINE_TRANSCRIPT_MAX_CHARS = 28_000;
11
13
  const MEMORY_CLEANUP_LENGTH_THRESHOLD = 5_000;
12
14
  const MEMORY_UPDATE_BLOCK_THRESHOLD = 4;
@@ -15,6 +17,7 @@ const HISTORY_BLOCK_THRESHOLD = 5;
15
17
  const HISTORY_RECENT_BLOCKS_TO_KEEP = 3;
16
18
  const INLINE_CONSOLIDATION_TIMEOUT_MS = 20_000;
17
19
  const MEMORY_CLEANUP_TIMEOUT_MS = 120_000;
20
+ const MEMORY_CLEANUP_INPUT_MAX_CHARS = 24_000;
18
21
  const HISTORY_FOLDING_TIMEOUT_MS = 120_000;
19
22
  const MEMORY_CLEANUP_SYSTEM_PROMPT = `You are rewriting a Pipiclaw channel MEMORY.md file.
20
23
 
@@ -70,30 +73,6 @@ function entriesAfterLatestCompactionBoundary(entries) {
70
73
  function extractMessagesFromSessionEntries(entries) {
71
74
  return entries.filter(isMessage).map((entry) => entry.message);
72
75
  }
73
- function hasMeaningfulMessages(messages) {
74
- let meaningfulCount = 0;
75
- for (const message of messages) {
76
- if (message.role === "user") {
77
- const text = typeof message.content === "string"
78
- ? message.content
79
- : message.content.map((part) => (part.type === "text" ? part.text : "[image]")).join("\n");
80
- if (text.trim())
81
- meaningfulCount++;
82
- }
83
- else if (message.role === "assistant") {
84
- const text = message.content
85
- .filter((part) => part.type === "text")
86
- .map((part) => part.text)
87
- .join("\n");
88
- if (text.trim())
89
- meaningfulCount++;
90
- }
91
- if (meaningfulCount >= 2) {
92
- return true;
93
- }
94
- }
95
- return false;
96
- }
97
76
  function countMatchingSectionHeadings(content, prefix) {
98
77
  return splitH2Sections(content).filter((section) => section.heading.startsWith(prefix)).length;
99
78
  }
@@ -132,7 +111,7 @@ export async function runInlineConsolidation(options) {
132
111
  const sourceEntries = options.sourceWindow?.entries ?? entriesAfterLatestCompactionBoundary(options.sessionEntries ?? []);
133
112
  const relevantMessages = options.sourceWindow?.messages ??
134
113
  (sourceEntries.length > 0 ? extractMessagesFromSessionEntries(sourceEntries) : options.messages);
135
- if (!hasMeaningfulMessages(sanitizeMessagesForMemory(relevantMessages))) {
114
+ if (!hasMeaningfulExchange(sanitizeMessagesForMemory(relevantMessages))) {
136
115
  return {
137
116
  skipped: true,
138
117
  appendedMemoryEntries: 0,
@@ -182,8 +161,7 @@ export async function runInlineConsolidation(options) {
182
161
  const acceptedProbationary = probationaryCandidates.slice(0, MAX_PROBATION_WRITES_PER_RUN);
183
162
  rejectedMemoryOps.push(...probationaryCandidates.slice(MAX_PROBATION_WRITES_PER_RUN));
184
163
  let appliedMemoryOps = 0;
185
- if ((durableCandidates.length > 0 || acceptedProbationary.length > 0) &&
186
- !options.sourceWindow?.hasExternalToolContent) {
164
+ if (durableCandidates.length > 0 || acceptedProbationary.length > 0) {
187
165
  const sourceEntryIds = options.sourceWindow?.entries.map((entry) => entry.id) ?? [];
188
166
  const ops = [
189
167
  ...durableCandidates.map((candidate) => toMemoryOp(candidate, { sourceEntryIds, correlationId }, "durable")),
@@ -223,14 +201,17 @@ function isCleanupResultTooSmall(currentMemory, nextMemory, guard) {
223
201
  const afterEntries = parseChannelMemoryEntries(after).length;
224
202
  if (beforeEntries > 0 && afterEntries === 0)
225
203
  return true;
204
+ // Entry-count guard applies at every file size. The char threshold below exists so a tiny
205
+ // file is not judged on byte ratio, but "four short Update blocks" is exactly the shape
206
+ // cleanup fires on and it sits under that threshold — letting the char escape short-circuit
207
+ // the entry guard left the most common cleanup input completely unprotected.
208
+ if (beforeEntries >= 4 && afterEntries * 2 < beforeEntries)
209
+ return true;
226
210
  if (before.length < Math.max(0, guard.cleanupShrinkGuardMinChars))
227
211
  return false;
228
- if (after.length < before.length * Math.max(0, Math.min(1, guard.cleanupShrinkGuardMinRatio))) {
229
- return true;
230
- }
231
- return beforeEntries > 0 && afterEntries * 2 < beforeEntries;
212
+ return after.length < before.length * Math.max(0, Math.min(1, guard.cleanupShrinkGuardMinRatio));
232
213
  }
233
- function validateCleanupSchema(currentMemory, nextMemory) {
214
+ function validateCleanupSchema(currentMemory, nextMemory, mustKeepIds) {
234
215
  if (!/^# Channel Memory(?:\s|$)/.test(nextMemory.trimStart())) {
235
216
  return 'cleanup output must start with "# Channel Memory"';
236
217
  }
@@ -244,24 +225,40 @@ function validateCleanupSchema(currentMemory, nextMemory) {
244
225
  return `cleanup output duplicated entry id ${entry.id}`;
245
226
  ids.add(entry.id);
246
227
  }
228
+ const missing = mustKeepIds.filter((id) => !ids.has(id));
229
+ if (missing.length > 0)
230
+ return `cleanup output dropped user-saved entries: ${missing.join(", ")}`;
247
231
  return null;
248
232
  }
249
233
  export async function cleanupChannelMemory(options, currentMemory, guard) {
250
234
  if (!shouldCleanupChannelMemory(currentMemory)) {
251
- return false;
235
+ return { rewritten: false, droppedEntryIds: [] };
252
236
  }
253
- const prompt = `Current MEMORY.md:
254
- ${currentMemory}`;
237
+ const metadata = await readMemoryMetadata(options.channelDir);
238
+ const beforeEntries = parseChannelMemoryEntries(currentMemory);
239
+ const mustKeepIds = beforeEntries
240
+ .map((entry) => entry.id)
241
+ .filter((id) => metadata.entries[id]?.sourceType === "user");
242
+ const prompt = [
243
+ mustKeepIds.length > 0
244
+ ? `These entries were saved on the user's explicit instruction and MUST appear verbatim in the output: ${mustKeepIds.join(", ")}`
245
+ : "",
246
+ `Current MEMORY.md:\n${clipText(currentMemory, MEMORY_CLEANUP_INPUT_MAX_CHARS, { headRatio: 0.5 })}`,
247
+ ]
248
+ .filter(Boolean)
249
+ .join("\n\n");
255
250
  const nextMemory = await runWorkerPrompt("memory-cleanup", options.model, options.resolveApiKey, MEMORY_CLEANUP_SYSTEM_PROMPT, prompt, MEMORY_CLEANUP_TIMEOUT_MS, usageContextFor(options.channelId, options.usageCorrelationId));
256
- const schemaError = validateCleanupSchema(currentMemory, nextMemory);
251
+ const schemaError = validateCleanupSchema(currentMemory, nextMemory, mustKeepIds);
257
252
  if (schemaError) {
258
253
  throw new MemoryCleanupRejectedError(`${schemaError}. Retry cleanup while preserving the MEMORY.md schema and ids.`);
259
254
  }
260
255
  if (guard && isCleanupResultTooSmall(currentMemory, nextMemory, guard)) {
261
256
  throw new MemoryCleanupRejectedError("cleanup result shrank below the configured guard threshold");
262
257
  }
258
+ const afterIds = new Set(parseChannelMemoryEntries(nextMemory).map((entry) => entry.id));
259
+ const droppedEntryIds = beforeEntries.map((entry) => entry.id).filter((id) => !afterIds.has(id));
263
260
  await rewriteChannelMemory(options.channelDir, nextMemory);
264
- return true;
261
+ return { rewritten: true, droppedEntryIds };
265
262
  }
266
263
  export async function foldChannelHistory(options, currentHistory) {
267
264
  if (!shouldFoldChannelHistory(currentHistory)) {
@@ -1,7 +1,7 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import { type MemoryOp } from "./files.js";
4
- import type { MemoryEntryKind } from "./metadata.js";
4
+ import { type MemoryEntryKind } from "./metadata.js";
5
5
  import type { MemoryPromotionCandidate, MemoryWriteTier } from "./promotion.js";
6
6
  export interface MemoryExtractionPromptOptions {
7
7
  includeHistoryBlock: boolean;
@@ -44,4 +44,11 @@ export interface MemoryExtractionRequest extends MemoryExtractionPromptOptions {
44
44
  correlationId?: string;
45
45
  };
46
46
  }
47
+ /**
48
+ * Tool output never reaches this prompt: `sanitizeMessagesForMemory` drops every `toolResult`
49
+ * message before serialization (`transcript.ts`), an invariant pinned by
50
+ * `test/memory-transcript.test.ts` ("drops tool results ... before memory workers see them").
51
+ * That is why no additional untrusted-content filter is applied here — a window-level one used to
52
+ * exist and silently discarded every durable write from any tool-using conversation.
53
+ */
47
54
  export declare function runMemoryExtraction(request: MemoryExtractionRequest): Promise<MemoryExtractionResult>;