@oyasmi/pipiclaw 0.9.2 → 0.9.3-beta.2

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 (178) hide show
  1. package/README.en.md +250 -0
  2. package/README.md +3 -1
  3. package/dist/agent/channel-runner.d.ts +59 -2
  4. package/dist/agent/channel-runner.js +177 -76
  5. package/dist/agent/job-manager.d.ts +76 -21
  6. package/dist/agent/job-manager.js +447 -63
  7. package/dist/agent/maintenance-context.js +4 -5
  8. package/dist/agent/prompt/manifest.d.ts +0 -2
  9. package/dist/agent/prompt/manifest.js +2 -3
  10. package/dist/agent/prompt/sections.js +3 -3
  11. package/dist/agent/session-events.js +4 -8
  12. package/dist/agent/turn-prompt.d.ts +7 -7
  13. package/dist/agent/turn-prompt.js +6 -9
  14. package/dist/agent/types.d.ts +12 -0
  15. package/dist/agent/types.js +1 -0
  16. package/dist/channel/channel-context.d.ts +13 -0
  17. package/dist/channel/channel-context.js +21 -1
  18. package/dist/commands/catalog.js +47 -20
  19. package/dist/memory/commands.d.ts +8 -0
  20. package/dist/memory/commands.js +113 -148
  21. package/dist/memory/index-budget.d.ts +27 -0
  22. package/dist/memory/index-budget.js +99 -0
  23. package/dist/memory/journal.d.ts +20 -0
  24. package/dist/memory/journal.js +78 -0
  25. package/dist/memory/lifecycle.d.ts +9 -15
  26. package/dist/memory/lifecycle.js +55 -145
  27. package/dist/memory/maintenance-gates.d.ts +13 -47
  28. package/dist/memory/maintenance-gates.js +13 -92
  29. package/dist/memory/maintenance-state.d.ts +10 -16
  30. package/dist/memory/maintenance-state.js +12 -59
  31. package/dist/memory/maintenance-tuning.d.ts +7 -27
  32. package/dist/memory/maintenance-tuning.js +11 -28
  33. package/dist/memory/migrate.d.ts +15 -0
  34. package/dist/memory/migrate.js +364 -0
  35. package/dist/memory/reflect-job.d.ts +43 -0
  36. package/dist/memory/reflect-job.js +117 -0
  37. package/dist/memory/reflect.d.ts +52 -0
  38. package/dist/memory/reflect.js +313 -0
  39. package/dist/memory/render.d.ts +19 -0
  40. package/dist/memory/render.js +35 -0
  41. package/dist/memory/review-log.d.ts +2 -1
  42. package/dist/memory/scheduler.d.ts +2 -3
  43. package/dist/memory/scheduler.js +14 -49
  44. package/dist/memory/search.d.ts +35 -0
  45. package/dist/memory/search.js +297 -0
  46. package/dist/memory/session-search.js +1 -1
  47. package/dist/memory/store.d.ts +108 -0
  48. package/dist/memory/store.js +418 -0
  49. package/dist/memory/task-digest.d.ts +2 -2
  50. package/dist/memory/task-digest.js +29 -36
  51. package/dist/memory/tombstones.d.ts +0 -11
  52. package/dist/memory/tombstones.js +6 -37
  53. package/dist/memory/transcript.js +12 -5
  54. package/dist/playbooks/agent-delegation.md +37 -9
  55. package/dist/playbooks/background-jobs.md +1 -1
  56. package/dist/playbooks/event-scheduling.md +6 -2
  57. package/dist/playbooks/memory-and-learning.md +36 -12
  58. package/dist/playbooks/outbound-media.md +1 -1
  59. package/dist/playbooks/runtime-orientation.md +9 -8
  60. package/dist/playbooks/task-loop.md +110 -0
  61. package/dist/runtime/bootstrap.d.ts +3 -3
  62. package/dist/runtime/bootstrap.js +66 -41
  63. package/dist/runtime/events.d.ts +9 -0
  64. package/dist/runtime/events.js +43 -4
  65. package/dist/runtime/task-commands.d.ts +14 -15
  66. package/dist/runtime/task-commands.js +249 -485
  67. package/dist/runtime/task-driver.d.ts +41 -29
  68. package/dist/runtime/task-driver.js +170 -317
  69. package/dist/runtime/task-migration.d.ts +34 -30
  70. package/dist/runtime/task-migration.js +229 -183
  71. package/dist/runtime/task-wake.d.ts +6 -3
  72. package/dist/runtime/task-wake.js +26 -19
  73. package/dist/settings.d.ts +0 -29
  74. package/dist/settings.js +12 -35
  75. package/dist/shared/markdown-sections.d.ts +0 -1
  76. package/dist/shared/markdown-sections.js +0 -3
  77. package/dist/subagents/discovery.d.ts +2 -2
  78. package/dist/subagents/discovery.js +21 -10
  79. package/dist/subagents/external/progress-tail.js +6 -1
  80. package/dist/subagents/external/run.js +1 -0
  81. package/dist/subagents/runs.d.ts +19 -2
  82. package/dist/subagents/runs.js +73 -4
  83. package/dist/subagents/tool.d.ts +10 -8
  84. package/dist/subagents/tool.js +55 -94
  85. package/dist/tasks/brief.d.ts +17 -0
  86. package/dist/tasks/brief.js +57 -0
  87. package/dist/tasks/budget.d.ts +26 -0
  88. package/dist/tasks/budget.js +59 -0
  89. package/dist/tasks/cycle.d.ts +48 -0
  90. package/dist/tasks/cycle.js +94 -0
  91. package/dist/tasks/frontmatter.d.ts +73 -0
  92. package/dist/tasks/frontmatter.js +175 -0
  93. package/dist/tasks/ledger.d.ts +66 -106
  94. package/dist/tasks/ledger.js +90 -546
  95. package/dist/tasks/log.d.ts +88 -0
  96. package/dist/tasks/log.js +97 -0
  97. package/dist/tasks/rounds.d.ts +41 -0
  98. package/dist/tasks/rounds.js +53 -0
  99. package/dist/tasks/session-path.d.ts +9 -0
  100. package/dist/tasks/session-path.js +16 -0
  101. package/dist/tasks/steer.d.ts +8 -0
  102. package/dist/tasks/steer.js +79 -0
  103. package/dist/tasks/store.d.ts +60 -35
  104. package/dist/tasks/store.js +166 -107
  105. package/dist/tasks/ticket.d.ts +102 -0
  106. package/dist/tasks/ticket.js +209 -0
  107. package/dist/tasks/verification.d.ts +47 -0
  108. package/dist/tasks/verification.js +60 -1
  109. package/dist/tools/index.d.ts +13 -4
  110. package/dist/tools/index.js +5 -10
  111. package/dist/tools/memory-manage.d.ts +6 -16
  112. package/dist/tools/memory-manage.js +108 -129
  113. package/dist/tools/presentation.js +2 -1
  114. package/dist/tools/registry.d.ts +11 -2
  115. package/dist/tools/registry.js +17 -6
  116. package/dist/tools/subagent-manage.d.ts +0 -9
  117. package/dist/tools/subagent-manage.js +8 -17
  118. package/dist/tools/task-manage/create.js +2 -2
  119. package/dist/tools/task-manage/lifecycle.d.ts +9 -4
  120. package/dist/tools/task-manage/lifecycle.js +136 -188
  121. package/dist/tools/task-manage/log-view.d.ts +8 -0
  122. package/dist/tools/task-manage/log-view.js +24 -0
  123. package/dist/tools/task-manage/schema.d.ts +38 -14
  124. package/dist/tools/task-manage/schema.js +46 -27
  125. package/dist/tools/task-manage/shared.d.ts +35 -31
  126. package/dist/tools/task-manage/shared.js +130 -141
  127. package/dist/tools/task-manage/step-end.d.ts +11 -0
  128. package/dist/tools/task-manage/step-end.js +134 -0
  129. package/dist/tools/task-manage/types.d.ts +23 -32
  130. package/dist/tools/task-manage.d.ts +4 -3
  131. package/dist/tools/task-manage.js +30 -15
  132. package/dist/tools/tool-details.d.ts +1 -1
  133. package/dist/tui/app.js +0 -2
  134. package/examples/sub-agents/README.md +54 -38
  135. package/examples/sub-agents/builder-hard.md +21 -12
  136. package/examples/sub-agents/builder.md +24 -16
  137. package/examples/sub-agents/explorer.md +17 -15
  138. package/examples/sub-agents/git-committer.md +8 -6
  139. package/examples/sub-agents/planner.md +17 -16
  140. package/examples/sub-agents/reviewer.md +11 -9
  141. package/examples/sub-agents/verifier.md +22 -16
  142. package/examples/sub-agents/worker.md +22 -6
  143. package/package.json +1 -1
  144. package/dist/agent/effect-ledger.d.ts +0 -32
  145. package/dist/agent/effect-ledger.js +0 -89
  146. package/dist/memory/bootstrap.d.ts +0 -17
  147. package/dist/memory/bootstrap.js +0 -120
  148. package/dist/memory/candidates.d.ts +0 -26
  149. package/dist/memory/candidates.js +0 -202
  150. package/dist/memory/consolidation.d.ts +0 -54
  151. package/dist/memory/consolidation.js +0 -292
  152. package/dist/memory/extraction.d.ts +0 -54
  153. package/dist/memory/extraction.js +0 -240
  154. package/dist/memory/files.d.ts +0 -71
  155. package/dist/memory/files.js +0 -419
  156. package/dist/memory/maintenance-jobs.d.ts +0 -41
  157. package/dist/memory/maintenance-jobs.js +0 -265
  158. package/dist/memory/metadata.d.ts +0 -57
  159. package/dist/memory/metadata.js +0 -142
  160. package/dist/memory/probation.d.ts +0 -17
  161. package/dist/memory/probation.js +0 -44
  162. package/dist/memory/promotion.d.ts +0 -38
  163. package/dist/memory/promotion.js +0 -36
  164. package/dist/memory/recall.d.ts +0 -59
  165. package/dist/memory/recall.js +0 -746
  166. package/dist/memory/session.d.ts +0 -24
  167. package/dist/memory/session.js +0 -273
  168. package/dist/playbooks/task-driving.md +0 -92
  169. package/dist/playbooks/task-planning.md +0 -58
  170. package/dist/tasks/control.d.ts +0 -56
  171. package/dist/tasks/control.js +0 -169
  172. package/dist/tasks/transitions.d.ts +0 -16
  173. package/dist/tasks/transitions.js +0 -48
  174. package/dist/tools/task-manage/verification.d.ts +0 -19
  175. package/dist/tools/task-manage/verification.js +0 -91
  176. package/examples/sub-agents/documenter.md +0 -50
  177. package/examples/sub-agents/log-sifter.md +0 -47
  178. package/examples/sub-agents/scout.md +0 -34
@@ -0,0 +1,418 @@
1
+ import { createHash } from "node:crypto";
2
+ import { appendFile, mkdir, readdir, readFile, rm, stat } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { writeFileAtomically } from "../shared/atomic-file.js";
5
+ import { readOptionalTextFile } from "../shared/fs-utils.js";
6
+ import { localDayKey } from "../shared/local-time.js";
7
+ import { containsSecret } from "./secret-redaction.js";
8
+ import { hashMemoryContent } from "./tombstones.js";
9
+ const MEMORY_TYPES = ["user", "feedback", "project", "reference"];
10
+ const MEMORY_SOURCES = ["user", "agent", "migrated"];
11
+ /** Group order in the generated index; also the fallback ordering used by the budget tiering. */
12
+ export const MEMORY_TYPE_ORDER = MEMORY_TYPES;
13
+ const NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
14
+ const MAX_NAME_LENGTH = 60;
15
+ const MAX_SLUG_WORDS = 6;
16
+ export function getChannelMemoryDir(channelDir) {
17
+ return join(channelDir, "memory");
18
+ }
19
+ export function getChannelMemoryIndexPath(channelDir) {
20
+ return join(channelDir, "MEMORY.md");
21
+ }
22
+ export function getMemoryEntryPath(channelDir, name) {
23
+ return join(getChannelMemoryDir(channelDir), `${name}.md`);
24
+ }
25
+ function getTombstonesPath(channelDir) {
26
+ return join(getChannelMemoryDir(channelDir), ".tombstones.jsonl");
27
+ }
28
+ // -------------------------------------------------------------------------------------------------
29
+ // Names
30
+ // -------------------------------------------------------------------------------------------------
31
+ export function isValidMemoryName(name) {
32
+ return name.length > 0 && name.length <= MAX_NAME_LENGTH && NAME_PATTERN.test(name);
33
+ }
34
+ function shortHash(seed) {
35
+ return createHash("sha1").update(seed).digest("hex").slice(0, 6);
36
+ }
37
+ /** Slugify free text into a memory name; falls back to `m-<hash6>` when nothing usable remains. */
38
+ export function slugifyMemoryName(text) {
39
+ const words = text
40
+ .toLowerCase()
41
+ .replace(/<!--[\s\S]*?-->/g, " ")
42
+ .normalize("NFKD")
43
+ .replace(/[^a-z0-9\s-]/g, " ")
44
+ .split(/[\s-]+/)
45
+ .filter(Boolean)
46
+ .slice(0, MAX_SLUG_WORDS);
47
+ const slug = words.join("-").slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
48
+ return isValidMemoryName(slug) ? slug : `m-${shortHash(text)}`;
49
+ }
50
+ /** Return a name not already taken by `existing`, appending `-2`, `-3`, … when needed. */
51
+ export function dedupeMemoryName(name, existing) {
52
+ const taken = new Set(existing);
53
+ if (!taken.has(name)) {
54
+ return name;
55
+ }
56
+ for (let suffix = 2;; suffix++) {
57
+ const candidate = `${name}-${suffix}`.slice(0, MAX_NAME_LENGTH);
58
+ if (!taken.has(candidate)) {
59
+ return candidate;
60
+ }
61
+ }
62
+ }
63
+ // -------------------------------------------------------------------------------------------------
64
+ // Frontmatter parse / serialize
65
+ // -------------------------------------------------------------------------------------------------
66
+ function collapseToLine(text) {
67
+ return text.replace(/\s+/g, " ").trim();
68
+ }
69
+ function firstParagraph(text) {
70
+ const block = text
71
+ .replace(/\r/g, "")
72
+ .split(/\n\s*\n/)
73
+ .map((part) => part.trim())
74
+ .find((part) => part.length > 0);
75
+ return block ? collapseToLine(block) : "";
76
+ }
77
+ function parseRawFrontmatter(raw) {
78
+ const normalized = raw.replace(/\r/g, "");
79
+ const fields = new Map();
80
+ if (!normalized.startsWith("---\n")) {
81
+ return { fields, body: normalized.trim(), hadFrontmatter: false };
82
+ }
83
+ const end = normalized.indexOf("\n---", 4);
84
+ if (end === -1) {
85
+ return { fields, body: normalized.trim(), hadFrontmatter: false };
86
+ }
87
+ const header = normalized.slice(4, end);
88
+ for (const line of header.split("\n")) {
89
+ const match = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/.exec(line.trim());
90
+ if (match) {
91
+ fields.set(match[1].toLowerCase(), match[2].trim().replace(/^["']|["']$/g, ""));
92
+ }
93
+ }
94
+ const afterEnd = normalized.indexOf("\n", end + 1);
95
+ const body = afterEnd === -1 ? "" : normalized.slice(afterEnd + 1).trim();
96
+ return { fields, body, hadFrontmatter: true };
97
+ }
98
+ function coerceType(value) {
99
+ return value && MEMORY_TYPES.includes(value) ? value : undefined;
100
+ }
101
+ function coerceSource(value) {
102
+ return value && MEMORY_SOURCES.includes(value) ? value : undefined;
103
+ }
104
+ /** Parse one memory file. `name` (from the file name) always wins over frontmatter `name`. */
105
+ export function parseMemoryFile(name, raw, fallbackDate) {
106
+ const { fields, body, hadFrontmatter } = parseRawFrontmatter(raw);
107
+ const type = coerceType(fields.get("type"));
108
+ const source = coerceSource(fields.get("source"));
109
+ const fmDescription = fields.get("description");
110
+ const description = collapseToLine(fmDescription || firstParagraph(hadFrontmatter ? body : raw));
111
+ const created = fields.get("created") || fallbackDate;
112
+ const updated = fields.get("updated") || created;
113
+ const expires = fields.get("expires") || undefined;
114
+ // When frontmatter carried no description, the first paragraph became the description, so it
115
+ // must not be repeated in the body.
116
+ const effectiveBody = fmDescription ? body : stripFirstParagraph(hadFrontmatter ? body : raw);
117
+ const malformed = !hadFrontmatter || !fmDescription || !type || !source || !fields.get("created");
118
+ return {
119
+ name,
120
+ description,
121
+ type: type ?? "project",
122
+ source: source ?? "migrated",
123
+ created,
124
+ updated,
125
+ expires,
126
+ body: effectiveBody,
127
+ malformed,
128
+ };
129
+ }
130
+ function stripFirstParagraph(text) {
131
+ const normalized = text.replace(/\r/g, "").trim();
132
+ const parts = normalized.split(/\n\s*\n/);
133
+ return parts.slice(1).join("\n\n").trim();
134
+ }
135
+ export function serializeMemoryEntry(entry) {
136
+ const lines = [
137
+ "---",
138
+ `name: ${entry.name}`,
139
+ `description: ${collapseToLine(entry.description)}`,
140
+ `type: ${entry.type}`,
141
+ `source: ${entry.source}`,
142
+ `created: ${entry.created}`,
143
+ `updated: ${entry.updated}`,
144
+ ];
145
+ if (entry.expires) {
146
+ lines.push(`expires: ${entry.expires}`);
147
+ }
148
+ lines.push("---", "");
149
+ const body = entry.body.trim();
150
+ return `${lines.join("\n")}\n${body ? `${body}\n` : ""}`;
151
+ }
152
+ // -------------------------------------------------------------------------------------------------
153
+ // Listing (with per-file mtime cache)
154
+ // -------------------------------------------------------------------------------------------------
155
+ const fileCache = new Map();
156
+ /** Test seam: drop the parse cache so a fixture rewritten in place is re-read. */
157
+ export function clearMemoryStoreCache() {
158
+ fileCache.clear();
159
+ }
160
+ export async function listMemoryEntries(channelDir) {
161
+ const dir = getChannelMemoryDir(channelDir);
162
+ let names;
163
+ try {
164
+ names = await readdir(dir);
165
+ }
166
+ catch (error) {
167
+ if (error.code === "ENOENT") {
168
+ return [];
169
+ }
170
+ throw error;
171
+ }
172
+ const entries = [];
173
+ for (const fileName of names) {
174
+ if (!fileName.endsWith(".md") || fileName.startsWith(".")) {
175
+ continue;
176
+ }
177
+ const path = join(dir, fileName);
178
+ let info;
179
+ try {
180
+ info = await stat(path);
181
+ }
182
+ catch {
183
+ continue;
184
+ }
185
+ if (!info.isFile()) {
186
+ continue;
187
+ }
188
+ const name = fileName.slice(0, -3);
189
+ const cached = fileCache.get(path);
190
+ if (cached && cached.mtimeMs === info.mtimeMs) {
191
+ entries.push(cached.entry);
192
+ continue;
193
+ }
194
+ const raw = await readFile(path, "utf-8");
195
+ const entry = parseMemoryFile(name, raw, localDayKey(info.mtime));
196
+ fileCache.set(path, { mtimeMs: info.mtimeMs, entry });
197
+ entries.push(entry);
198
+ }
199
+ entries.sort((a, b) => a.name.localeCompare(b.name));
200
+ return entries;
201
+ }
202
+ export async function readMemoryEntry(channelDir, name) {
203
+ const path = getMemoryEntryPath(channelDir, name);
204
+ const raw = await readOptionalTextFile(path);
205
+ if (!raw) {
206
+ return undefined;
207
+ }
208
+ let fallback = localDayKey();
209
+ try {
210
+ fallback = localDayKey((await stat(path)).mtime);
211
+ }
212
+ catch {
213
+ /* use today */
214
+ }
215
+ return parseMemoryFile(name, raw, fallback);
216
+ }
217
+ // -------------------------------------------------------------------------------------------------
218
+ // Index generation
219
+ // -------------------------------------------------------------------------------------------------
220
+ export function renderMemoryIndex(entries) {
221
+ const lines = ["# Channel Memory", ""];
222
+ for (const type of MEMORY_TYPE_ORDER) {
223
+ const group = entries.filter((entry) => entry.type === type).sort((a, b) => a.name.localeCompare(b.name));
224
+ if (group.length === 0) {
225
+ continue;
226
+ }
227
+ lines.push(`## ${type}`);
228
+ for (const entry of group) {
229
+ lines.push(renderIndexLine(entry));
230
+ }
231
+ lines.push("");
232
+ }
233
+ if (lines.length === 2) {
234
+ lines.push("_No stored memory in this channel yet._", "");
235
+ }
236
+ return `${lines.join("\n").trimEnd()}\n`;
237
+ }
238
+ export function renderIndexLine(entry) {
239
+ const marker = entry.body.trim() ? " (+)" : "";
240
+ return `- ${entry.name} — ${entry.description}${marker}`;
241
+ }
242
+ export async function rebuildMemoryIndex(channelDir) {
243
+ const entries = await listMemoryEntries(channelDir);
244
+ await writeFileAtomically(getChannelMemoryIndexPath(channelDir), renderMemoryIndex(entries));
245
+ return entries;
246
+ }
247
+ // -------------------------------------------------------------------------------------------------
248
+ // Tombstones
249
+ // -------------------------------------------------------------------------------------------------
250
+ export async function readMemoryTombstoneRecords(channelDir) {
251
+ const raw = await readOptionalTextFile(getTombstonesPath(channelDir));
252
+ if (!raw) {
253
+ return [];
254
+ }
255
+ const records = [];
256
+ for (const line of raw.split("\n")) {
257
+ if (!line.trim()) {
258
+ continue;
259
+ }
260
+ try {
261
+ const value = JSON.parse(line);
262
+ if (value.contentHash) {
263
+ records.push(value);
264
+ }
265
+ }
266
+ catch {
267
+ /* skip malformed line */
268
+ }
269
+ }
270
+ return records;
271
+ }
272
+ export async function appendMemoryTombstoneRecord(channelDir, record) {
273
+ const path = getTombstonesPath(channelDir);
274
+ await mkdir(getChannelMemoryDir(channelDir), { recursive: true });
275
+ await appendFile(path, `${JSON.stringify(record)}\n`, "utf-8");
276
+ }
277
+ export async function isDescriptionTombstoned(channelDir, description) {
278
+ const hash = hashMemoryContent(description);
279
+ return (await readMemoryTombstoneRecords(channelDir)).some((record) => record.contentHash === hash);
280
+ }
281
+ export async function applyMemoryOps(channelDir, ops, options = {}) {
282
+ const today = options.today ?? localDayKey();
283
+ const result = {
284
+ added: [],
285
+ updated: [],
286
+ deleted: [],
287
+ touched: [],
288
+ skippedTombstone: 0,
289
+ skippedSecret: 0,
290
+ missingTarget: 0,
291
+ renamed: [],
292
+ };
293
+ if (ops.length === 0) {
294
+ return result;
295
+ }
296
+ await mkdir(getChannelMemoryDir(channelDir), { recursive: true });
297
+ const existing = await listMemoryEntries(channelDir);
298
+ const byName = new Map(existing.map((entry) => [entry.name, entry]));
299
+ const liveNames = new Set(byName.keys());
300
+ for (const op of ops) {
301
+ if (op.op === "touch") {
302
+ for (const name of op.names) {
303
+ const entry = byName.get(name);
304
+ if (!entry) {
305
+ result.missingTarget++;
306
+ continue;
307
+ }
308
+ if (entry.expires) {
309
+ const next = { ...entry, expires: undefined, updated: today };
310
+ await writeEntryFile(channelDir, next);
311
+ byName.set(name, next);
312
+ }
313
+ result.touched.push(name);
314
+ }
315
+ continue;
316
+ }
317
+ if (op.op === "delete") {
318
+ const entry = byName.get(op.name);
319
+ if (!entry) {
320
+ result.missingTarget++;
321
+ continue;
322
+ }
323
+ await rm(getMemoryEntryPath(channelDir, op.name), { force: true });
324
+ await appendMemoryTombstoneRecord(channelDir, {
325
+ name: op.name,
326
+ contentHash: hashMemoryContent(entry.description),
327
+ deletedAt: today,
328
+ reason: op.reason?.trim() || "deleted",
329
+ });
330
+ byName.delete(op.name);
331
+ liveNames.delete(op.name);
332
+ result.deleted.push(op.name);
333
+ continue;
334
+ }
335
+ if (op.op === "update") {
336
+ const entry = byName.get(op.name);
337
+ if (!entry) {
338
+ result.missingTarget++;
339
+ continue;
340
+ }
341
+ const description = op.description ? collapseToLine(op.description) : entry.description;
342
+ if (containsSecret(description) || (op.details && containsSecret(op.details))) {
343
+ result.skippedSecret++;
344
+ continue;
345
+ }
346
+ const next = {
347
+ ...entry,
348
+ description,
349
+ type: op.type ?? entry.type,
350
+ body: op.details !== undefined ? op.details.trim() : entry.body,
351
+ updated: today,
352
+ expires: op.expires === undefined ? entry.expires : op.expires === null ? undefined : op.expires,
353
+ malformed: false,
354
+ };
355
+ await writeEntryFile(channelDir, next);
356
+ byName.set(op.name, next);
357
+ result.updated.push(op.name);
358
+ continue;
359
+ }
360
+ // add
361
+ const description = collapseToLine(op.description);
362
+ if (!description) {
363
+ continue;
364
+ }
365
+ if (containsSecret(description) || (op.details && containsSecret(op.details))) {
366
+ result.skippedSecret++;
367
+ continue;
368
+ }
369
+ if (await isDescriptionTombstoned(channelDir, description)) {
370
+ result.skippedTombstone++;
371
+ continue;
372
+ }
373
+ const requested = op.name && isValidMemoryName(op.name) ? op.name : slugifyMemoryName(op.name || description);
374
+ const name = dedupeMemoryName(requested, liveNames);
375
+ if (name !== requested) {
376
+ result.renamed.push({ requested, used: name });
377
+ }
378
+ const entry = {
379
+ name,
380
+ description,
381
+ type: op.type ?? "project",
382
+ source: op.source,
383
+ created: today,
384
+ updated: today,
385
+ expires: op.expires === null || op.expires === undefined ? undefined : op.expires,
386
+ body: op.details?.trim() ?? "",
387
+ malformed: false,
388
+ };
389
+ await writeEntryFile(channelDir, entry);
390
+ byName.set(name, entry);
391
+ liveNames.add(name);
392
+ result.added.push(name);
393
+ }
394
+ await rebuildMemoryIndex(channelDir);
395
+ return result;
396
+ }
397
+ async function writeEntryFile(channelDir, entry) {
398
+ await mkdir(getChannelMemoryDir(channelDir), { recursive: true });
399
+ await writeFileAtomically(getMemoryEntryPath(channelDir, entry.name), serializeMemoryEntry(entry));
400
+ }
401
+ /**
402
+ * Spec 050, D6/D8: a probationary entry nobody touched before `expires` is removed —
403
+ * deterministically, before the reflect pass even runs, so a cleanup prompt never spends
404
+ * tokens on an entry about to disappear. No tombstone: probation lapsing means "not needed
405
+ * right now", not "must never be learned again" (037, D8's rationale, carried over unchanged).
406
+ */
407
+ export async function expireProbationaryEntries(channelDir, today = localDayKey()) {
408
+ const entries = await listMemoryEntries(channelDir);
409
+ const expired = entries.filter((entry) => entry.expires && entry.expires < today);
410
+ if (expired.length === 0) {
411
+ return [];
412
+ }
413
+ for (const entry of expired) {
414
+ await rm(getMemoryEntryPath(channelDir, entry.name), { force: true });
415
+ }
416
+ await rebuildMemoryIndex(channelDir);
417
+ return expired.map((entry) => entry.name);
418
+ }
@@ -20,7 +20,7 @@ export interface TaskDigestOptions {
20
20
  }
21
21
  /**
22
22
  * Render the in-flight task agenda, or `""` when there are no live tasks to show.
23
- * Sleeping and disabled tasks stay visible so the model can distinguish dormant work from lost
24
- * work and tell the user which recovery source is needed.
23
+ * Parked and paused tasks stay visible so the model can distinguish dormant work from lost work
24
+ * and tell the user what each one is waiting for.
25
25
  */
26
26
  export declare function buildTaskDigest(options: TaskDigestOptions): Promise<string>;
@@ -1,59 +1,52 @@
1
1
  import { join } from "node:path";
2
+ import { parseLocalTime } from "../shared/local-time.js";
2
3
  import { countPromptUnits } from "../shared/prompt-units.js";
3
4
  import { readActiveTasks } from "../tasks/ledger.js";
5
+ import { describeTicket } from "../tasks/ticket.js";
4
6
  /** Automatic-context share for the in-flight task agenda (spec 026 §5.3). */
5
7
  export const TASK_AGENDA_MAX_UNITS = 600;
6
- function relativeWake(wakeMs, now) {
7
- if (wakeMs === undefined)
8
- return "wake —";
9
- const diffMs = wakeMs - now;
8
+ /** Relative time to a ticket's due/backstop moment, for a compact agenda line. */
9
+ function relativeTime(atMs, now) {
10
+ if (atMs === undefined || !Number.isFinite(atMs))
11
+ return undefined;
12
+ const diffMs = atMs - now;
10
13
  if (diffMs <= 0)
11
- return "wake due";
14
+ return "due";
12
15
  const minutes = Math.round(diffMs / 60000);
13
16
  if (minutes < 60)
14
- return `wake ${minutes}m`;
17
+ return `${minutes}m`;
15
18
  const hours = Math.round(minutes / 60);
16
19
  if (hours < 24)
17
- return `wake ${hours}h`;
18
- return `wake ${Math.round(hours / 24)}d`;
20
+ return `${hours}h`;
21
+ return `${Math.round(hours / 24)}d`;
19
22
  }
20
23
  function renderLine(entry, now) {
21
- const status = entry.frontmatter.readable ? (entry.frontmatter.status ?? "active") : "⚠ unreadable frontmatter";
22
- const parts = [
23
- `${entry.id} — ${entry.title}`,
24
- status,
25
- entry.frontmatter.enabled === false ? "disabled" : "enabled",
26
- relativeWake(entry.wakeMs, now),
27
- ];
28
- const control = entry.frontmatter.control;
29
- if (control) {
30
- if (control.verification.required)
31
- parts.push(`verify required/${control.verification.status}`);
32
- if (control.waitingFor)
33
- parts.push(`waiting for ${control.waitingFor}`);
34
- if (control.stop)
35
- parts.push(`stop ${control.stop.by}: ${control.stop.reason}`);
36
- if (control.deadline)
37
- parts.push(`deadline ${control.deadline}`);
38
- if (control.nextAction)
39
- parts.push(`next ${control.nextAction}`);
24
+ const parts = [`${entry.id} — ${entry.title}`, entry.readable ? entry.fields.state : "⚠ unreadable frontmatter"];
25
+ if (entry.fields.paused)
26
+ parts.push(`paused(${entry.fields.paused.by})`);
27
+ const ticket = entry.fields.ticket;
28
+ if (ticket) {
29
+ const due = relativeTime(entry.dueMs, now);
30
+ const by = relativeTime(parseLocalTime(ticket.by), now);
31
+ parts.push(`${describeTicket(ticket)}${due ? ` · due ${due}` : ""}${by ? ` · 兜底 ${by}` : ""}`);
32
+ }
33
+ const cycle = entry.fields.cycle;
34
+ if (cycle) {
35
+ const cost = cycle.usd > 0 ? ` · $${cycle.usd.toFixed(2)}${cycle.usdEstimated ? "≈" : ""}` : "";
36
+ parts.push(`${cycle.id} · ${cycle.steps} 步 · ${cycle.rounds} 轮${cost}`);
40
37
  }
41
38
  // spec 037, D4: the agenda shows Plan progress and the current step, not the full Plan — the
42
- // complete section is only read from the task file at wake time (task-driver.ts's capsule),
43
- // staying well inside the 600-unit budget this block competes for (spec 025/026).
39
+ // complete section is read from the task file by the loop itself, staying well inside the
40
+ // 600-unit budget this block competes for (spec 025/026).
44
41
  if (entry.plan) {
45
42
  parts.push(`plan ${entry.plan.done}/${entry.plan.total} · @${entry.plan.current?.id ?? "-"}`);
46
43
  }
47
- if (entry.latestNote) {
48
- const note = entry.latestNote.length > 80 ? `${entry.latestNote.slice(0, 79)}…` : entry.latestNote;
49
- parts.push(note);
50
- }
51
44
  return `- ${parts.join(" · ")}`;
52
45
  }
53
46
  /**
54
47
  * Render the in-flight task agenda, or `""` when there are no live tasks to show.
55
- * Sleeping and disabled tasks stay visible so the model can distinguish dormant work from lost
56
- * work and tell the user which recovery source is needed.
48
+ * Parked and paused tasks stay visible so the model can distinguish dormant work from lost work
49
+ * and tell the user what each one is waiting for.
57
50
  */
58
51
  export async function buildTaskDigest(options) {
59
52
  const now = options.now ?? Date.now();
@@ -61,7 +54,7 @@ export async function buildTaskDigest(options) {
61
54
  const all = await readActiveTasks(tasksDir, now);
62
55
  // A legacy terminal file may briefly remain in the active directory while startup migration
63
56
  // is running. It is already non-actionable at the ledger layer and must not enter prompt context.
64
- const agenda = all.filter((entry) => !entry.frontmatter.archiveOutcome);
57
+ const agenda = all.filter((entry) => !entry.fields.outcome);
65
58
  if (agenda.length === 0)
66
59
  return "";
67
60
  const shown = agenda.slice(0, Math.max(1, options.maxTasks));
@@ -1,12 +1 @@
1
- export interface MemoryTombstone {
2
- entryId: string;
3
- contentHash: string;
4
- deletedAt: string;
5
- scope: "channel";
6
- reason: string;
7
- sourceEntryIds?: string[];
8
- }
9
1
  export declare function hashMemoryContent(content: string): string;
10
- export declare function getMemoryTombstonesPath(channelDir: string): string;
11
- export declare function appendMemoryTombstone(channelDir: string, tombstone: MemoryTombstone): Promise<void>;
12
- export declare function readMemoryTombstones(channelDir: string): Promise<MemoryTombstone[]>;
@@ -1,44 +1,13 @@
1
1
  import { createHash } from "node:crypto";
2
- import { appendFile, mkdir, readFile } from "node:fs/promises";
3
- import { dirname, join } from "node:path";
4
- import { createSerialQueue } from "../shared/serial-queue.js";
5
- const appendQueue = createSerialQueue();
2
+ /**
3
+ * The one piece of the v1 tombstone module that survived spec 050: a normalized content hash,
4
+ * shared by `store.ts` (the v2 `.tombstones.jsonl`), `migrate.ts` (carrying v1 tombstones over
5
+ * by hash), and the memory tools/commands (audit log entries that must not carry the forgotten
6
+ * text itself).
7
+ */
6
8
  function normalizeMemoryContent(content) {
7
9
  return content.normalize("NFKC").replace(/\s+/g, " ").trim().toLowerCase();
8
10
  }
9
11
  export function hashMemoryContent(content) {
10
12
  return createHash("sha256").update(normalizeMemoryContent(content)).digest("hex");
11
13
  }
12
- export function getMemoryTombstonesPath(channelDir) {
13
- return join(channelDir, ".memory", "tombstones.jsonl");
14
- }
15
- export async function appendMemoryTombstone(channelDir, tombstone) {
16
- const path = getMemoryTombstonesPath(channelDir);
17
- await appendQueue.run(path, async () => {
18
- await mkdir(dirname(path), { recursive: true });
19
- await appendFile(path, `${JSON.stringify(tombstone)}\n`, "utf-8");
20
- });
21
- }
22
- export async function readMemoryTombstones(channelDir) {
23
- try {
24
- const raw = await readFile(getMemoryTombstonesPath(channelDir), "utf-8");
25
- return raw
26
- .split("\n")
27
- .filter(Boolean)
28
- .flatMap((line) => {
29
- try {
30
- const value = JSON.parse(line);
31
- return value.entryId && value.contentHash ? [value] : [];
32
- }
33
- catch {
34
- return [];
35
- }
36
- });
37
- }
38
- catch (error) {
39
- if (error instanceof Error && "code" in error && error.code === "ENOENT") {
40
- return [];
41
- }
42
- throw error;
43
- }
44
- }
@@ -1,12 +1,19 @@
1
1
  import { buildStandardMessages } from "../shared/type-guards.js";
2
+ import { MEMORY_BOOTSTRAP_TAG } from "./render.js";
2
3
  import { redactSecrets } from "./secret-redaction.js";
3
- // The channel runner prepends the channel capsule, recalled memory, the task agenda
4
- // and the durable bootstrap to the raw user input, then wraps the input itself in
5
- // <user_message>. If that combined text flows back into consolidation / session
6
- // refresh / signal scans, previously recalled memory gets re-summarized into
4
+ // The channel runner prepends the memory bootstrap, the task agenda and the channel
5
+ // capsule to the raw user input, then wraps the input itself in <user_message>
6
+ // (`agent/turn-prompt.ts`). If that combined text flows back into consolidation /
7
+ // session refresh / signal scans, previously recalled memory gets re-summarized into
7
8
  // MEMORY.md — a self-reinforcing echo. Strip the injected wrappers before any memory
8
9
  // job reads the transcript.
9
- const INJECTED_CONTEXT_BLOCK = /<(runtime_context|runtime_turn_context|durable_memory_snapshot|task_agenda)>[\s\S]*?<\/\1>\s*/gi;
10
+ //
11
+ // The list must name every wrapper the runner can prepend, including retired ones still
12
+ // present in old transcripts: a name missing here does not merely leak that block, it
13
+ // also leaves text in front of <user_message> and so defeats the anchored unwrap below,
14
+ // which is exactly how `memory_bootstrap` went unnoticed after spec 050 renamed the
15
+ // wrapper (`durable_memory_snapshot` → `memory_bootstrap`).
16
+ const INJECTED_CONTEXT_BLOCK = new RegExp(`<(runtime_context|runtime_turn_context|durable_memory_snapshot|${MEMORY_BOOTSTRAP_TAG}|task_agenda)>[\\s\\S]*?<\\/\\1>\\s*`, "gi");
10
17
  const USER_MESSAGE_WRAPPER = /^<user_message>\s*([\s\S]*?)\s*<\/user_message>$/i;
11
18
  export function stripInjectedMemoryContext(text) {
12
19
  const withoutBlocks = text.replace(INJECTED_CONTEXT_BLOCK, "").trim();