@oyasmi/pipiclaw 0.9.2-beta.6 → 0.9.3-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 (165) hide show
  1. package/README.en.md +250 -0
  2. package/README.md +2 -0
  3. package/dist/agent/channel-runner.d.ts +43 -2
  4. package/dist/agent/channel-runner.js +135 -75
  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 +14 -0
  40. package/dist/memory/render.js +28 -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/playbooks/agent-delegation.md +4 -2
  54. package/dist/playbooks/background-jobs.md +1 -1
  55. package/dist/playbooks/event-scheduling.md +6 -2
  56. package/dist/playbooks/memory-and-learning.md +18 -11
  57. package/dist/playbooks/outbound-media.md +1 -1
  58. package/dist/playbooks/runtime-orientation.md +9 -8
  59. package/dist/playbooks/task-loop.md +88 -0
  60. package/dist/runtime/bootstrap.d.ts +3 -3
  61. package/dist/runtime/bootstrap.js +66 -41
  62. package/dist/runtime/events.d.ts +9 -0
  63. package/dist/runtime/events.js +43 -4
  64. package/dist/runtime/task-commands.d.ts +14 -15
  65. package/dist/runtime/task-commands.js +249 -485
  66. package/dist/runtime/task-driver.d.ts +41 -29
  67. package/dist/runtime/task-driver.js +170 -317
  68. package/dist/runtime/task-migration.d.ts +34 -30
  69. package/dist/runtime/task-migration.js +229 -183
  70. package/dist/runtime/task-wake.d.ts +6 -3
  71. package/dist/runtime/task-wake.js +26 -19
  72. package/dist/settings.d.ts +0 -29
  73. package/dist/settings.js +12 -35
  74. package/dist/shared/markdown-sections.d.ts +0 -1
  75. package/dist/shared/markdown-sections.js +0 -3
  76. package/dist/subagents/discovery.d.ts +2 -2
  77. package/dist/subagents/discovery.js +21 -10
  78. package/dist/subagents/external/progress-tail.js +6 -1
  79. package/dist/subagents/external/run.js +1 -0
  80. package/dist/subagents/runs.d.ts +19 -2
  81. package/dist/subagents/runs.js +73 -4
  82. package/dist/subagents/tool.d.ts +10 -8
  83. package/dist/subagents/tool.js +55 -94
  84. package/dist/tasks/brief.d.ts +17 -0
  85. package/dist/tasks/brief.js +57 -0
  86. package/dist/tasks/budget.d.ts +26 -0
  87. package/dist/tasks/budget.js +59 -0
  88. package/dist/tasks/cycle.d.ts +48 -0
  89. package/dist/tasks/cycle.js +94 -0
  90. package/dist/tasks/frontmatter.d.ts +73 -0
  91. package/dist/tasks/frontmatter.js +175 -0
  92. package/dist/tasks/ledger.d.ts +66 -106
  93. package/dist/tasks/ledger.js +90 -546
  94. package/dist/tasks/log.d.ts +88 -0
  95. package/dist/tasks/log.js +97 -0
  96. package/dist/tasks/rounds.d.ts +43 -0
  97. package/dist/tasks/rounds.js +57 -0
  98. package/dist/tasks/session-path.d.ts +9 -0
  99. package/dist/tasks/session-path.js +16 -0
  100. package/dist/tasks/steer.d.ts +8 -0
  101. package/dist/tasks/steer.js +79 -0
  102. package/dist/tasks/store.d.ts +60 -35
  103. package/dist/tasks/store.js +166 -107
  104. package/dist/tasks/ticket.d.ts +102 -0
  105. package/dist/tasks/ticket.js +209 -0
  106. package/dist/tasks/verification.d.ts +16 -0
  107. package/dist/tasks/verification.js +40 -1
  108. package/dist/tools/index.d.ts +13 -4
  109. package/dist/tools/index.js +5 -10
  110. package/dist/tools/memory-manage.d.ts +6 -16
  111. package/dist/tools/memory-manage.js +108 -129
  112. package/dist/tools/presentation.js +2 -1
  113. package/dist/tools/registry.d.ts +11 -2
  114. package/dist/tools/registry.js +17 -6
  115. package/dist/tools/subagent-manage.d.ts +0 -9
  116. package/dist/tools/subagent-manage.js +8 -17
  117. package/dist/tools/task-manage/create.js +2 -2
  118. package/dist/tools/task-manage/lifecycle.d.ts +9 -4
  119. package/dist/tools/task-manage/lifecycle.js +139 -187
  120. package/dist/tools/task-manage/log-view.d.ts +8 -0
  121. package/dist/tools/task-manage/log-view.js +24 -0
  122. package/dist/tools/task-manage/schema.d.ts +38 -14
  123. package/dist/tools/task-manage/schema.js +46 -27
  124. package/dist/tools/task-manage/shared.d.ts +24 -31
  125. package/dist/tools/task-manage/shared.js +103 -141
  126. package/dist/tools/task-manage/step-end.d.ts +11 -0
  127. package/dist/tools/task-manage/step-end.js +136 -0
  128. package/dist/tools/task-manage/types.d.ts +23 -32
  129. package/dist/tools/task-manage.d.ts +4 -3
  130. package/dist/tools/task-manage.js +30 -15
  131. package/dist/tools/tool-details.d.ts +1 -1
  132. package/dist/tui/app.js +0 -2
  133. package/package.json +1 -1
  134. package/dist/agent/effect-ledger.d.ts +0 -32
  135. package/dist/agent/effect-ledger.js +0 -89
  136. package/dist/memory/bootstrap.d.ts +0 -17
  137. package/dist/memory/bootstrap.js +0 -120
  138. package/dist/memory/candidates.d.ts +0 -26
  139. package/dist/memory/candidates.js +0 -202
  140. package/dist/memory/consolidation.d.ts +0 -54
  141. package/dist/memory/consolidation.js +0 -292
  142. package/dist/memory/extraction.d.ts +0 -54
  143. package/dist/memory/extraction.js +0 -240
  144. package/dist/memory/files.d.ts +0 -71
  145. package/dist/memory/files.js +0 -419
  146. package/dist/memory/maintenance-jobs.d.ts +0 -41
  147. package/dist/memory/maintenance-jobs.js +0 -265
  148. package/dist/memory/metadata.d.ts +0 -57
  149. package/dist/memory/metadata.js +0 -142
  150. package/dist/memory/probation.d.ts +0 -17
  151. package/dist/memory/probation.js +0 -44
  152. package/dist/memory/promotion.d.ts +0 -38
  153. package/dist/memory/promotion.js +0 -36
  154. package/dist/memory/recall.d.ts +0 -59
  155. package/dist/memory/recall.js +0 -746
  156. package/dist/memory/session.d.ts +0 -24
  157. package/dist/memory/session.js +0 -273
  158. package/dist/playbooks/task-driving.md +0 -92
  159. package/dist/playbooks/task-planning.md +0 -58
  160. package/dist/tasks/control.d.ts +0 -56
  161. package/dist/tasks/control.js +0 -169
  162. package/dist/tasks/transitions.d.ts +0 -16
  163. package/dist/tasks/transitions.js +0 -48
  164. package/dist/tools/task-manage/verification.d.ts +0 -19
  165. package/dist/tools/task-manage/verification.js +0 -91
@@ -1,419 +0,0 @@
1
- import { createHash, randomBytes } from "crypto";
2
- import { existsSync, mkdirSync } from "fs";
3
- import { appendFile, copyFile, readdir, rename, rm, stat } from "fs/promises";
4
- import { basename, join } from "path";
5
- import { writeFileAtomically, writeFileAtomicallySync } from "../shared/atomic-file.js";
6
- import { readOptionalTextFile } from "../shared/fs-utils.js";
7
- import { formatLocalTime, localStampForFilename, parseLocalTime } from "../shared/local-time.js";
8
- import { syncMemoryMetadata } from "./metadata.js";
9
- import { containsSecret, REDACTED_SECRET } from "./secret-redaction.js";
10
- import { appendMemoryTombstone, hashMemoryContent, readMemoryTombstones } from "./tombstones.js";
11
- const DEFAULT_CHANNEL_MEMORY = `# Channel Memory
12
-
13
- This file stores durable channel-specific memory.
14
-
15
- - It is not preloaded into session context.
16
- - Read it on demand when prior decisions, preferences, or long-running work matter.
17
- - The runtime may append updates here during consolidation.
18
-
19
- ## Durable Facts
20
-
21
- <!-- Stable facts, preferences, and ongoing commitments can accumulate here. -->
22
- `;
23
- const DEFAULT_CHANNEL_HISTORY = `# Channel History
24
-
25
- This file stores summarized older channel history.
26
-
27
- - It is not preloaded into session context.
28
- - Read it on demand when older context matters.
29
- - The runtime may append and fold history blocks here during consolidation.
30
- `;
31
- const DEFAULT_CHANNEL_SESSION = `# Session Title
32
-
33
- <!-- A short title for the current active work in this channel. -->
34
-
35
- # Current State
36
-
37
- <!-- What is actively being worked on right now. -->
38
-
39
- # User Intent
40
-
41
- <!-- What the user is currently trying to achieve. -->
42
-
43
- # Active Files
44
-
45
- <!-- Important files or directories currently in focus. -->
46
-
47
- # Decisions
48
-
49
- <!-- Recent decisions that matter to the current work. -->
50
-
51
- # Constraints
52
-
53
- <!-- Current constraints, assumptions, or important guardrails. -->
54
-
55
- # Errors & Corrections
56
-
57
- <!-- Recent failures, corrections, and things to avoid repeating. -->
58
-
59
- # Next Steps
60
-
61
- <!-- Likely next actions if work resumes later. -->
62
-
63
- # Worklog
64
-
65
- <!-- Very terse notes about recent progress. -->
66
- `;
67
- const MEMORY_BACKUP_DIR = ".memory-backups";
68
- // Backups are the last line of defense against a bad cleanup/rewrite (§1.3 tightened the guards
69
- // in front of them, but the backups themselves are what a human falls back to). At the default
70
- // 6-hour structural-maintenance cadence, 5 backups covered only ~30 hours of history.
71
- const MEMORY_BACKUP_KEEP = 10;
72
- const ENTRY_ID_COMMENT = /<!--\s*id:(m-[a-z0-9]+)\s*-->/i;
73
- const ENTRY_ID_COMMENT_TRAILING = /\s*<!--\s*id:m-[a-z0-9]+\s*-->\s*$/i;
74
- export function generateMemoryEntryId() {
75
- return `m-${randomBytes(4).toString("hex")}`;
76
- }
77
- // Deterministic id for legacy entries that predate id comments, so a single
78
- // consolidation prompt can reference them; the real id is written in on supersede.
79
- function stableMemoryEntryId(sectionHeading, content) {
80
- const hash = createHash("sha1").update(`${sectionHeading}\x00${content}`).digest("hex");
81
- return `m-${hash.slice(0, 8)}`;
82
- }
83
- export function stripMemoryEntryIdComment(text) {
84
- return text.replace(ENTRY_ID_COMMENT_TRAILING, "").trimEnd();
85
- }
86
- function renderMemoryEntryLine(content, id) {
87
- return `- ${content.trim()} <!--id:${id}-->`;
88
- }
89
- export function parseUpdateHeadingTimestamp(heading) {
90
- const match = heading.match(/^Update\s+(.+)$/);
91
- if (!match) {
92
- return undefined;
93
- }
94
- const timestamp = match[1].trim();
95
- return parseLocalTime(timestamp) !== undefined ? timestamp : undefined;
96
- }
97
- /** Parse durable MEMORY.md bullet entries with stable ids for op-based edits. */
98
- export function parseChannelMemoryEntries(content) {
99
- const lines = content.replace(/\r/g, "").split("\n");
100
- const entries = [];
101
- let currentHeading = "";
102
- for (let index = 0; index < lines.length; index++) {
103
- const line = lines[index];
104
- if (line.startsWith("## ")) {
105
- currentHeading = line.slice(3).trim();
106
- continue;
107
- }
108
- const trimmed = line.trim();
109
- // Only bullets inside an H2 section are durable entries; bullets under the H1
110
- // header (the template's descriptive intro) are prose, not memory.
111
- if (!currentHeading || !trimmed.startsWith("- ")) {
112
- continue;
113
- }
114
- const body = trimmed.slice(2);
115
- const idMatch = body.match(ENTRY_ID_COMMENT);
116
- const displayContent = stripMemoryEntryIdComment(body).trim();
117
- if (!displayContent) {
118
- continue;
119
- }
120
- entries.push({
121
- id: idMatch ? idMatch[1] : stableMemoryEntryId(currentHeading, displayContent),
122
- content: displayContent,
123
- sectionHeading: currentHeading,
124
- timestamp: parseUpdateHeadingTimestamp(currentHeading),
125
- lineIndex: index,
126
- hasExplicitId: Boolean(idMatch),
127
- });
128
- }
129
- return entries;
130
- }
131
- /**
132
- * Apply add/supersede/invalidate ops to a channel MEMORY.md with line-level edits,
133
- * preserving any surrounding markdown. Missing supersede targets downgrade to add;
134
- * missing invalidate targets are skipped. Mutating edits are backed up first.
135
- */
136
- export async function applyChannelMemoryOps(channelDir, ops, timestamp = formatLocalTime()) {
137
- const result = {
138
- added: 0,
139
- superseded: 0,
140
- invalidated: 0,
141
- downgradedToAdd: 0,
142
- missingTarget: 0,
143
- forgotten: 0,
144
- blockedByPolicy: 0,
145
- blockedByTombstone: 0,
146
- skippedDuplicate: 0,
147
- promotedFromProbation: 0,
148
- };
149
- if (ops.length === 0) {
150
- return result;
151
- }
152
- ensureChannelMemoryFilesSync(channelDir);
153
- const path = getChannelMemoryPath(channelDir);
154
- const existing = await readOptionalTextFile(path);
155
- const lines = existing.replace(/\r/g, "").split("\n");
156
- const existingEntries = parseChannelMemoryEntries(existing);
157
- const byId = new Map(existingEntries.map((entry) => [entry.id, entry]));
158
- // Reconcile legacy entries before applying removals so terminal status retains
159
- // the entry's provenance even when no sidecar record existed yet.
160
- const currentMetadata = await syncMemoryMetadata(channelDir, existingEntries, [], timestamp);
161
- const tombstones = await readMemoryTombstones(channelDir);
162
- const tombstoneHashes = new Set(tombstones.map((tombstone) => tombstone.contentHash));
163
- const tombstoneSourceIds = new Set(tombstones.flatMap((tombstone) => tombstone.sourceEntryIds ?? []));
164
- const activeContentHashes = new Set(existingEntries.map((entry) => hashMemoryContent(entry.content)));
165
- const activeEntryIdByContentHash = new Map(existingEntries.map((entry) => [hashMemoryContent(entry.content), entry.id]));
166
- const appliedSourceCorrelationIds = new Set(Object.values(currentMetadata.entries).flatMap((entry) => entry.sourceCorrelationIds));
167
- const removals = new Set();
168
- const replacements = new Map();
169
- const additions = [];
170
- const metadataUpdates = [];
171
- for (const op of ops) {
172
- if (op.op === "add" || op.op === "supersede") {
173
- if (op.metadata?.sourceCorrelationId && appliedSourceCorrelationIds.has(op.metadata.sourceCorrelationId)) {
174
- result.skippedDuplicate++;
175
- continue;
176
- }
177
- if (containsSecret(op.content) || op.content.includes(REDACTED_SECRET)) {
178
- result.blockedByPolicy++;
179
- continue;
180
- }
181
- if (tombstoneHashes.has(hashMemoryContent(op.content)) ||
182
- op.sourceEntryIds?.some((entryId) => tombstoneSourceIds.has(entryId))) {
183
- result.blockedByTombstone++;
184
- continue;
185
- }
186
- }
187
- if (op.op === "add") {
188
- if (op.content.trim()) {
189
- const contentHash = hashMemoryContent(op.content);
190
- if (activeContentHashes.has(contentHash)) {
191
- result.skippedDuplicate++;
192
- // A durable write (explicit `probationUntil: null`) restating a fact that is
193
- // already stored, possibly on probation, is itself evidence the fact matters —
194
- // promote the existing entry in place (spec 037, D7 path 2). A probationary
195
- // restatement leaves the existing entry's deadline untouched: seeing the same
196
- // medium-necessity thing twice does not by itself earn it a permanent slot.
197
- if (op.metadata?.probationUntil === null) {
198
- const existingId = activeEntryIdByContentHash.get(contentHash);
199
- if (existingId) {
200
- metadataUpdates.push({ id: existingId, metadata: { probationUntil: null } });
201
- result.promotedFromProbation++;
202
- }
203
- }
204
- continue;
205
- }
206
- const id = generateMemoryEntryId();
207
- additions.push({ content: op.content.trim(), id });
208
- activeContentHashes.add(contentHash);
209
- metadataUpdates.push({ id, status: "active", metadata: op.metadata, sourceEntryIds: op.sourceEntryIds });
210
- result.added++;
211
- }
212
- continue;
213
- }
214
- const target = byId.get(op.targetId);
215
- if (op.op === "invalidate" || op.op === "forget") {
216
- if (target) {
217
- removals.add(target.lineIndex);
218
- if (op.op === "forget") {
219
- const sourceEntryIds = Array.from(new Set([
220
- ...(currentMetadata.entries[target.id]?.sourceEntryIds ?? []),
221
- ...(op.sourceEntryIds ?? []),
222
- ]));
223
- await appendMemoryTombstone(channelDir, {
224
- entryId: target.id,
225
- contentHash: hashMemoryContent(target.content),
226
- deletedAt: timestamp,
227
- scope: "channel",
228
- reason: op.reason?.trim() || "user forget",
229
- sourceEntryIds,
230
- });
231
- result.forgotten++;
232
- metadataUpdates.push({ id: target.id, status: "forgotten", sourceEntryIds });
233
- }
234
- else {
235
- result.invalidated++;
236
- metadataUpdates.push({ id: target.id, status: "invalidated" });
237
- }
238
- }
239
- else {
240
- result.missingTarget++;
241
- }
242
- continue;
243
- }
244
- // supersede
245
- if (!op.content.trim()) {
246
- continue;
247
- }
248
- if (target) {
249
- const replacementId = target.hasExplicitId ? target.id : generateMemoryEntryId();
250
- replacements.set(target.lineIndex, renderMemoryEntryLine(op.content, replacementId));
251
- if (replacementId !== target.id)
252
- metadataUpdates.push({ id: target.id, status: "superseded" });
253
- metadataUpdates.push({
254
- id: replacementId,
255
- status: "active",
256
- metadata: op.metadata,
257
- sourceEntryIds: op.sourceEntryIds,
258
- });
259
- result.superseded++;
260
- }
261
- else {
262
- const contentHash = hashMemoryContent(op.content);
263
- if (activeContentHashes.has(contentHash)) {
264
- result.skippedDuplicate++;
265
- continue;
266
- }
267
- const id = generateMemoryEntryId();
268
- additions.push({ content: op.content.trim(), id });
269
- activeContentHashes.add(contentHash);
270
- metadataUpdates.push({ id, status: "active", metadata: op.metadata, sourceEntryIds: op.sourceEntryIds });
271
- result.downgradedToAdd++;
272
- result.missingTarget++;
273
- }
274
- }
275
- const editedLines = lines
276
- .map((line, index) => replacements.get(index) ?? line)
277
- .filter((_, index) => !removals.has(index));
278
- let nextContent = editedLines.join("\n");
279
- if (additions.length > 0) {
280
- const block = [
281
- `## Update ${timestamp}`,
282
- ...additions.map(({ content, id }) => renderMemoryEntryLine(content, id)),
283
- ].join("\n");
284
- nextContent = `${ensureTrailingNewlines(nextContent)}${block}\n`;
285
- }
286
- else {
287
- nextContent = `${nextContent.replace(/\s+$/, "")}\n`;
288
- }
289
- if (removals.size > 0 || replacements.size > 0) {
290
- await backupBeforeRewrite(channelDir, path);
291
- }
292
- await writeFileAtomically(path, nextContent);
293
- await syncMemoryMetadata(channelDir, parseChannelMemoryEntries(nextContent), metadataUpdates, timestamp);
294
- return result;
295
- }
296
- // Best-effort: a backup is a safety net, never a precondition for the write, so a
297
- // backup failure (permissions, disk full) must not block persisting memory.
298
- async function backupBeforeRewrite(channelDir, sourcePath) {
299
- try {
300
- if (!existsSync(sourcePath)) {
301
- return;
302
- }
303
- const backupDir = join(channelDir, MEMORY_BACKUP_DIR);
304
- mkdirSync(backupDir, { recursive: true });
305
- const stamp = localStampForFilename();
306
- const name = basename(sourcePath, ".md");
307
- await copyFile(sourcePath, join(backupDir, `${name}-${stamp}.md`));
308
- const files = (await readdir(backupDir))
309
- .filter((file) => file.startsWith(`${name}-`) && file.endsWith(".md"))
310
- .sort();
311
- const excess = files.slice(0, Math.max(0, files.length - MEMORY_BACKUP_KEEP));
312
- await Promise.all(excess.map((file) => rm(join(backupDir, file), { force: true })));
313
- }
314
- catch {
315
- /* best-effort backup */
316
- }
317
- }
318
- function normalizeContent(content) {
319
- return content.trim().length > 0 ? `${content.trim()}\n` : "";
320
- }
321
- function ensureTrailingNewlines(content) {
322
- return content.trimEnd().length > 0 ? `${content.trimEnd()}\n\n` : "";
323
- }
324
- export function getChannelMemoryPath(channelDir) {
325
- return join(channelDir, "MEMORY.md");
326
- }
327
- export function getChannelHistoryPath(channelDir) {
328
- return join(channelDir, "HISTORY.md");
329
- }
330
- export function getChannelSessionPath(channelDir) {
331
- return join(channelDir, "SESSION.md");
332
- }
333
- export function ensureChannelMemoryFilesSync(channelDir) {
334
- const memoryPath = getChannelMemoryPath(channelDir);
335
- const historyPath = getChannelHistoryPath(channelDir);
336
- const sessionPath = getChannelSessionPath(channelDir);
337
- mkdirSync(channelDir, { recursive: true });
338
- if (!existsSync(memoryPath)) {
339
- writeFileAtomicallySync(memoryPath, DEFAULT_CHANNEL_MEMORY);
340
- }
341
- if (!existsSync(historyPath)) {
342
- writeFileAtomicallySync(historyPath, DEFAULT_CHANNEL_HISTORY);
343
- }
344
- if (!existsSync(sessionPath)) {
345
- writeFileAtomicallySync(sessionPath, DEFAULT_CHANNEL_SESSION);
346
- }
347
- }
348
- export async function readChannelMemory(channelDir) {
349
- return readOptionalTextFile(getChannelMemoryPath(channelDir));
350
- }
351
- export async function readChannelHistory(channelDir) {
352
- return readOptionalTextFile(getChannelHistoryPath(channelDir));
353
- }
354
- export async function readChannelSession(channelDir) {
355
- return readOptionalTextFile(getChannelSessionPath(channelDir));
356
- }
357
- export async function rewriteChannelMemory(channelDir, content) {
358
- ensureChannelMemoryFilesSync(channelDir);
359
- const path = getChannelMemoryPath(channelDir);
360
- await backupBeforeRewrite(channelDir, path);
361
- const nextContent = normalizeContent(content) || DEFAULT_CHANNEL_MEMORY;
362
- await writeFileAtomically(path, nextContent);
363
- await syncMemoryMetadata(channelDir, parseChannelMemoryEntries(nextContent));
364
- }
365
- export async function rewriteChannelHistory(channelDir, content) {
366
- ensureChannelMemoryFilesSync(channelDir);
367
- const path = getChannelHistoryPath(channelDir);
368
- await backupBeforeRewrite(channelDir, path);
369
- const nextContent = normalizeContent(content) || DEFAULT_CHANNEL_HISTORY;
370
- await writeFileAtomically(path, nextContent);
371
- }
372
- export async function rewriteChannelSession(channelDir, content) {
373
- ensureChannelMemoryFilesSync(channelDir);
374
- const nextContent = normalizeContent(content) || DEFAULT_CHANNEL_SESSION;
375
- await writeFileAtomically(getChannelSessionPath(channelDir), nextContent);
376
- }
377
- export function getChannelHistoryArchivePath(channelDir) {
378
- return join(channelDir, "HISTORY.archive.md");
379
- }
380
- /** Append raw history blocks to a never-rewritten archive before lossy folding. */
381
- // First-generation LLM summaries live only here (not in context.jsonl), so this file is never
382
- // deleted, only rotated: at 4MB the whole file becomes `.1` (overwriting any older `.1`) and a
383
- // fresh file starts, capping retention at two generations instead of growing unbounded.
384
- const HISTORY_ARCHIVE_ROTATE_AT_BYTES = 4 * 1024 * 1024;
385
- export async function appendChannelHistoryArchive(channelDir, block) {
386
- const trimmedContent = block.content.trim();
387
- if (!trimmedContent) {
388
- return;
389
- }
390
- ensureChannelMemoryFilesSync(channelDir);
391
- const path = getChannelHistoryArchivePath(channelDir);
392
- const renderedBlock = [`## Archived ${block.timestamp}`, trimmedContent].join("\n\n");
393
- const currentSize = await stat(path)
394
- .then((info) => info.size)
395
- .catch(() => 0);
396
- if (currentSize === 0) {
397
- await writeFileAtomically(path, `${ensureTrailingNewlines("# Channel History Archive\n")}${renderedBlock}\n`);
398
- return;
399
- }
400
- if (currentSize >= HISTORY_ARCHIVE_ROTATE_AT_BYTES) {
401
- await rename(path, `${path}.1`).catch(() => { });
402
- await writeFileAtomically(path, `${ensureTrailingNewlines("# Channel History Archive\n")}${renderedBlock}\n`);
403
- return;
404
- }
405
- // Append-only: this file only ever grows through this function, so a full read-modify-write
406
- // on every fold (previously O(n) per call, O(n^2) over the file's lifetime) is unnecessary.
407
- await appendFile(path, `\n${renderedBlock}\n`, "utf-8");
408
- }
409
- export async function appendChannelHistoryBlock(channelDir, block) {
410
- const trimmedContent = block.content.trim();
411
- if (!trimmedContent) {
412
- return;
413
- }
414
- ensureChannelMemoryFilesSync(channelDir);
415
- const path = getChannelHistoryPath(channelDir);
416
- const existing = await readOptionalTextFile(path);
417
- const renderedBlock = [`## ${block.timestamp}`, trimmedContent].join("\n\n");
418
- await writeFileAtomically(path, `${ensureTrailingNewlines(existing)}${renderedBlock}\n`);
419
- }
@@ -1,41 +0,0 @@
1
- import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
- import type { Api, Model } from "@earendil-works/pi-ai";
3
- import type { SessionEntry } from "@earendil-works/pi-coding-agent";
4
- import type { PipiclawMemoryMaintenanceSettings, PipiclawSessionMemorySettings } from "../settings.js";
5
- import { type ChannelMemoryQueue } from "./channel-maintenance-queue.js";
6
- import { type MaintenanceJobKind } from "./maintenance-gates.js";
7
- export interface MaintenanceJobSettings {
8
- sessionMemory: PipiclawSessionMemorySettings;
9
- memoryMaintenance: PipiclawMemoryMaintenanceSettings;
10
- }
11
- interface BaseMaintenanceJobInput {
12
- appHomeDir: string;
13
- channelId: string;
14
- channelDir: string;
15
- channelActive: boolean;
16
- now?: Date;
17
- settings: MaintenanceJobSettings;
18
- model: Model<Api>;
19
- resolveApiKey: (model: Model<Api>) => Promise<string>;
20
- /** Transcript accessors: only called once a gate has decided the job may actually run. */
21
- messages: () => AgentMessage[];
22
- sessionEntries: () => SessionEntry[];
23
- queue?: ChannelMemoryQueue;
24
- }
25
- export interface SessionRefreshJobInput extends BaseMaintenanceJobInput {
26
- }
27
- export interface MemoryCheckpointJobInput extends BaseMaintenanceJobInput {
28
- }
29
- export interface StructuralMaintenanceJobInput extends BaseMaintenanceJobInput {
30
- }
31
- export interface MaintenanceJobResult {
32
- jobKind: MaintenanceJobKind;
33
- ran: boolean;
34
- skipped: boolean;
35
- skipReason?: string;
36
- error?: string;
37
- }
38
- export declare function runSessionRefreshJob(input: SessionRefreshJobInput): Promise<MaintenanceJobResult>;
39
- export declare function runMemoryCheckpointJob(input: MemoryCheckpointJobInput): Promise<MaintenanceJobResult>;
40
- export declare function runStructuralMaintenanceJob(input: StructuralMaintenanceJobInput): Promise<MaintenanceJobResult>;
41
- export {};