@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
@@ -1,265 +0,0 @@
1
- import { formatLocalTime } from "../shared/local-time.js";
2
- import { errorMessage } from "../shared/text-utils.js";
3
- import { getDefaultChannelMemoryQueue } from "./channel-maintenance-queue.js";
4
- import { cleanupChannelMemory, foldChannelHistory, getStructuralMaintenanceStats, runInlineConsolidation, } from "./consolidation.js";
5
- import { readChannelHistory, readChannelMemory } from "./files.js";
6
- import { shouldRunMemoryCheckpoint, shouldRunSessionRefresh, shouldRunStructuralMaintenance, } from "./maintenance-gates.js";
7
- import { readMemoryMaintenanceState, updateMemoryMaintenanceState } from "./maintenance-state.js";
8
- import { readMemoryMetadata } from "./metadata.js";
9
- import { collectExpiredEntryIds, expireMemoryEntries } from "./probation.js";
10
- import { appendMemoryReviewLog } from "./review-log.js";
11
- import { updateChannelSessionMemory } from "./session.js";
12
- import { buildIncrementalMemorySourceWindow } from "./source-window.js";
13
- import { hasMeaningfulExchange, sanitizeMessagesForMemory } from "./transcript.js";
14
- /** Evaluate `load` at most once, so a gate and the job body can share one expensive read. */
15
- function once(load) {
16
- let cached;
17
- return () => {
18
- cached ??= { value: load() };
19
- return cached.value;
20
- };
21
- }
22
- function latestEntryId(entries) {
23
- return entries.at(-1)?.id;
24
- }
25
- function hasMeaningfulMessages(messages) {
26
- return hasMeaningfulExchange(sanitizeMessagesForMemory(messages));
27
- }
28
- function makeRunOptions(input, usageCorrelationId) {
29
- return {
30
- channelId: input.channelId,
31
- channelDir: input.channelDir,
32
- model: input.model,
33
- resolveApiKey: input.resolveApiKey,
34
- messages: input.messages(),
35
- sessionEntries: input.sessionEntries(),
36
- usageCorrelationId,
37
- minAutoWriteConfidence: input.settings.memoryMaintenance.minMemoryAutoWriteConfidence,
38
- };
39
- }
40
- function backoffUntil(now, settings) {
41
- return formatLocalTime(new Date(now.getTime() + Math.max(0, settings.failureBackoffMinutes) * 60_000));
42
- }
43
- async function appendJobReviewLog(channelDir, channelId, reason, entry, now) {
44
- await appendMemoryReviewLog(channelDir, {
45
- timestamp: formatLocalTime(now),
46
- channelId,
47
- reason,
48
- ...entry,
49
- });
50
- }
51
- function skipped(jobKind, skipReason) {
52
- return { jobKind, ran: false, skipped: true, skipReason };
53
- }
54
- function ran(jobKind) {
55
- return { jobKind, ran: true, skipped: false };
56
- }
57
- function failed(jobKind, error) {
58
- return {
59
- jobKind,
60
- ran: false,
61
- skipped: false,
62
- error: errorMessage(error),
63
- };
64
- }
65
- async function runQueued(input, job) {
66
- return (input.queue ?? getDefaultChannelMemoryQueue()).run(input.channelId, job);
67
- }
68
- export async function runSessionRefreshJob(input) {
69
- return runQueued(input, async () => {
70
- const now = input.now ?? new Date();
71
- const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
72
- const messages = once(input.messages);
73
- const latestEntry = once(() => latestEntryId(input.sessionEntries()));
74
- const decision = shouldRunSessionRefresh({
75
- now,
76
- state,
77
- sessionMemory: input.settings.sessionMemory,
78
- maintenance: input.settings.memoryMaintenance,
79
- channelActive: input.channelActive,
80
- hasNewSessionEntry: () => latestEntry() !== undefined && latestEntry() !== state.lastSessionRefreshedEntryId,
81
- hasMeaningfulMaterial: () => hasMeaningfulMessages(messages()),
82
- });
83
- if (!decision.allowed) {
84
- await appendJobReviewLog(input.channelDir, input.channelId, "session-refresh-job", { skipped: [{ target: "SESSION.md", reason: decision.skipReason }] }, now);
85
- return skipped(decision.jobKind, decision.skipReason ?? "skipped");
86
- }
87
- const latestId = latestEntry();
88
- try {
89
- const correlationId = `session-refresh:${latestId ?? formatLocalTime(now)}`;
90
- await updateChannelSessionMemory({
91
- channelId: input.channelId,
92
- channelDir: input.channelDir,
93
- messages: messages(),
94
- model: input.model,
95
- resolveApiKey: input.resolveApiKey,
96
- timeoutMs: input.settings.sessionMemory.timeoutMs,
97
- usageCorrelationId: correlationId,
98
- });
99
- await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
100
- ...current,
101
- lastSessionRefreshAt: formatLocalTime(now),
102
- turnsSinceSessionRefresh: 0,
103
- toolCallsSinceSessionRefresh: 0,
104
- lastSessionRefreshedEntryId: latestId ?? current.lastSessionRefreshedEntryId,
105
- lastSessionEntryId: latestId ?? current.lastSessionEntryId,
106
- failureBackoffUntil: null,
107
- }));
108
- await appendJobReviewLog(input.channelDir, input.channelId, "session-refresh-job", { actions: [{ target: "SESSION.md", action: "rewrite" }], correlationId }, now);
109
- return ran("session-refresh");
110
- }
111
- catch (error) {
112
- await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
113
- ...current,
114
- failureBackoffUntil: backoffUntil(now, input.settings.memoryMaintenance),
115
- }));
116
- const result = failed("session-refresh", error);
117
- await appendJobReviewLog(input.channelDir, input.channelId, "session-refresh-job", { error: result.error, skipped: [{ target: "SESSION.md", reason: "failed" }] }, now);
118
- return result;
119
- }
120
- });
121
- }
122
- export async function runMemoryCheckpointJob(input) {
123
- return runQueued(input, async () => {
124
- const now = input.now ?? new Date();
125
- const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
126
- const loadSourceWindow = once(() => buildIncrementalMemorySourceWindow({
127
- entries: input.sessionEntries(),
128
- lastEntryId: state.lastCheckpointEntryId,
129
- sourceKind: "idle",
130
- fallbackMessages: input.messages(),
131
- }));
132
- const decision = shouldRunMemoryCheckpoint({
133
- now,
134
- state,
135
- maintenance: input.settings.memoryMaintenance,
136
- channelActive: input.channelActive,
137
- material: () => {
138
- const window = loadSourceWindow();
139
- return {
140
- hasNewEntry: window.entries.length > 0,
141
- hasMeaningfulExchange: hasMeaningfulMessages(window.messages),
142
- batchSize: window.entries.length,
143
- };
144
- },
145
- });
146
- if (!decision.allowed) {
147
- await appendJobReviewLog(input.channelDir, input.channelId, "memory-checkpoint-job", { skipped: [{ target: "consolidation", reason: decision.skipReason }] }, now);
148
- return skipped(decision.jobKind, decision.skipReason ?? "skipped");
149
- }
150
- const sourceWindow = loadSourceWindow();
151
- try {
152
- const result = await runInlineConsolidation({
153
- ...makeRunOptions(input),
154
- sourceWindow,
155
- mode: "idle",
156
- });
157
- await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
158
- ...current,
159
- lastCheckpointAt: formatLocalTime(now),
160
- lastCheckpointEntryId: sourceWindow.throughEntryId ?? current.lastCheckpointEntryId,
161
- failureBackoffUntil: null,
162
- }));
163
- await appendJobReviewLog(input.channelDir, input.channelId, "memory-checkpoint-job", result.skipped
164
- ? {
165
- skipped: [{ target: "consolidation", reason: "no meaningful snapshot" }],
166
- correlationId: sourceWindow.windowId,
167
- }
168
- : {
169
- actions: [
170
- {
171
- target: "MEMORY.md",
172
- action: "append",
173
- entries: result.appendedMemoryEntries,
174
- durableCandidates: result.appendedDurableEntries,
175
- probationaryCandidates: result.appendedProbationaryEntries,
176
- },
177
- ],
178
- skipped: (result.rejectedMemoryOps ?? []).map((candidate) => ({
179
- target: "MEMORY.md",
180
- candidate,
181
- reason: "below auto-write confidence",
182
- })),
183
- correlationId: sourceWindow.windowId,
184
- }, now);
185
- return ran("memory-checkpoint");
186
- }
187
- catch (error) {
188
- await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
189
- ...current,
190
- failureBackoffUntil: backoffUntil(now, input.settings.memoryMaintenance),
191
- }));
192
- const result = failed("memory-checkpoint", error);
193
- await appendJobReviewLog(input.channelDir, input.channelId, "memory-checkpoint-job", { error: result.error, skipped: [{ target: "consolidation", reason: "failed" }] }, now);
194
- return result;
195
- }
196
- });
197
- }
198
- export async function runStructuralMaintenanceJob(input) {
199
- return runQueued(input, async () => {
200
- const now = input.now ?? new Date();
201
- const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
202
- const loadFiles = once(() => Promise.all([readChannelMemory(input.channelDir), readChannelHistory(input.channelDir)]));
203
- const loadExpiredCount = once(async () => {
204
- const metadata = await readMemoryMetadata(input.channelDir);
205
- return collectExpiredEntryIds(metadata, now).length;
206
- });
207
- const decision = await shouldRunStructuralMaintenance({
208
- now,
209
- state,
210
- maintenance: input.settings.memoryMaintenance,
211
- channelActive: input.channelActive,
212
- material: async () => ({
213
- ...getStructuralMaintenanceStats(...(await loadFiles())),
214
- expiredEntryCount: await loadExpiredCount(),
215
- }),
216
- });
217
- if (!decision.allowed) {
218
- await appendJobReviewLog(input.channelDir, input.channelId, "structural-maintenance-job", { skipped: [{ target: "structural-maintenance", reason: decision.skipReason }] }, now);
219
- return skipped(decision.jobKind, decision.skipReason ?? "skipped");
220
- }
221
- try {
222
- const correlationId = `structural-maintenance:${formatLocalTime(now)}`;
223
- const options = makeRunOptions(input, correlationId);
224
- // Probation eviction runs first, deterministically, before the LLM cleanup pass sees the
225
- // file — no point spending a cleanup prompt on entries about to be invalidated (spec 037, D8).
226
- const expiredCount = decision.runProbationExpiry ? await expireMemoryEntries(input.channelDir, now) : 0;
227
- const [cachedMemory, currentHistory] = await loadFiles();
228
- // `loadFiles`'s cached read predates the expiry write above, so a fresh read is needed
229
- // whenever expiry actually changed the file; otherwise the cache is still accurate.
230
- const currentMemory = expiredCount > 0 ? await readChannelMemory(input.channelDir) : cachedMemory;
231
- const cleanup = decision.runMemoryCleanup
232
- ? await cleanupChannelMemory(options, currentMemory, {
233
- cleanupShrinkGuardMinRatio: input.settings.memoryMaintenance.cleanupShrinkGuardMinRatio,
234
- cleanupShrinkGuardMinChars: input.settings.memoryMaintenance.cleanupShrinkGuardMinChars,
235
- })
236
- : null;
237
- const foldedHistory = decision.runHistoryFolding ? await foldChannelHistory(options, currentHistory) : false;
238
- await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
239
- ...current,
240
- lastStructuralMaintenanceAt: formatLocalTime(now),
241
- failureBackoffUntil: null,
242
- }));
243
- await appendJobReviewLog(input.channelDir, input.channelId, "structural-maintenance-job", {
244
- correlationId,
245
- actions: [
246
- ...(expiredCount > 0 ? [{ target: "MEMORY.md", action: "expire", entries: expiredCount }] : []),
247
- ...(cleanup?.rewritten
248
- ? [{ target: "MEMORY.md", action: "rewrite", droppedEntryIds: cleanup.droppedEntryIds }]
249
- : []),
250
- ...(foldedHistory ? [{ target: "HISTORY.md", action: "rewrite" }] : []),
251
- ],
252
- }, now);
253
- return ran("structural-maintenance");
254
- }
255
- catch (error) {
256
- await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
257
- ...current,
258
- failureBackoffUntil: backoffUntil(now, input.settings.memoryMaintenance),
259
- }));
260
- const result = failed("structural-maintenance", error);
261
- await appendJobReviewLog(input.channelDir, input.channelId, "structural-maintenance-job", { error: result.error, skipped: [{ target: "structural-maintenance", reason: "failed" }] }, now);
262
- return result;
263
- }
264
- });
265
- }
@@ -1,57 +0,0 @@
1
- export type MemoryEntryKind = "fact" | "preference" | "decision" | "constraint" | "open-loop" | "lesson";
2
- export type MemorySourceType = "user" | "agent" | "repo" | "tool" | "web" | "legacy";
3
- export type MemoryEntryStatus = "active" | "superseded" | "invalidated" | "forgotten";
4
- export type MemoryEntryNecessity = "low" | "medium" | "high";
5
- export interface MemoryWriteMetadataInput {
6
- kind?: MemoryEntryKind;
7
- sourceType?: MemorySourceType;
8
- sourceCorrelationId?: string;
9
- necessity?: MemoryEntryNecessity;
10
- /**
11
- * Probationary write deadline (spec 037, D6/D7): `undefined` leaves any existing value alone,
12
- * a string sets/renews it, `null` explicitly clears it (promotion to durable). Distinct from
13
- * `undefined` because "keep previous" and "durable now" are different intents — a durable
14
- * supersede replacing a probationary entry in place must clear it, not silently inherit it.
15
- */
16
- probationUntil?: string | null;
17
- }
18
- export interface MemoryEntryMetadata {
19
- id: string;
20
- kind: MemoryEntryKind;
21
- sourceEntryIds: string[];
22
- sourceCorrelationIds: string[];
23
- sourceType: MemorySourceType;
24
- necessity?: MemoryEntryNecessity;
25
- createdAt: string;
26
- updatedAt: string;
27
- status: MemoryEntryStatus;
28
- sectionHeading: string;
29
- contentHash: string;
30
- recallCount: number;
31
- lastRecalledAt?: string;
32
- queryFingerprints: string[];
33
- recallByDay: Record<string, number>;
34
- /** Set only while this entry is on probation (spec 037, D7); absent = durable. */
35
- probationUntil?: string;
36
- }
37
- export interface MemoryMetadataFile {
38
- schemaVersion: 1;
39
- updatedAt: string;
40
- entries: Record<string, MemoryEntryMetadata>;
41
- }
42
- export interface MetadataEntryView {
43
- id: string;
44
- content: string;
45
- sectionHeading: string;
46
- timestamp?: string;
47
- }
48
- export interface MemoryMetadataUpdate {
49
- id: string;
50
- status?: MemoryEntryStatus;
51
- metadata?: MemoryWriteMetadataInput;
52
- sourceEntryIds?: string[];
53
- }
54
- export declare function getMemoryMetadataPath(channelDir: string): string;
55
- export declare function readMemoryMetadata(channelDir: string): Promise<MemoryMetadataFile>;
56
- export declare function syncMemoryMetadata(channelDir: string, activeEntries: MetadataEntryView[], updates?: MemoryMetadataUpdate[], timestamp?: string): Promise<MemoryMetadataFile>;
57
- export declare function recordMemoryRecall(channelDir: string, entryIds: string[], query: string, timestamp?: string): Promise<void>;
@@ -1,142 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { join } from "node:path";
3
- import { writeFileAtomically } from "../shared/atomic-file.js";
4
- import { readOptionalTextFile } from "../shared/fs-utils.js";
5
- import { formatLocalTime, localDayKey, parseLocalTime } from "../shared/local-time.js";
6
- import { createSerialQueue } from "../shared/serial-queue.js";
7
- const metadataQueue = createSerialQueue();
8
- function contentHash(content) {
9
- return createHash("sha256").update(content.normalize("NFKC").replace(/\s+/g, " ").trim()).digest("hex");
10
- }
11
- function inferKind(sectionHeading) {
12
- const section = sectionHeading.toLowerCase();
13
- if (section.includes("preference"))
14
- return "preference";
15
- if (section.includes("decision"))
16
- return "decision";
17
- if (section.includes("constraint"))
18
- return "constraint";
19
- if (section.includes("open loop") || section.includes("ongoing"))
20
- return "open-loop";
21
- if (section.includes("lesson") || section.includes("correction"))
22
- return "lesson";
23
- return "fact";
24
- }
25
- function emptyMetadataFile(timestamp) {
26
- return { schemaVersion: 1, updatedAt: timestamp, entries: {} };
27
- }
28
- export function getMemoryMetadataPath(channelDir) {
29
- return join(channelDir, ".memory", "entries.json");
30
- }
31
- export async function readMemoryMetadata(channelDir) {
32
- const timestamp = formatLocalTime();
33
- const raw = await readOptionalTextFile(getMemoryMetadataPath(channelDir));
34
- if (!raw.trim())
35
- return emptyMetadataFile(timestamp);
36
- try {
37
- const parsed = JSON.parse(raw);
38
- if (parsed.schemaVersion === 1 && parsed.entries && typeof parsed.entries === "object")
39
- return parsed;
40
- }
41
- catch {
42
- // Rebuildable from MEMORY.md on the next reconciliation.
43
- }
44
- return emptyMetadataFile(timestamp);
45
- }
46
- export async function syncMemoryMetadata(channelDir, activeEntries, updates = [], timestamp = formatLocalTime()) {
47
- const path = getMemoryMetadataPath(channelDir);
48
- return metadataQueue.run(path, async () => {
49
- const current = await readMemoryMetadata(channelDir);
50
- const entries = { ...current.entries };
51
- const updatesById = new Map(updates.map((update) => [update.id, update]));
52
- const activeIds = new Set(activeEntries.map((entry) => entry.id));
53
- for (const entry of activeEntries) {
54
- const previous = entries[entry.id];
55
- const update = updatesById.get(entry.id);
56
- const hint = update?.metadata;
57
- entries[entry.id] = {
58
- id: entry.id,
59
- kind: hint?.kind ?? previous?.kind ?? inferKind(entry.sectionHeading),
60
- sourceEntryIds: Array.from(new Set([...(previous?.sourceEntryIds ?? []), ...(update?.sourceEntryIds ?? [])])),
61
- sourceCorrelationIds: Array.from(new Set([
62
- ...(previous?.sourceCorrelationIds ?? []),
63
- ...(hint?.sourceCorrelationId ? [hint.sourceCorrelationId] : []),
64
- ])),
65
- sourceType: hint?.sourceType ?? previous?.sourceType ?? "legacy",
66
- necessity: hint?.necessity ?? previous?.necessity,
67
- createdAt: previous?.createdAt ?? entry.timestamp ?? timestamp,
68
- updatedAt: update || previous?.contentHash !== contentHash(entry.content) ? timestamp : previous.updatedAt,
69
- status: "active",
70
- sectionHeading: entry.sectionHeading,
71
- contentHash: contentHash(entry.content),
72
- recallCount: previous?.recallCount ?? 0,
73
- lastRecalledAt: previous?.lastRecalledAt,
74
- queryFingerprints: previous?.queryFingerprints ?? [],
75
- recallByDay: previous?.recallByDay ?? {},
76
- probationUntil: hint?.probationUntil === null ? undefined : (hint?.probationUntil ?? previous?.probationUntil),
77
- };
78
- }
79
- for (const update of updates) {
80
- if (!update.status || update.status === "active" || activeIds.has(update.id))
81
- continue;
82
- const previous = entries[update.id];
83
- if (previous)
84
- entries[update.id] = { ...previous, status: update.status, updatedAt: timestamp };
85
- }
86
- for (const [id, entry] of Object.entries(entries)) {
87
- if (entry.status === "active" && !activeIds.has(id) && !updatesById.has(id)) {
88
- entries[id] = { ...entry, status: "invalidated", updatedAt: timestamp };
89
- }
90
- }
91
- // `updatedAt` is per-entry and only advances when a field actually changes (see above), so
92
- // a byte-identical `entries` map means this call had nothing new to record — a bare
93
- // reconcile pass over an unchanged file should not cost an atomic write every turn.
94
- if (JSON.stringify(entries) === JSON.stringify(current.entries)) {
95
- return current;
96
- }
97
- const next = { schemaVersion: 1, updatedAt: timestamp, entries };
98
- await writeFileAtomically(path, `${JSON.stringify(next, null, 2)}\n`);
99
- return next;
100
- });
101
- }
102
- export async function recordMemoryRecall(channelDir, entryIds, query, timestamp = formatLocalTime()) {
103
- if (entryIds.length === 0)
104
- return;
105
- const path = getMemoryMetadataPath(channelDir);
106
- await metadataQueue.run(path, async () => {
107
- const current = await readMemoryMetadata(channelDir);
108
- const fingerprint = createHash("sha256")
109
- .update(query.normalize("NFKC").replace(/\s+/g, " ").trim().toLowerCase())
110
- .digest("hex")
111
- .slice(0, 16);
112
- const timestampMs = parseLocalTime(timestamp) ?? Date.now();
113
- const day = localDayKey(new Date(timestampMs));
114
- const cutoffDate = new Date(timestampMs);
115
- cutoffDate.setDate(cutoffDate.getDate() - 89);
116
- const cutoffDay = localDayKey(cutoffDate);
117
- let changed = false;
118
- for (const id of new Set(entryIds)) {
119
- const entry = current.entries[id];
120
- if (!entry || entry.status !== "active")
121
- continue;
122
- const fingerprints = Array.from(new Set([...entry.queryFingerprints, fingerprint])).slice(-32);
123
- const recallByDay = Object.fromEntries(Object.entries(entry.recallByDay ?? {}).filter(([recordedDay]) => recordedDay >= cutoffDay));
124
- current.entries[id] = {
125
- ...entry,
126
- recallCount: entry.recallCount + 1,
127
- lastRecalledAt: timestamp,
128
- queryFingerprints: fingerprints,
129
- recallByDay: { ...recallByDay, [day]: (recallByDay[day] ?? 0) + 1 },
130
- // Being recalled at all is the evidence a probationary entry needs to earn its
131
- // permanent place (spec 037, D7) — this write was already happening on every
132
- // recall, so promotion rides along for free.
133
- probationUntil: undefined,
134
- };
135
- changed = true;
136
- }
137
- if (!changed)
138
- return;
139
- current.updatedAt = timestamp;
140
- await writeFileAtomically(path, `${JSON.stringify(current, null, 2)}\n`);
141
- });
142
- }
@@ -1,17 +0,0 @@
1
- import { readMemoryMetadata } from "./metadata.js";
2
- /**
3
- * How long a probationary memory entry survives without being recalled (spec 037, D7/D8).
4
- * A code constant, not a setting: the durable/probation split is an algorithm parameter, same
5
- * class as `minMemoryAutoWriteConfidence` before it (spec 035's `RETIRED_SETTINGS_KEYS`).
6
- */
7
- export declare const MEMORY_PROBATION_DAYS = 30;
8
- export declare function probationDeadline(now?: Date): string;
9
- /** Active entries whose probation lapsed. */
10
- export declare function collectExpiredEntryIds(metadata: Awaited<ReturnType<typeof readMemoryMetadata>>, now?: Date): string[];
11
- /**
12
- * Evict every expired entry via `invalidate`, never `forget` (spec 037, D8): probation lapsing
13
- * means "not needed right now", not "must never be written again" — a tombstone would permanently
14
- * block the same fact from being relearned later, which is the wrong failure mode for a
15
- * confidence-gated background write.
16
- */
17
- export declare function expireMemoryEntries(channelDir: string, now?: Date): Promise<number>;
@@ -1,44 +0,0 @@
1
- import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
2
- import { applyChannelMemoryOps } from "./files.js";
3
- import { readMemoryMetadata } from "./metadata.js";
4
- /**
5
- * How long a probationary memory entry survives without being recalled (spec 037, D7/D8).
6
- * A code constant, not a setting: the durable/probation split is an algorithm parameter, same
7
- * class as `minMemoryAutoWriteConfidence` before it (spec 035's `RETIRED_SETTINGS_KEYS`).
8
- */
9
- export const MEMORY_PROBATION_DAYS = 30;
10
- export function probationDeadline(now = new Date()) {
11
- return formatLocalTime(new Date(now.getTime() + MEMORY_PROBATION_DAYS * 24 * 60 * 60 * 1000));
12
- }
13
- function isPast(value, nowMs) {
14
- if (!value)
15
- return false;
16
- const ms = parseLocalTime(value);
17
- return ms !== undefined && ms <= nowMs;
18
- }
19
- /** Active entries whose probation lapsed. */
20
- export function collectExpiredEntryIds(metadata, now = new Date()) {
21
- const nowMs = now.getTime();
22
- return Object.values(metadata.entries)
23
- .filter((entry) => entry.status === "active" && isPast(entry.probationUntil, nowMs))
24
- .map((entry) => entry.id);
25
- }
26
- /**
27
- * Evict every expired entry via `invalidate`, never `forget` (spec 037, D8): probation lapsing
28
- * means "not needed right now", not "must never be written again" — a tombstone would permanently
29
- * block the same fact from being relearned later, which is the wrong failure mode for a
30
- * confidence-gated background write.
31
- */
32
- export async function expireMemoryEntries(channelDir, now = new Date()) {
33
- const metadata = await readMemoryMetadata(channelDir);
34
- const expiredIds = collectExpiredEntryIds(metadata, now);
35
- if (expiredIds.length === 0)
36
- return 0;
37
- const ops = expiredIds.map((targetId) => ({
38
- op: "invalidate",
39
- targetId,
40
- reason: "probation expired without being recalled",
41
- }));
42
- const result = await applyChannelMemoryOps(channelDir, ops, formatLocalTime(now));
43
- return result.invalidated;
44
- }
@@ -1,38 +0,0 @@
1
- export type MemoryPromotionTarget = "channel-memory";
2
- export interface MemoryPromotionCandidate {
3
- target: MemoryPromotionTarget;
4
- op: "add" | "supersede" | "invalidate";
5
- targetId?: string;
6
- content?: string;
7
- kind: "fact" | "preference" | "decision" | "constraint" | "open-loop" | "lesson";
8
- confidence: number;
9
- reason: string;
10
- necessity: "low" | "medium" | "high";
11
- }
12
- export declare const DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE = 0.85;
13
- /**
14
- * Confidence bar for a `necessity: "medium"` candidate to enter the durable file at all — as a
15
- * probationary entry, not permanently (spec 037, D6). Higher than the durable bar: "not
16
- * necessary but useful" needs more certainty to earn a slot than "necessary".
17
- */
18
- export declare const MEMORY_PROBATION_WRITE_CONFIDENCE = 0.9;
19
- /** Per consolidation run, how many probationary entries may be written (spec 037, D6). */
20
- export declare const MAX_PROBATION_WRITES_PER_RUN = 5;
21
- export type MemoryWriteTier = "durable" | "probationary";
22
- /**
23
- * Classify a memory candidate into a write tier, or `undefined` to reject it.
24
- *
25
- * `necessity` (would future turns break without this?) and `confidence` (how sure is the
26
- * model?) are orthogonal axes. The gate used to AND them at the strictest tier, which meant a
27
- * new employee's day-to-day operating knowledge — almost all "medium" necessity — could never
28
- * be written at all (spec 037 background, L1). Splitting into two tiers lets medium-necessity,
29
- * high-confidence material in on probation: it must be *used* once (a recall) to become durable,
30
- * or it expires (`src/memory/probation.ts`). This keeps the durable bar exactly as strict as
31
- * before — `high` + 0.85 is unchanged — while giving genuinely useful-but-not-critical knowledge
32
- * a path in.
33
- *
34
- * `supersede`/`invalidate` can never land on probation: a durable entry must only be overwritten
35
- * or removed by something at least as durable, or the overwrite/removal itself could silently
36
- * expire and resurrect the stale content it was meant to replace.
37
- */
38
- export declare function classifyMemoryWrite(candidate: MemoryPromotionCandidate, durableThreshold?: number, probationThreshold?: number): MemoryWriteTier | undefined;
@@ -1,36 +0,0 @@
1
- export const DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE = 0.85;
2
- /**
3
- * Confidence bar for a `necessity: "medium"` candidate to enter the durable file at all — as a
4
- * probationary entry, not permanently (spec 037, D6). Higher than the durable bar: "not
5
- * necessary but useful" needs more certainty to earn a slot than "necessary".
6
- */
7
- export const MEMORY_PROBATION_WRITE_CONFIDENCE = 0.9;
8
- /** Per consolidation run, how many probationary entries may be written (spec 037, D6). */
9
- export const MAX_PROBATION_WRITES_PER_RUN = 5;
10
- /**
11
- * Classify a memory candidate into a write tier, or `undefined` to reject it.
12
- *
13
- * `necessity` (would future turns break without this?) and `confidence` (how sure is the
14
- * model?) are orthogonal axes. The gate used to AND them at the strictest tier, which meant a
15
- * new employee's day-to-day operating knowledge — almost all "medium" necessity — could never
16
- * be written at all (spec 037 background, L1). Splitting into two tiers lets medium-necessity,
17
- * high-confidence material in on probation: it must be *used* once (a recall) to become durable,
18
- * or it expires (`src/memory/probation.ts`). This keeps the durable bar exactly as strict as
19
- * before — `high` + 0.85 is unchanged — while giving genuinely useful-but-not-critical knowledge
20
- * a path in.
21
- *
22
- * `supersede`/`invalidate` can never land on probation: a durable entry must only be overwritten
23
- * or removed by something at least as durable, or the overwrite/removal itself could silently
24
- * expire and resurrect the stale content it was meant to replace.
25
- */
26
- export function classifyMemoryWrite(candidate, durableThreshold = DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE, probationThreshold = MEMORY_PROBATION_WRITE_CONFIDENCE) {
27
- const hasPayload = candidate.op === "invalidate" ? Boolean(candidate.targetId) : Boolean(candidate.content?.trim());
28
- if (!hasPayload)
29
- return undefined;
30
- if (candidate.necessity === "high" && candidate.confidence >= durableThreshold)
31
- return "durable";
32
- if (candidate.op === "add" && candidate.necessity === "medium" && candidate.confidence >= probationThreshold) {
33
- return "probationary";
34
- }
35
- return undefined;
36
- }
@@ -1,59 +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 MemoryCandidate, type MemoryCandidateStore } from "./candidates.js";
4
- export interface RecallRequest {
5
- query: string;
6
- channelId?: string;
7
- workspaceDir: string;
8
- channelDir: string;
9
- allowedSources?: MemoryCandidate["source"][];
10
- excludedCandidateIds?: string[];
11
- maxCandidates: number;
12
- maxInjected: number;
13
- maxChars: number;
14
- /**
15
- * Runtime hard cap in prompt units for the automatic turn context (spec 026 §5.3);
16
- * whichever of chars/units binds first clips. Omitted for explicit searches, which
17
- * budget in characters only.
18
- */
19
- maxUnits?: number;
20
- rerankWithModel: boolean | "auto";
21
- model: Model<Api>;
22
- resolveApiKey: (model: Model<Api>) => Promise<string>;
23
- candidateStore?: MemoryCandidateStore;
24
- /**
25
- * The previous user turn, offered as scoring-only fallback context for a deictic follow-up
26
- * ("那个方案后来怎么定的?") whose own tokens cannot clear the evidence bar. Never enters the
27
- * prompt or the recall query fingerprint — only `query` does.
28
- */
29
- contextQuery?: string;
30
- }
31
- export interface RecalledMemory {
32
- id: string;
33
- entryId?: string;
34
- source: MemoryCandidate["source"];
35
- path: string;
36
- title: string;
37
- content: string;
38
- score: number;
39
- }
40
- export interface RecallResult {
41
- items: RecalledMemory[];
42
- renderedText: string;
43
- }
44
- /** Automatic-context share for relevant memory recall (spec 026 §5.3). */
45
- export declare const MEMORY_RECALL_MAX_UNITS = 1800;
46
- /** The most recent user turn, with injected memory/context wrappers stripped (see `transcript.ts`). */
47
- export declare function findPreviousUserText(messages: AgentMessage[]): string | undefined;
48
- export declare function tokenizeRecallText(text: string): string[];
49
- /**
50
- * Age-bucketed recency boost (≤1 day / ≤7 days / ≤30 days / older), scaled by `weights` — the
51
- * bucket shape is shared with `session-search.ts`'s scoring, but the two scoring systems live on
52
- * different magnitudes, so each caller supplies its own weights rather than sharing a fixed scale.
53
- */
54
- export declare function recencyBoostByAge(timestamp: string | undefined, weights: {
55
- day: number;
56
- week: number;
57
- month: number;
58
- }): number;
59
- export declare function recallRelevantMemory(request: RecallRequest): Promise<RecallResult>;