@oyasmi/pipiclaw 0.9.2 → 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
@@ -4,11 +4,11 @@ import { formatLocalTime } from "../shared/local-time.js";
4
4
  import { clipTextByPromptUnits } from "../shared/prompt-units.js";
5
5
  import { errorMessage } from "../shared/text-utils.js";
6
6
  import { getDefaultChannelMemoryQueue } from "./channel-maintenance-queue.js";
7
- import { runInlineConsolidation, } from "./consolidation.js";
8
7
  import { readMemoryMaintenanceState, updateMemoryMaintenanceState, } from "./maintenance-state.js";
8
+ import { runReflect } from "./reflect.js";
9
+ import { reviewLogEntryFor } from "./reflect-job.js";
9
10
  import { appendMemoryReviewLog } from "./review-log.js";
10
- import { updateChannelSessionMemory } from "./session.js";
11
- import { buildCompactionMemorySourceWindow, buildIncrementalMemorySourceWindow, } from "./source-window.js";
11
+ import { buildCompactionMemorySourceWindow, buildIncrementalMemorySourceWindow } from "./source-window.js";
12
12
  const COMPACTION_INPUT_MAX_UNITS = 48_000;
13
13
  const COMPACTION_INPUT_MIN_UNITS = 4_000;
14
14
  const COMPACTION_INPUT_CHARS_PER_TOKEN = 3;
@@ -57,25 +57,13 @@ export function boundCompactionMessages(messages, contextWindow, reserveTokens)
57
57
  export class MemoryLifecycle {
58
58
  constructor(options) {
59
59
  this.options = options;
60
- this.sessionRefreshQueue = Promise.resolve();
61
60
  this.durableDirty = false;
62
61
  this.durableRevision = 0;
63
62
  this.lastDurableConsolidationRevision = 0;
64
- // Tracks the detached new-session consolidation so shutdown/tests can await it.
65
- this.backgroundNewSessionConsolidation = Promise.resolve();
63
+ // Tracks the detached new-session reflect run so shutdown/tests can await it.
64
+ this.backgroundNewSessionReflect = Promise.resolve();
66
65
  this.channelMemoryQueue = options.channelMemoryQueue ?? getDefaultChannelMemoryQueue();
67
66
  }
68
- buildRunOptions(messages, sessionEntries, sourceWindow) {
69
- return {
70
- channelId: this.options.channelId,
71
- channelDir: this.options.channelDir,
72
- model: this.options.getModel(),
73
- resolveApiKey: this.options.resolveApiKey,
74
- messages: messages ?? this.options.getMessages(),
75
- sessionEntries: sessionEntries ?? this.options.getSessionEntries(),
76
- sourceWindow,
77
- };
78
- }
79
67
  createExtensionFactory() {
80
68
  return (pi) => {
81
69
  pi.on("session_before_compact", async (event) => {
@@ -106,71 +94,27 @@ export class MemoryLifecycle {
106
94
  this.recordActivity("assistant-turn-completed");
107
95
  }
108
96
  async flushForShutdown() {
109
- // Let any detached new-session consolidation finish (and update the durable
110
- // checkpoint) before deciding whether a final flush is still needed.
111
- await this.whenNewSessionConsolidationSettled();
97
+ // Let any detached new-session reflect run finish (and update the durable checkpoint)
98
+ // before deciding whether a final flush is still needed.
99
+ await this.whenNewSessionReflectSettled();
112
100
  await this.runDurableMemoryJobSerial(async () => {
113
101
  // Shutdown is the last chance to persist, so use a looser gate than the
114
- // idle/compaction path: consolidate any unconsolidated durable activity,
115
- // including a session that only produced tool output with no final
116
- // assistant turn (which hasPendingAssistantSnapshot would skip).
102
+ // idle/compaction path: reflect on any unconsolidated durable activity, including a
103
+ // session that only produced tool output with no final assistant turn.
117
104
  if (!this.hasPendingDurableSnapshot()) {
118
105
  return;
119
106
  }
120
107
  const messageSnapshot = [...this.options.getMessages()];
121
108
  const sessionEntrySnapshot = [...this.options.getSessionEntries()];
122
109
  const revisionSnapshot = this.durableRevision;
123
- const settings = this.options.getSessionMemorySettings();
124
- await this.runPreflightConsolidationNow("shutdown", messageSnapshot, sessionEntrySnapshot, revisionSnapshot, settings);
110
+ await this.runBoundaryReflectNow("shutdown", messageSnapshot, sessionEntrySnapshot, revisionSnapshot);
125
111
  });
126
112
  }
127
- shouldForceRefreshFor(reason, settings) {
128
- if (!settings.enabled) {
129
- return false;
130
- }
131
- if (reason === "compaction") {
132
- return settings.forceRefreshBeforeCompact;
133
- }
134
- if (reason === "new-session") {
135
- return settings.forceRefreshBeforeNewSession;
136
- }
137
- return false;
138
- }
139
- async refreshSessionMemory(request) {
140
- const settings = this.options.getSessionMemorySettings();
141
- if (!settings.enabled) {
142
- return false;
143
- }
144
- const { reason } = request;
145
- try {
146
- await updateChannelSessionMemory({
147
- channelId: this.options.channelId,
148
- channelDir: this.options.channelDir,
149
- messages: request.messages ?? this.options.getMessages(),
150
- model: this.options.getModel(),
151
- resolveApiKey: this.options.resolveApiKey,
152
- timeoutMs: settings.timeoutMs,
153
- });
154
- log.logInfo(`[${this.options.channelId}] Session memory updated (${reason})`);
155
- return true;
156
- }
157
- catch (error) {
158
- const message = errorMessage(error);
159
- log.logWarning(`[${this.options.channelId}] Session memory update failed (${reason})`, message);
160
- return false;
161
- }
162
- }
163
- runSessionRefreshSerial(request) {
164
- const run = async () => this.refreshSessionMemory(request);
165
- const resultPromise = this.sessionRefreshQueue.then(run, run);
166
- this.sessionRefreshQueue = resultPromise.then(() => undefined, () => undefined);
167
- return resultPromise;
168
- }
169
113
  runDurableMemoryJobSerial(job) {
170
114
  return this.channelMemoryQueue.run(this.options.channelId, job);
171
115
  }
172
- // Any unconsolidated durable activity since the last checkpoint, regardless of
173
- // whether it ended on an assistant turn. Used only for the shutdown flush.
116
+ // Any unconsolidated durable activity since the last checkpoint, regardless of whether it
117
+ // ended on an assistant turn. Used only for the shutdown flush.
174
118
  hasPendingDurableSnapshot() {
175
119
  return this.durableDirty && this.durableRevision > this.lastDurableConsolidationRevision;
176
120
  }
@@ -178,15 +122,15 @@ export class MemoryLifecycle {
178
122
  this.lastDurableConsolidationRevision = Math.max(this.lastDurableConsolidationRevision, revision);
179
123
  this.durableDirty = this.durableRevision > this.lastDurableConsolidationRevision;
180
124
  }
181
- logConsolidationResult(reason, result) {
125
+ logReflectResult(reason, result) {
182
126
  if (result.skipped) {
183
- log.logEvent("debug", "memory.consolidation.skipped", "No meaningful snapshot", {
127
+ log.logEvent("debug", "memory.reflect.skipped", "No meaningful snapshot", {
184
128
  ctx: { channelId: this.options.channelId },
185
129
  fields: { reason },
186
130
  });
187
131
  return;
188
132
  }
189
- log.logInfo(`[${this.options.channelId}] Memory consolidation finished (${reason}): memory entries=${result.appendedMemoryEntries}, history=${result.appendedHistoryBlock ? "yes" : "no"}`);
133
+ log.logInfo(`[${this.options.channelId}] Memory reflect finished (${reason}): added=${result.added.length} updated=${result.updated.length} deleted=${result.deleted.length} touched=${result.touched.length} journal+=${result.journalAppended}`);
190
134
  }
191
135
  async appendReviewLog(entry) {
192
136
  try {
@@ -201,102 +145,71 @@ export class MemoryLifecycle {
201
145
  log.logWarning(`[${this.options.channelId}] Failed to write memory review log`, message);
202
146
  }
203
147
  }
204
- async recordConsolidationReview(reason, result) {
205
- if (result.skipped) {
206
- await this.appendReviewLog({
207
- reason,
208
- skipped: [{ target: "consolidation", reason: "no meaningful snapshot" }],
209
- });
210
- return;
211
- }
212
- const actions = [];
213
- const skipped = [];
214
- const candidateCount = result.appendedDurableEntries + result.appendedProbationaryEntries;
215
- if (candidateCount > 0 || result.appendedMemoryEntries > 0) {
216
- actions.push({
217
- target: "MEMORY.md",
218
- action: "append",
219
- entries: result.appendedMemoryEntries,
220
- durableCandidates: result.appendedDurableEntries,
221
- probationaryCandidates: result.appendedProbationaryEntries,
222
- });
223
- }
224
- if (result.appendedHistoryBlock) {
225
- actions.push({ target: "HISTORY.md", action: "append" });
226
- }
227
- else if (reason === "idle") {
228
- skipped.push({ target: "HISTORY.md", reason: "idle does not write HISTORY.md" });
229
- }
230
- // Defensive: review-log bookkeeping runs after the consolidation has already been
231
- // applied and checkpointed, so a shape surprise here must not report success as failure.
232
- for (const candidate of result.rejectedMemoryOps ?? []) {
233
- skipped.push({ target: "MEMORY.md", candidate, reason: "below auto-write confidence" });
234
- }
235
- await this.appendReviewLog({ reason, actions, skipped });
236
- }
237
- async runPreflightConsolidation(reason, messages, sessionEntries, firstKeptEntryId) {
148
+ async runBoundaryReflect(reason, messages, sessionEntries, firstKeptEntryId) {
238
149
  const messageSnapshot = [...(messages ?? this.options.getMessages())];
239
150
  const sessionEntrySnapshot = sessionEntries ? [...sessionEntries] : [...this.options.getSessionEntries()];
240
151
  const revisionSnapshot = this.durableRevision;
241
- const settings = this.options.getSessionMemorySettings();
242
152
  await this.runDurableMemoryJobSerial(async () => {
243
- await this.runPreflightConsolidationNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot, settings, firstKeptEntryId);
153
+ await this.runBoundaryReflectNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot, firstKeptEntryId);
244
154
  });
245
155
  }
246
- async runPreflightConsolidationNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot = this.durableRevision, settings = this.options.getSessionMemorySettings(), firstKeptEntryId) {
247
- if (this.shouldForceRefreshFor(reason, settings)) {
248
- await this.runSessionRefreshSerial({
249
- reason,
250
- messages: messageSnapshot,
251
- });
252
- }
156
+ async runBoundaryReflectNow(reason, messageSnapshot, sessionEntrySnapshot = [], revisionSnapshot = this.durableRevision, firstKeptEntryId) {
253
157
  try {
254
158
  const maintenanceState = this.options.appHomeDir
255
159
  ? await readMemoryMaintenanceState(this.options.appHomeDir, this.options.channelId)
256
160
  : undefined;
257
- const lastEntryId = maintenanceState?.lastCheckpointEntryId;
161
+ const lastEntryId = maintenanceState?.lastReflectedEntryId;
258
162
  const sourceWindow = reason === "compaction"
259
163
  ? buildCompactionMemorySourceWindow({
260
- entries: sessionEntrySnapshot ?? [],
164
+ entries: sessionEntrySnapshot,
261
165
  messagesToSummarize: messageSnapshot,
262
166
  firstKeptEntryId,
263
167
  lastEntryId,
264
168
  })
265
169
  : buildIncrementalMemorySourceWindow({
266
- entries: sessionEntrySnapshot ?? [],
170
+ entries: sessionEntrySnapshot,
267
171
  lastEntryId,
268
172
  sourceKind: reason,
269
173
  fallbackMessages: messageSnapshot,
270
174
  });
271
- log.logInfo(`[${this.options.channelId}] Memory consolidation starting (${reason})`);
272
- const result = await runInlineConsolidation({
273
- ...this.buildRunOptions(messageSnapshot, sessionEntrySnapshot, sourceWindow),
274
- mode: "boundary",
175
+ log.logInfo(`[${this.options.channelId}] Memory reflect starting (${reason})`);
176
+ const result = await runReflect({
177
+ channelId: this.options.channelId,
178
+ channelDir: this.options.channelDir,
179
+ workspaceDir: this.options.workspaceDir,
180
+ model: this.options.getModel(),
181
+ resolveApiKey: this.options.resolveApiKey,
182
+ messages: sourceWindow.messages,
183
+ usageContext: { channelId: this.options.channelId, correlationId: sourceWindow.windowId },
275
184
  });
276
185
  if (this.options.appHomeDir && sourceWindow.throughEntryId) {
277
186
  await updateMemoryMaintenanceState(this.options.appHomeDir, this.options.channelId, (current) => ({
278
187
  ...current,
279
- lastCheckpointEntryId: sourceWindow.throughEntryId,
280
- lastCheckpointAt: formatLocalTime(),
188
+ lastReflectedEntryId: sourceWindow.throughEntryId,
189
+ lastReflectAt: formatLocalTime(),
281
190
  failureBackoffUntil: null,
282
191
  }));
283
192
  }
284
193
  this.markDurableConsolidationCheckpoint(revisionSnapshot);
285
- this.logConsolidationResult(reason, result);
286
- await this.recordConsolidationReview(reason, result);
194
+ this.logReflectResult(reason, result);
195
+ await this.appendReviewLog({
196
+ reason: "reflect-boundary",
197
+ correlationId: sourceWindow.windowId,
198
+ ...reviewLogEntryFor(result),
199
+ });
287
200
  }
288
201
  catch (error) {
289
202
  const message = errorMessage(error);
290
- log.logWarning(`[${this.options.channelId}] Memory consolidation failed (${reason})`, message);
203
+ log.logWarning(`[${this.options.channelId}] Memory reflect failed (${reason})`, message);
291
204
  await this.appendReviewLog({
292
- reason,
205
+ reason: "reflect-boundary",
293
206
  error: message,
294
- skipped: [{ target: "consolidation", reason: "failed" }],
207
+ skipped: [{ target: "reflect", reason: "failed" }],
295
208
  });
296
209
  }
297
210
  }
298
211
  async handleSessionBeforeCompact(event) {
299
- await this.runPreflightConsolidation("compaction", event.preparation.messagesToSummarize, this.options.getSessionEntries(), event.preparation.firstKeptEntryId);
212
+ await this.runBoundaryReflect("compaction", event.preparation.messagesToSummarize, this.options.getSessionEntries(), event.preparation.firstKeptEntryId);
300
213
  const model = this.options.getModel();
301
214
  for (const key of ["messagesToSummarize", "turnPrefixMessages"]) {
302
215
  const bounded = boundCompactionMessages(event.preparation[key] ?? [], model.contextWindow, event.preparation.settings?.reserveTokens ?? 16_384);
@@ -317,25 +230,24 @@ export class MemoryLifecycle {
317
230
  }
318
231
  /** Snapshot the outgoing state for an out-of-band `/new` before its runner is retired. */
319
232
  noteNewSessionBoundary() {
320
- // Snapshot the outgoing session synchronously: the switch has not happened
321
- // yet, so getMessages()/getSessionEntries() still reference the session that
322
- // is about to be replaced. Once we yield, this.session is rebound to the new
323
- // (empty) session and the snapshot would be lost.
233
+ // Snapshot the outgoing session synchronously: the switch has not happened yet, so
234
+ // getMessages()/getSessionEntries() still reference the session about to be replaced.
235
+ // Once we yield, this.session is rebound to the new (empty) session and the snapshot
236
+ // would be lost.
324
237
  const messageSnapshot = [...this.options.getMessages()];
325
238
  const sessionEntrySnapshot = [...this.options.getSessionEntries()];
326
- // Run the LLM-backed consolidation in the background so /new returns
327
- // immediately. Failures are tolerated: runPreflightConsolidationNow catches
328
- // and logs its own errors, and the serial queue keeps this from racing with
329
- // idle/maintenance work on the same channel.
330
- this.backgroundNewSessionConsolidation = this.runPreflightConsolidation("new-session", messageSnapshot, sessionEntrySnapshot).catch((error) => {
239
+ // Run the LLM-backed reflect pass in the background so /new returns immediately.
240
+ // Failures are tolerated: runBoundaryReflectNow catches and logs its own errors, and the
241
+ // serial queue keeps this from racing with idle/maintenance work on the same channel.
242
+ this.backgroundNewSessionReflect = this.runBoundaryReflect("new-session", messageSnapshot, sessionEntrySnapshot).catch((error) => {
331
243
  const message = errorMessage(error);
332
- log.logWarning(`[${this.options.channelId}] Background new-session consolidation rejected`, message);
244
+ log.logWarning(`[${this.options.channelId}] Background new-session reflect rejected`, message);
333
245
  });
334
246
  this.recordActivity("boundary");
335
247
  }
336
- /** Await any in-flight detached new-session consolidation (shutdown/tests). */
337
- async whenNewSessionConsolidationSettled() {
338
- await this.backgroundNewSessionConsolidation;
248
+ /** Await any in-flight detached new-session reflect run (shutdown/tests). */
249
+ async whenNewSessionReflectSettled() {
250
+ await this.backgroundNewSessionReflect;
339
251
  }
340
252
  handleSessionStart(event) {
341
253
  if (event.reason !== "new") {
@@ -345,12 +257,10 @@ export class MemoryLifecycle {
345
257
  }
346
258
  recordActivity(kind) {
347
259
  const now = new Date();
348
- const latestSessionEntryId = this.options.getSessionEntries().at(-1)?.id;
349
260
  const event = {
350
261
  kind,
351
262
  channelId: this.options.channelId,
352
263
  timestamp: formatLocalTime(now),
353
- latestSessionEntryId,
354
264
  };
355
265
  try {
356
266
  void this.options.recordMemoryActivity?.(event);
@@ -1,61 +1,27 @@
1
- import type { PipiclawMemoryMaintenanceSettings, PipiclawSessionMemorySettings } from "../settings.js";
1
+ import type { PipiclawMemoryMaintenanceSettings } from "../settings.js";
2
2
  import type { MemoryMaintenanceState } from "./maintenance-state.js";
3
- export type MaintenanceJobKind = "session-refresh" | "memory-checkpoint" | "structural-maintenance";
3
+ /** Spec 050, D9: the three v1 jobs collapse to one. */
4
+ export type MaintenanceJobKind = "reflect";
4
5
  export interface MaintenanceGateDecision {
5
6
  allowed: boolean;
6
7
  skipReason?: string;
7
8
  jobKind: MaintenanceJobKind;
8
9
  }
9
- /**
10
- * Material checks are passed as thunks, never as values.
11
- *
12
- * Every gate below decides on cheap state (settings, timestamps, idle/backoff windows) before it
13
- * looks at any material, and the material is expensive to produce: scanning the whole transcript,
14
- * building the incremental source window, reading MEMORY.md/HISTORY.md. Evaluating it up front is
15
- * what made an idle daemon pay a real cost on every one-minute tick just to be denied.
16
- */
17
- export interface SessionRefreshGateInput {
18
- now: Date;
19
- state: MemoryMaintenanceState;
20
- sessionMemory: PipiclawSessionMemorySettings;
21
- maintenance: PipiclawMemoryMaintenanceSettings;
22
- channelActive: boolean;
23
- hasNewSessionEntry: () => boolean;
24
- hasMeaningfulMaterial: () => boolean;
25
- }
26
- export interface MemoryCheckpointMaterial {
10
+ export interface ReflectMaterial {
27
11
  hasNewEntry: boolean;
28
12
  hasMeaningfulExchange: boolean;
29
- batchSize: number;
30
- }
31
- export interface MemoryCheckpointGateInput {
32
- now: Date;
33
- state: MemoryMaintenanceState;
34
- maintenance: PipiclawMemoryMaintenanceSettings;
35
- channelActive: boolean;
36
- material: () => MemoryCheckpointMaterial;
37
- minBatchSize?: number;
38
13
  }
39
- export interface StructuralMaintenanceMaterial {
40
- memoryCleanupNeeded: boolean;
41
- historyFoldingNeeded: boolean;
42
- hasMemoryContent: boolean;
43
- hasHistoryContent: boolean;
44
- /** Active entries whose probation lapsed (spec 037, D8). */
45
- expiredEntryCount: number;
46
- }
47
- export interface StructuralMaintenanceGateInput {
14
+ /**
15
+ * Material checks are passed as a thunk, never as a value: every cheap check below (settings,
16
+ * timestamps, idle/backoff windows) runs before the material — which means building the
17
+ * incremental source window and scanning the transcript — is ever paid for. That is what keeps
18
+ * an idle daemon's steady-state tick to one state-file read plus timestamp arithmetic.
19
+ */
20
+ export interface ReflectGateInput {
48
21
  now: Date;
49
22
  state: MemoryMaintenanceState;
50
23
  maintenance: PipiclawMemoryMaintenanceSettings;
51
24
  channelActive: boolean;
52
- material: () => Promise<StructuralMaintenanceMaterial>;
53
- }
54
- export interface StructuralMaintenanceGateDecision extends MaintenanceGateDecision {
55
- runMemoryCleanup: boolean;
56
- runHistoryFolding: boolean;
57
- runProbationExpiry: boolean;
25
+ material: () => ReflectMaterial;
58
26
  }
59
- export declare function shouldRunSessionRefresh(input: SessionRefreshGateInput): MaintenanceGateDecision;
60
- export declare function shouldRunMemoryCheckpoint(input: MemoryCheckpointGateInput): MaintenanceGateDecision;
61
- export declare function shouldRunStructuralMaintenance(input: StructuralMaintenanceGateInput): Promise<StructuralMaintenanceGateDecision>;
27
+ export declare function shouldRunReflect(input: ReflectGateInput): MaintenanceGateDecision;
@@ -1,10 +1,8 @@
1
1
  import { parseLocalTime } from "../shared/local-time.js";
2
- function deny(jobKind, skipReason) {
3
- return { allowed: false, jobKind, skipReason };
4
- }
5
- function allow(jobKind) {
6
- return { allowed: true, jobKind };
2
+ function deny(skipReason) {
3
+ return { allowed: false, jobKind: "reflect", skipReason };
7
4
  }
5
+ const allow = { allowed: true, jobKind: "reflect" };
8
6
  function parseTime(value) {
9
7
  if (!value) {
10
8
  return null;
@@ -23,105 +21,28 @@ function hasIntervalElapsed(now, lastRunAt, intervalMs) {
23
21
  function minutesToMs(minutes) {
24
22
  return Math.max(0, minutes) * 60_000;
25
23
  }
26
- function hoursToMs(hours) {
27
- return Math.max(0, hours) * 3_600_000;
28
- }
29
- function sessionRefreshThresholdMet(state, settings) {
30
- return (state.turnsSinceSessionRefresh >= settings.minTurnsBetweenUpdate ||
31
- state.toolCallsSinceSessionRefresh >= settings.minToolCallsBetweenUpdate);
32
- }
33
- export function shouldRunSessionRefresh(input) {
34
- if (!input.sessionMemory.enabled) {
35
- return deny("session-refresh", "disabled");
36
- }
24
+ export function shouldRunReflect(input) {
37
25
  if (!input.state.dirty) {
38
- return deny("session-refresh", "clean");
26
+ return deny("clean");
39
27
  }
40
28
  if (isBeforeOptional(input.now, input.state.eligibleAfter)) {
41
- return deny("session-refresh", "not-idle-yet");
29
+ return deny("not-idle-yet");
42
30
  }
43
31
  if (input.channelActive) {
44
- return deny("session-refresh", "channel-active");
32
+ return deny("channel-active");
45
33
  }
46
34
  if (isBeforeOptional(input.now, input.state.failureBackoffUntil)) {
47
- return deny("session-refresh", "backoff-active");
48
- }
49
- if (!hasIntervalElapsed(input.now, input.state.lastSessionRefreshAt, minutesToMs(input.maintenance.sessionRefreshIntervalMinutes))) {
50
- return deny("session-refresh", "interval-not-elapsed");
51
- }
52
- if (!sessionRefreshThresholdMet(input.state, input.sessionMemory)) {
53
- return deny("session-refresh", "threshold-not-met");
54
- }
55
- if (!input.hasNewSessionEntry()) {
56
- return deny("session-refresh", "no-new-session-entry");
57
- }
58
- if (!input.hasMeaningfulMaterial()) {
59
- return deny("session-refresh", "no-meaningful-material");
60
- }
61
- return allow("session-refresh");
62
- }
63
- export function shouldRunMemoryCheckpoint(input) {
64
- if (!input.state.dirty) {
65
- return deny("memory-checkpoint", "clean");
66
- }
67
- if (isBeforeOptional(input.now, input.state.eligibleAfter)) {
68
- return deny("memory-checkpoint", "not-idle-yet");
35
+ return deny("backoff-active");
69
36
  }
70
- if (input.channelActive) {
71
- return deny("memory-checkpoint", "channel-active");
72
- }
73
- if (!hasIntervalElapsed(input.now, input.state.lastCheckpointAt, minutesToMs(input.maintenance.checkpointIntervalMinutes))) {
74
- return deny("memory-checkpoint", "interval-not-elapsed");
75
- }
76
- if (isBeforeOptional(input.now, input.state.failureBackoffUntil)) {
77
- return deny("memory-checkpoint", "backoff-active");
37
+ if (!hasIntervalElapsed(input.now, input.state.lastReflectAt, minutesToMs(input.maintenance.reflectIntervalMinutes))) {
38
+ return deny("interval-not-elapsed");
78
39
  }
79
40
  const material = input.material();
80
41
  if (!material.hasNewEntry) {
81
- return deny("memory-checkpoint", "no-new-entry");
42
+ return deny("no-new-entry");
82
43
  }
83
44
  if (!material.hasMeaningfulExchange) {
84
- return deny("memory-checkpoint", "no-meaningful-exchange");
85
- }
86
- if (material.batchSize < (input.minBatchSize ?? 2)) {
87
- return deny("memory-checkpoint", "batch-threshold-not-met");
88
- }
89
- return allow("memory-checkpoint");
90
- }
91
- export async function shouldRunStructuralMaintenance(input) {
92
- const jobKind = "structural-maintenance";
93
- const denyStructural = (skipReason) => ({
94
- allowed: false,
95
- jobKind,
96
- skipReason,
97
- runMemoryCleanup: false,
98
- runHistoryFolding: false,
99
- runProbationExpiry: false,
100
- });
101
- if (input.channelActive) {
102
- return denyStructural("channel-active");
103
- }
104
- if (!hasIntervalElapsed(input.now, input.state.lastStructuralMaintenanceAt, hoursToMs(input.maintenance.structuralMaintenanceIntervalHours))) {
105
- return denyStructural("interval-not-elapsed");
106
- }
107
- if (isBeforeOptional(input.now, input.state.failureBackoffUntil)) {
108
- return denyStructural("backoff-active");
109
- }
110
- const material = await input.material();
111
- const runProbationExpiry = material.expiredEntryCount > 0;
112
- if (!material.hasMemoryContent && !material.hasHistoryContent && !runProbationExpiry) {
113
- return denyStructural("empty-template-files");
114
- }
115
- const runMemoryCleanup = material.memoryCleanupNeeded;
116
- const runHistoryFolding = material.historyFoldingNeeded;
117
- if (!runMemoryCleanup && !runHistoryFolding && !runProbationExpiry) {
118
- return denyStructural("nothing-to-maintain");
45
+ return deny("no-meaningful-exchange");
119
46
  }
120
- return {
121
- allowed: true,
122
- jobKind,
123
- runMemoryCleanup,
124
- runHistoryFolding,
125
- runProbationExpiry,
126
- };
47
+ return allow;
127
48
  }
@@ -1,16 +1,11 @@
1
+ /** Spec 050, D9: one job (reflect), one small state shape. */
1
2
  export interface MemoryMaintenanceState {
2
3
  channelId: string;
3
4
  dirty: boolean;
4
5
  lastActivityAt?: string;
5
6
  eligibleAfter?: string;
6
- lastSessionRefreshAt?: string;
7
- lastCheckpointAt?: string;
8
- lastStructuralMaintenanceAt?: string;
9
- turnsSinceSessionRefresh: number;
10
- toolCallsSinceSessionRefresh: number;
11
- lastSessionEntryId?: string;
12
- lastSessionRefreshedEntryId?: string;
13
- lastCheckpointEntryId?: string;
7
+ lastReflectAt?: string;
8
+ lastReflectedEntryId?: string;
14
9
  failureBackoffUntil?: string | null;
15
10
  }
16
11
  export type MemoryActivityKind = "user-turn-started" | "tool-call" | "assistant-turn-completed" | "boundary";
@@ -19,7 +14,6 @@ export interface MemoryActivityEvent {
19
14
  channelId: string;
20
15
  timestamp: string;
21
16
  eligibleAfter?: string;
22
- latestSessionEntryId?: string;
23
17
  }
24
18
  export declare function getMemoryMaintenanceStateDir(appHomeDir: string): string;
25
19
  /**
@@ -42,13 +36,13 @@ export declare function applyMemoryActivityToState(state: MemoryMaintenanceState
42
36
  * JSON file through `writeFileAtomically` — two fsyncs apiece. A thirty-step turn paid that thirty
43
37
  * times, on storage whose fsync latency the runtime does not control.
44
38
  *
45
- * Batching is safe because nothing consumes this state promptly: every gate in
46
- * `maintenance-gates.ts` denies outright while the channel is active, and `eligibleAfter` holds
47
- * maintenance off for `minIdleMinutesBeforeLlmWork` after that. The scheduler then polls once a
48
- * minute. So the state only has to be accurate by the time a channel goes *idle* — which is why
49
- * the runner also flushes explicitly at the end of every turn, on top of the debounce here. The
50
- * debounce bounds what a crash can lose to a few seconds of counters, never a checkpoint: those
51
- * are written directly, and the serial queue keeps a flush from reordering against them.
39
+ * Batching is safe because nothing consumes this state promptly: the reflect gate denies outright
40
+ * while the channel is active, and `eligibleAfter` holds it off for `minIdleMinutesBeforeLlmWork`
41
+ * after that. The scheduler then polls once a minute. So the state only has to be accurate by the
42
+ * time a channel goes *idle* — which is why the runner also flushes explicitly at the end of every
43
+ * turn, on top of the debounce here. The debounce bounds what a crash can lose to a few seconds of
44
+ * `dirty`/`lastActivityAt`, never a reflect checkpoint: those are written directly, and the serial
45
+ * queue keeps a flush from reordering against them.
52
46
  */
53
47
  export interface MemoryActivityRecorder {
54
48
  record(event: MemoryActivityEvent): void;