@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.
- package/README.en.md +250 -0
- package/README.md +3 -1
- package/dist/agent/channel-runner.d.ts +59 -2
- package/dist/agent/channel-runner.js +177 -76
- package/dist/agent/job-manager.d.ts +76 -21
- package/dist/agent/job-manager.js +447 -63
- package/dist/agent/maintenance-context.js +4 -5
- package/dist/agent/prompt/manifest.d.ts +0 -2
- package/dist/agent/prompt/manifest.js +2 -3
- package/dist/agent/prompt/sections.js +3 -3
- package/dist/agent/session-events.js +4 -8
- package/dist/agent/turn-prompt.d.ts +7 -7
- package/dist/agent/turn-prompt.js +6 -9
- package/dist/agent/types.d.ts +12 -0
- package/dist/agent/types.js +1 -0
- package/dist/channel/channel-context.d.ts +13 -0
- package/dist/channel/channel-context.js +21 -1
- package/dist/commands/catalog.js +47 -20
- package/dist/memory/commands.d.ts +8 -0
- package/dist/memory/commands.js +113 -148
- package/dist/memory/index-budget.d.ts +27 -0
- package/dist/memory/index-budget.js +99 -0
- package/dist/memory/journal.d.ts +20 -0
- package/dist/memory/journal.js +78 -0
- package/dist/memory/lifecycle.d.ts +9 -15
- package/dist/memory/lifecycle.js +55 -145
- package/dist/memory/maintenance-gates.d.ts +13 -47
- package/dist/memory/maintenance-gates.js +13 -92
- package/dist/memory/maintenance-state.d.ts +10 -16
- package/dist/memory/maintenance-state.js +12 -59
- package/dist/memory/maintenance-tuning.d.ts +7 -27
- package/dist/memory/maintenance-tuning.js +11 -28
- package/dist/memory/migrate.d.ts +15 -0
- package/dist/memory/migrate.js +364 -0
- package/dist/memory/reflect-job.d.ts +43 -0
- package/dist/memory/reflect-job.js +117 -0
- package/dist/memory/reflect.d.ts +52 -0
- package/dist/memory/reflect.js +313 -0
- package/dist/memory/render.d.ts +19 -0
- package/dist/memory/render.js +35 -0
- package/dist/memory/review-log.d.ts +2 -1
- package/dist/memory/scheduler.d.ts +2 -3
- package/dist/memory/scheduler.js +14 -49
- package/dist/memory/search.d.ts +35 -0
- package/dist/memory/search.js +297 -0
- package/dist/memory/session-search.js +1 -1
- package/dist/memory/store.d.ts +108 -0
- package/dist/memory/store.js +418 -0
- package/dist/memory/task-digest.d.ts +2 -2
- package/dist/memory/task-digest.js +29 -36
- package/dist/memory/tombstones.d.ts +0 -11
- package/dist/memory/tombstones.js +6 -37
- package/dist/memory/transcript.js +12 -5
- package/dist/playbooks/agent-delegation.md +37 -9
- package/dist/playbooks/background-jobs.md +1 -1
- package/dist/playbooks/event-scheduling.md +6 -2
- package/dist/playbooks/memory-and-learning.md +36 -12
- package/dist/playbooks/outbound-media.md +1 -1
- package/dist/playbooks/runtime-orientation.md +9 -8
- package/dist/playbooks/task-loop.md +110 -0
- package/dist/runtime/bootstrap.d.ts +3 -3
- package/dist/runtime/bootstrap.js +66 -41
- package/dist/runtime/events.d.ts +9 -0
- package/dist/runtime/events.js +43 -4
- package/dist/runtime/task-commands.d.ts +14 -15
- package/dist/runtime/task-commands.js +249 -485
- package/dist/runtime/task-driver.d.ts +41 -29
- package/dist/runtime/task-driver.js +170 -317
- package/dist/runtime/task-migration.d.ts +34 -30
- package/dist/runtime/task-migration.js +229 -183
- package/dist/runtime/task-wake.d.ts +6 -3
- package/dist/runtime/task-wake.js +26 -19
- package/dist/settings.d.ts +0 -29
- package/dist/settings.js +12 -35
- package/dist/shared/markdown-sections.d.ts +0 -1
- package/dist/shared/markdown-sections.js +0 -3
- package/dist/subagents/discovery.d.ts +2 -2
- package/dist/subagents/discovery.js +21 -10
- package/dist/subagents/external/progress-tail.js +6 -1
- package/dist/subagents/external/run.js +1 -0
- package/dist/subagents/runs.d.ts +19 -2
- package/dist/subagents/runs.js +73 -4
- package/dist/subagents/tool.d.ts +10 -8
- package/dist/subagents/tool.js +55 -94
- package/dist/tasks/brief.d.ts +17 -0
- package/dist/tasks/brief.js +57 -0
- package/dist/tasks/budget.d.ts +26 -0
- package/dist/tasks/budget.js +59 -0
- package/dist/tasks/cycle.d.ts +48 -0
- package/dist/tasks/cycle.js +94 -0
- package/dist/tasks/frontmatter.d.ts +73 -0
- package/dist/tasks/frontmatter.js +175 -0
- package/dist/tasks/ledger.d.ts +66 -106
- package/dist/tasks/ledger.js +90 -546
- package/dist/tasks/log.d.ts +88 -0
- package/dist/tasks/log.js +97 -0
- package/dist/tasks/rounds.d.ts +41 -0
- package/dist/tasks/rounds.js +53 -0
- package/dist/tasks/session-path.d.ts +9 -0
- package/dist/tasks/session-path.js +16 -0
- package/dist/tasks/steer.d.ts +8 -0
- package/dist/tasks/steer.js +79 -0
- package/dist/tasks/store.d.ts +60 -35
- package/dist/tasks/store.js +166 -107
- package/dist/tasks/ticket.d.ts +102 -0
- package/dist/tasks/ticket.js +209 -0
- package/dist/tasks/verification.d.ts +47 -0
- package/dist/tasks/verification.js +60 -1
- package/dist/tools/index.d.ts +13 -4
- package/dist/tools/index.js +5 -10
- package/dist/tools/memory-manage.d.ts +6 -16
- package/dist/tools/memory-manage.js +108 -129
- package/dist/tools/presentation.js +2 -1
- package/dist/tools/registry.d.ts +11 -2
- package/dist/tools/registry.js +17 -6
- package/dist/tools/subagent-manage.d.ts +0 -9
- package/dist/tools/subagent-manage.js +8 -17
- package/dist/tools/task-manage/create.js +2 -2
- package/dist/tools/task-manage/lifecycle.d.ts +9 -4
- package/dist/tools/task-manage/lifecycle.js +136 -188
- package/dist/tools/task-manage/log-view.d.ts +8 -0
- package/dist/tools/task-manage/log-view.js +24 -0
- package/dist/tools/task-manage/schema.d.ts +38 -14
- package/dist/tools/task-manage/schema.js +46 -27
- package/dist/tools/task-manage/shared.d.ts +35 -31
- package/dist/tools/task-manage/shared.js +130 -141
- package/dist/tools/task-manage/step-end.d.ts +11 -0
- package/dist/tools/task-manage/step-end.js +134 -0
- package/dist/tools/task-manage/types.d.ts +23 -32
- package/dist/tools/task-manage.d.ts +4 -3
- package/dist/tools/task-manage.js +30 -15
- package/dist/tools/tool-details.d.ts +1 -1
- package/dist/tui/app.js +0 -2
- package/examples/sub-agents/README.md +54 -38
- package/examples/sub-agents/builder-hard.md +21 -12
- package/examples/sub-agents/builder.md +24 -16
- package/examples/sub-agents/explorer.md +17 -15
- package/examples/sub-agents/git-committer.md +8 -6
- package/examples/sub-agents/planner.md +17 -16
- package/examples/sub-agents/reviewer.md +11 -9
- package/examples/sub-agents/verifier.md +22 -16
- package/examples/sub-agents/worker.md +22 -6
- package/package.json +1 -1
- package/dist/agent/effect-ledger.d.ts +0 -32
- package/dist/agent/effect-ledger.js +0 -89
- package/dist/memory/bootstrap.d.ts +0 -17
- package/dist/memory/bootstrap.js +0 -120
- package/dist/memory/candidates.d.ts +0 -26
- package/dist/memory/candidates.js +0 -202
- package/dist/memory/consolidation.d.ts +0 -54
- package/dist/memory/consolidation.js +0 -292
- package/dist/memory/extraction.d.ts +0 -54
- package/dist/memory/extraction.js +0 -240
- package/dist/memory/files.d.ts +0 -71
- package/dist/memory/files.js +0 -419
- package/dist/memory/maintenance-jobs.d.ts +0 -41
- package/dist/memory/maintenance-jobs.js +0 -265
- package/dist/memory/metadata.d.ts +0 -57
- package/dist/memory/metadata.js +0 -142
- package/dist/memory/probation.d.ts +0 -17
- package/dist/memory/probation.js +0 -44
- package/dist/memory/promotion.d.ts +0 -38
- package/dist/memory/promotion.js +0 -36
- package/dist/memory/recall.d.ts +0 -59
- package/dist/memory/recall.js +0 -746
- package/dist/memory/session.d.ts +0 -24
- package/dist/memory/session.js +0 -273
- package/dist/playbooks/task-driving.md +0 -92
- package/dist/playbooks/task-planning.md +0 -58
- package/dist/tasks/control.d.ts +0 -56
- package/dist/tasks/control.js +0 -169
- package/dist/tasks/transitions.d.ts +0 -16
- package/dist/tasks/transitions.js +0 -48
- package/dist/tools/task-manage/verification.d.ts +0 -19
- package/dist/tools/task-manage/verification.js +0 -91
- package/examples/sub-agents/documenter.md +0 -50
- package/examples/sub-agents/log-sifter.md +0 -47
- package/examples/sub-agents/scout.md +0 -34
|
@@ -1,292 +0,0 @@
|
|
|
1
|
-
import { getLatestCompactionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { formatLocalTime } from "../shared/local-time.js";
|
|
3
|
-
import { splitH2Sections } from "../shared/markdown-sections.js";
|
|
4
|
-
import { clipText } from "../shared/text-utils.js";
|
|
5
|
-
import { runMemoryExtraction, toMemoryOp } from "./extraction.js";
|
|
6
|
-
import { appendChannelHistoryArchive, appendChannelHistoryBlock, applyChannelMemoryOps, parseChannelMemoryEntries, rewriteChannelHistory, rewriteChannelMemory, } from "./files.js";
|
|
7
|
-
import { readMemoryMetadata } from "./metadata.js";
|
|
8
|
-
import { classifyMemoryWrite, DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE, MAX_PROBATION_WRITES_PER_RUN, } from "./promotion.js";
|
|
9
|
-
import { MEMORY_INPUT_SAFETY_RULES } from "./prompt-safety.js";
|
|
10
|
-
import { runSidecarTask } from "./sidecar-worker.js";
|
|
11
|
-
import { hasMeaningfulExchange, sanitizeMessagesForMemory } from "./transcript.js";
|
|
12
|
-
const INLINE_TRANSCRIPT_MAX_CHARS = 28_000;
|
|
13
|
-
const MEMORY_CLEANUP_LENGTH_THRESHOLD = 5_000;
|
|
14
|
-
const MEMORY_UPDATE_BLOCK_THRESHOLD = 4;
|
|
15
|
-
const HISTORY_LENGTH_THRESHOLD = 8_000;
|
|
16
|
-
const HISTORY_BLOCK_THRESHOLD = 5;
|
|
17
|
-
const HISTORY_RECENT_BLOCKS_TO_KEEP = 3;
|
|
18
|
-
const INLINE_CONSOLIDATION_TIMEOUT_MS = 20_000;
|
|
19
|
-
const MEMORY_CLEANUP_TIMEOUT_MS = 120_000;
|
|
20
|
-
const MEMORY_CLEANUP_INPUT_MAX_CHARS = 24_000;
|
|
21
|
-
const HISTORY_FOLDING_TIMEOUT_MS = 120_000;
|
|
22
|
-
const MEMORY_CLEANUP_SYSTEM_PROMPT = `You are rewriting a Pipiclaw channel MEMORY.md file.
|
|
23
|
-
|
|
24
|
-
Return Markdown only. Do not use code fences.
|
|
25
|
-
|
|
26
|
-
Goals:
|
|
27
|
-
${MEMORY_INPUT_SAFETY_RULES}
|
|
28
|
-
- Keep only durable and useful channel memory.
|
|
29
|
-
- Remove outdated entries, duplicates, verbose phrasing, transient working state, temporary debugging observations, and completed worklog.
|
|
30
|
-
- Organize the result with stable sections where relevant.
|
|
31
|
-
- Prefer concise bullets over prose.
|
|
32
|
-
- Remove content that is clearly transient session-state and belongs in SESSION.md instead.
|
|
33
|
-
- Do not preserve minute-level current task progress unless it is a durable decision, constraint, user preference, or medium-horizon open loop.
|
|
34
|
-
- Preserve the top-level "# Channel Memory" heading.
|
|
35
|
-
- Every retained bullet must preserve its original <!--id:m-*--> comment exactly.
|
|
36
|
-
- Do not invent ids, duplicate ids, prose instructions, or content outside H2 sections.
|
|
37
|
-
|
|
38
|
-
Suggested sections:
|
|
39
|
-
- ## Identity / Participants
|
|
40
|
-
- ## Preferences
|
|
41
|
-
- ## Ongoing Work
|
|
42
|
-
- ## Constraints
|
|
43
|
-
- ## Decisions
|
|
44
|
-
- ## Open Loops
|
|
45
|
-
|
|
46
|
-
Omit empty sections.`;
|
|
47
|
-
const HISTORY_FOLDING_SYSTEM_PROMPT = `You are folding older HISTORY.md blocks for Pipiclaw.
|
|
48
|
-
|
|
49
|
-
Return Markdown only. Do not use code fences.
|
|
50
|
-
|
|
51
|
-
Goals:
|
|
52
|
-
${MEMORY_INPUT_SAFETY_RULES}
|
|
53
|
-
- Compress older history blocks into one concise summary block.
|
|
54
|
-
- Keep important decisions, milestones, and unresolved outcomes.
|
|
55
|
-
- Remove redundancy and transcript-like detail.
|
|
56
|
-
- Preserve a chronological narrative at a high level.`;
|
|
57
|
-
function usageContextFor(channelId, correlationId) {
|
|
58
|
-
return channelId ? { channelId, correlationId } : undefined;
|
|
59
|
-
}
|
|
60
|
-
function normalizeText(text) {
|
|
61
|
-
return text.replace(/\r/g, "").trim();
|
|
62
|
-
}
|
|
63
|
-
function isMessage(entry) {
|
|
64
|
-
return entry.type === "message";
|
|
65
|
-
}
|
|
66
|
-
function entriesAfterLatestCompactionBoundary(entries) {
|
|
67
|
-
const latestCompaction = getLatestCompactionEntry(entries);
|
|
68
|
-
if (!latestCompaction)
|
|
69
|
-
return entries;
|
|
70
|
-
const boundaryIndex = entries.findIndex((entry) => entry.id === latestCompaction.firstKeptEntryId);
|
|
71
|
-
return boundaryIndex >= 0 ? entries.slice(boundaryIndex) : entries;
|
|
72
|
-
}
|
|
73
|
-
function extractMessagesFromSessionEntries(entries) {
|
|
74
|
-
return entries.filter(isMessage).map((entry) => entry.message);
|
|
75
|
-
}
|
|
76
|
-
function countMatchingSectionHeadings(content, prefix) {
|
|
77
|
-
return splitH2Sections(content).filter((section) => section.heading.startsWith(prefix)).length;
|
|
78
|
-
}
|
|
79
|
-
export function shouldCleanupChannelMemory(currentMemory) {
|
|
80
|
-
return (currentMemory.length >= MEMORY_CLEANUP_LENGTH_THRESHOLD ||
|
|
81
|
-
countMatchingSectionHeadings(currentMemory, "Update ") >= MEMORY_UPDATE_BLOCK_THRESHOLD);
|
|
82
|
-
}
|
|
83
|
-
export function shouldFoldChannelHistory(currentHistory) {
|
|
84
|
-
const sections = splitH2Sections(currentHistory);
|
|
85
|
-
return ((currentHistory.length >= HISTORY_LENGTH_THRESHOLD || sections.length >= HISTORY_BLOCK_THRESHOLD) &&
|
|
86
|
-
sections.length > HISTORY_RECENT_BLOCKS_TO_KEEP);
|
|
87
|
-
}
|
|
88
|
-
export function getStructuralMaintenanceStats(currentMemory, currentHistory) {
|
|
89
|
-
return {
|
|
90
|
-
memoryCleanupNeeded: shouldCleanupChannelMemory(currentMemory),
|
|
91
|
-
historyFoldingNeeded: shouldFoldChannelHistory(currentHistory),
|
|
92
|
-
hasMemoryContent: currentMemory.replace(/^# Channel Memory\s*/i, "").trim().length > 0,
|
|
93
|
-
hasHistoryContent: currentHistory.replace(/^# Channel History\s*/i, "").trim().length > 0,
|
|
94
|
-
};
|
|
95
|
-
}
|
|
96
|
-
async function runWorkerPrompt(name, model, resolveApiKey, systemPrompt, prompt, timeoutMs, usageContext) {
|
|
97
|
-
const result = await runSidecarTask({
|
|
98
|
-
name,
|
|
99
|
-
model,
|
|
100
|
-
resolveApiKey,
|
|
101
|
-
systemPrompt,
|
|
102
|
-
prompt,
|
|
103
|
-
timeoutMs,
|
|
104
|
-
usageContext,
|
|
105
|
-
parse: (text) => text.trim(),
|
|
106
|
-
});
|
|
107
|
-
return result.output;
|
|
108
|
-
}
|
|
109
|
-
export async function runInlineConsolidation(options) {
|
|
110
|
-
const mode = options.mode ?? "boundary";
|
|
111
|
-
const sourceEntries = options.sourceWindow?.entries ?? entriesAfterLatestCompactionBoundary(options.sessionEntries ?? []);
|
|
112
|
-
const relevantMessages = options.sourceWindow?.messages ??
|
|
113
|
-
(sourceEntries.length > 0 ? extractMessagesFromSessionEntries(sourceEntries) : options.messages);
|
|
114
|
-
if (!hasMeaningfulExchange(sanitizeMessagesForMemory(relevantMessages))) {
|
|
115
|
-
return {
|
|
116
|
-
skipped: true,
|
|
117
|
-
appendedMemoryEntries: 0,
|
|
118
|
-
appendedDurableEntries: 0,
|
|
119
|
-
appendedProbationaryEntries: 0,
|
|
120
|
-
appendedHistoryBlock: false,
|
|
121
|
-
rejectedMemoryOps: [],
|
|
122
|
-
};
|
|
123
|
-
}
|
|
124
|
-
const correlationId = options.sourceWindow?.windowId ?? options.usageCorrelationId;
|
|
125
|
-
const response = await runMemoryExtraction({
|
|
126
|
-
name: "memory-inline-consolidation",
|
|
127
|
-
channelId: options.channelId,
|
|
128
|
-
channelDir: options.channelDir,
|
|
129
|
-
messages: relevantMessages,
|
|
130
|
-
model: options.model,
|
|
131
|
-
resolveApiKey: options.resolveApiKey,
|
|
132
|
-
timeoutMs: INLINE_CONSOLIDATION_TIMEOUT_MS,
|
|
133
|
-
transcriptMaxChars: INLINE_TRANSCRIPT_MAX_CHARS,
|
|
134
|
-
// Idle passes never write HISTORY.md; only real boundaries summarize the chunk.
|
|
135
|
-
includeHistoryBlock: mode === "boundary",
|
|
136
|
-
usageContext: usageContextFor(options.channelId, correlationId),
|
|
137
|
-
});
|
|
138
|
-
const timestamp = formatLocalTime();
|
|
139
|
-
// The same bar the growth review applies. Consolidation used to write whatever the model
|
|
140
|
-
// returned, which is how transient state reached durable memory: the strictest reviewer
|
|
141
|
-
// was gated behind a keyword scan while the ungated paths wrote freely. Rejected material
|
|
142
|
-
// is not lost — historyBlock and cold storage still carry it.
|
|
143
|
-
//
|
|
144
|
-
// Two tiers (spec 037, D6): durable is unlimited, exactly as before; probationary is capped
|
|
145
|
-
// per run so a single talkative window cannot flood MEMORY.md with unconfirmed entries.
|
|
146
|
-
// Overflow beyond the cap is rejected, not deferred — the next idle window gets its own
|
|
147
|
-
// extraction pass and its own cap.
|
|
148
|
-
const threshold = options.minAutoWriteConfidence ?? DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE;
|
|
149
|
-
const durableCandidates = [];
|
|
150
|
-
const probationaryCandidates = [];
|
|
151
|
-
const rejectedMemoryOps = [];
|
|
152
|
-
for (const candidate of response.memoryOps) {
|
|
153
|
-
const tier = classifyMemoryWrite(candidate, threshold);
|
|
154
|
-
if (tier === "durable")
|
|
155
|
-
durableCandidates.push(candidate);
|
|
156
|
-
else if (tier === "probationary")
|
|
157
|
-
probationaryCandidates.push(candidate);
|
|
158
|
-
else
|
|
159
|
-
rejectedMemoryOps.push(candidate);
|
|
160
|
-
}
|
|
161
|
-
const acceptedProbationary = probationaryCandidates.slice(0, MAX_PROBATION_WRITES_PER_RUN);
|
|
162
|
-
rejectedMemoryOps.push(...probationaryCandidates.slice(MAX_PROBATION_WRITES_PER_RUN));
|
|
163
|
-
let appliedMemoryOps = 0;
|
|
164
|
-
if (durableCandidates.length > 0 || acceptedProbationary.length > 0) {
|
|
165
|
-
const sourceEntryIds = options.sourceWindow?.entries.map((entry) => entry.id) ?? [];
|
|
166
|
-
const ops = [
|
|
167
|
-
...durableCandidates.map((candidate) => toMemoryOp(candidate, { sourceEntryIds, correlationId }, "durable")),
|
|
168
|
-
...acceptedProbationary.map((candidate) => toMemoryOp(candidate, { sourceEntryIds, correlationId }, "probationary")),
|
|
169
|
-
];
|
|
170
|
-
const applied = await applyChannelMemoryOps(options.channelDir, ops, timestamp);
|
|
171
|
-
appliedMemoryOps = applied.added + applied.superseded + applied.invalidated + applied.downgradedToAdd;
|
|
172
|
-
}
|
|
173
|
-
if (mode === "boundary" && response.historyBlock.trim()) {
|
|
174
|
-
await appendChannelHistoryBlock(options.channelDir, {
|
|
175
|
-
timestamp,
|
|
176
|
-
content: response.historyBlock,
|
|
177
|
-
});
|
|
178
|
-
}
|
|
179
|
-
return {
|
|
180
|
-
skipped: false,
|
|
181
|
-
appendedMemoryEntries: appliedMemoryOps,
|
|
182
|
-
appendedDurableEntries: durableCandidates.length,
|
|
183
|
-
appendedProbationaryEntries: acceptedProbationary.length,
|
|
184
|
-
appendedHistoryBlock: mode === "boundary" && response.historyBlock.trim().length > 0,
|
|
185
|
-
rejectedMemoryOps,
|
|
186
|
-
};
|
|
187
|
-
}
|
|
188
|
-
export class MemoryCleanupRejectedError extends Error {
|
|
189
|
-
constructor(reason) {
|
|
190
|
-
super(reason);
|
|
191
|
-
this.name = "MemoryCleanupRejectedError";
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
// Guard against a cleanup pass that catastrophically drops content (e.g. a truncated
|
|
195
|
-
// or malformed LLM response). Backups exist too, but refusing the write avoids
|
|
196
|
-
// clobbering good memory in the first place.
|
|
197
|
-
function isCleanupResultTooSmall(currentMemory, nextMemory, guard) {
|
|
198
|
-
const before = normalizeText(currentMemory);
|
|
199
|
-
const after = normalizeText(nextMemory);
|
|
200
|
-
const beforeEntries = parseChannelMemoryEntries(before).length;
|
|
201
|
-
const afterEntries = parseChannelMemoryEntries(after).length;
|
|
202
|
-
if (beforeEntries > 0 && afterEntries === 0)
|
|
203
|
-
return true;
|
|
204
|
-
// Entry-count guard applies at every file size. The char threshold below exists so a tiny
|
|
205
|
-
// file is not judged on byte ratio, but "four short Update blocks" is exactly the shape
|
|
206
|
-
// cleanup fires on and it sits under that threshold — letting the char escape short-circuit
|
|
207
|
-
// the entry guard left the most common cleanup input completely unprotected.
|
|
208
|
-
if (beforeEntries >= 4 && afterEntries * 2 < beforeEntries)
|
|
209
|
-
return true;
|
|
210
|
-
if (before.length < Math.max(0, guard.cleanupShrinkGuardMinChars))
|
|
211
|
-
return false;
|
|
212
|
-
return after.length < before.length * Math.max(0, Math.min(1, guard.cleanupShrinkGuardMinRatio));
|
|
213
|
-
}
|
|
214
|
-
function validateCleanupSchema(currentMemory, nextMemory, mustKeepIds) {
|
|
215
|
-
if (!/^# Channel Memory(?:\s|$)/.test(nextMemory.trimStart())) {
|
|
216
|
-
return 'cleanup output must start with "# Channel Memory"';
|
|
217
|
-
}
|
|
218
|
-
const originalIds = new Set(parseChannelMemoryEntries(currentMemory).map((entry) => entry.id));
|
|
219
|
-
const entries = parseChannelMemoryEntries(nextMemory);
|
|
220
|
-
const ids = new Set();
|
|
221
|
-
for (const entry of entries) {
|
|
222
|
-
if (!originalIds.has(entry.id))
|
|
223
|
-
return `cleanup output invented unknown entry id ${entry.id}`;
|
|
224
|
-
if (ids.has(entry.id))
|
|
225
|
-
return `cleanup output duplicated entry id ${entry.id}`;
|
|
226
|
-
ids.add(entry.id);
|
|
227
|
-
}
|
|
228
|
-
const missing = mustKeepIds.filter((id) => !ids.has(id));
|
|
229
|
-
if (missing.length > 0)
|
|
230
|
-
return `cleanup output dropped user-saved entries: ${missing.join(", ")}`;
|
|
231
|
-
return null;
|
|
232
|
-
}
|
|
233
|
-
export async function cleanupChannelMemory(options, currentMemory, guard) {
|
|
234
|
-
if (!shouldCleanupChannelMemory(currentMemory)) {
|
|
235
|
-
return { rewritten: false, droppedEntryIds: [] };
|
|
236
|
-
}
|
|
237
|
-
const metadata = await readMemoryMetadata(options.channelDir);
|
|
238
|
-
const beforeEntries = parseChannelMemoryEntries(currentMemory);
|
|
239
|
-
const mustKeepIds = beforeEntries
|
|
240
|
-
.map((entry) => entry.id)
|
|
241
|
-
.filter((id) => metadata.entries[id]?.sourceType === "user");
|
|
242
|
-
const prompt = [
|
|
243
|
-
mustKeepIds.length > 0
|
|
244
|
-
? `These entries were saved on the user's explicit instruction and MUST appear verbatim in the output: ${mustKeepIds.join(", ")}`
|
|
245
|
-
: "",
|
|
246
|
-
`Current MEMORY.md:\n${clipText(currentMemory, MEMORY_CLEANUP_INPUT_MAX_CHARS, { headRatio: 0.5 })}`,
|
|
247
|
-
]
|
|
248
|
-
.filter(Boolean)
|
|
249
|
-
.join("\n\n");
|
|
250
|
-
const nextMemory = await runWorkerPrompt("memory-cleanup", options.model, options.resolveApiKey, MEMORY_CLEANUP_SYSTEM_PROMPT, prompt, MEMORY_CLEANUP_TIMEOUT_MS, usageContextFor(options.channelId, options.usageCorrelationId));
|
|
251
|
-
const schemaError = validateCleanupSchema(currentMemory, nextMemory, mustKeepIds);
|
|
252
|
-
if (schemaError) {
|
|
253
|
-
throw new MemoryCleanupRejectedError(`${schemaError}. Retry cleanup while preserving the MEMORY.md schema and ids.`);
|
|
254
|
-
}
|
|
255
|
-
if (guard && isCleanupResultTooSmall(currentMemory, nextMemory, guard)) {
|
|
256
|
-
throw new MemoryCleanupRejectedError("cleanup result shrank below the configured guard threshold");
|
|
257
|
-
}
|
|
258
|
-
const afterIds = new Set(parseChannelMemoryEntries(nextMemory).map((entry) => entry.id));
|
|
259
|
-
const droppedEntryIds = beforeEntries.map((entry) => entry.id).filter((id) => !afterIds.has(id));
|
|
260
|
-
await rewriteChannelMemory(options.channelDir, nextMemory);
|
|
261
|
-
return { rewritten: true, droppedEntryIds };
|
|
262
|
-
}
|
|
263
|
-
export async function foldChannelHistory(options, currentHistory) {
|
|
264
|
-
if (!shouldFoldChannelHistory(currentHistory)) {
|
|
265
|
-
return false;
|
|
266
|
-
}
|
|
267
|
-
const sections = splitH2Sections(currentHistory);
|
|
268
|
-
const olderSections = sections.slice(0, -HISTORY_RECENT_BLOCKS_TO_KEEP);
|
|
269
|
-
const recentSections = sections.slice(-HISTORY_RECENT_BLOCKS_TO_KEEP);
|
|
270
|
-
const renderedOlder = olderSections.map((section) => `## ${section.heading}\n\n${section.content}`).join("\n\n");
|
|
271
|
-
// Preserve the raw blocks before folding turns them lossy, so nothing is
|
|
272
|
-
// permanently blurred by repeated folds.
|
|
273
|
-
await appendChannelHistoryArchive(options.channelDir, {
|
|
274
|
-
timestamp: formatLocalTime(),
|
|
275
|
-
content: renderedOlder,
|
|
276
|
-
});
|
|
277
|
-
const prompt = `Older history blocks to fold:
|
|
278
|
-
${renderedOlder}`;
|
|
279
|
-
const foldedSummary = await runWorkerPrompt("history-folding", options.model, options.resolveApiKey, HISTORY_FOLDING_SYSTEM_PROMPT, prompt, HISTORY_FOLDING_TIMEOUT_MS, usageContextFor(options.channelId, options.usageCorrelationId));
|
|
280
|
-
const foldedHeading = `## Folded History Through ${olderSections[olderSections.length - 1]?.heading ?? formatLocalTime()}`;
|
|
281
|
-
const rebuiltHistory = [
|
|
282
|
-
"# Channel History",
|
|
283
|
-
"",
|
|
284
|
-
foldedHeading,
|
|
285
|
-
"",
|
|
286
|
-
normalizeText(foldedSummary),
|
|
287
|
-
"",
|
|
288
|
-
...recentSections.flatMap((section) => [`## ${section.heading}`, "", normalizeText(section.content), ""]),
|
|
289
|
-
].join("\n");
|
|
290
|
-
await rewriteChannelHistory(options.channelDir, rebuiltHistory);
|
|
291
|
-
return true;
|
|
292
|
-
}
|
|
@@ -1,54 +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 MemoryOp } from "./files.js";
|
|
4
|
-
import { type MemoryEntryKind } from "./metadata.js";
|
|
5
|
-
import type { MemoryPromotionCandidate, MemoryWriteTier } from "./promotion.js";
|
|
6
|
-
export interface MemoryExtractionPromptOptions {
|
|
7
|
-
includeHistoryBlock: boolean;
|
|
8
|
-
}
|
|
9
|
-
export declare function buildMemoryExtractionSystemPrompt(options: MemoryExtractionPromptOptions): string;
|
|
10
|
-
export interface MemoryExtractionResult {
|
|
11
|
-
memoryOps: MemoryPromotionCandidate[];
|
|
12
|
-
historyBlock: string;
|
|
13
|
-
discarded: Array<{
|
|
14
|
-
content: string;
|
|
15
|
-
reason: string;
|
|
16
|
-
}>;
|
|
17
|
-
}
|
|
18
|
-
export declare function normalizeMemoryEntryKind(value: unknown): MemoryEntryKind;
|
|
19
|
-
export declare function parseMemoryExtractionResult(value: unknown): MemoryExtractionResult;
|
|
20
|
-
/**
|
|
21
|
-
* Turn an accepted candidate into a write op, stamping shared provenance metadata.
|
|
22
|
-
*
|
|
23
|
-
* `tier` stamps `probationUntil` (spec 037, D6/D7): a probationary `add` gets a 30-day deadline
|
|
24
|
-
* that is cancelled the first time the entry is recalled (`recordMemoryRecall`); a durable write
|
|
25
|
-
* stamps `null` to explicitly clear any prior probation — relevant when a durable `supersede`
|
|
26
|
-
* replaces a probationary entry in place (same entry id), which must not silently inherit the
|
|
27
|
-
* old deadline.
|
|
28
|
-
*/
|
|
29
|
-
export declare function toMemoryOp(candidate: MemoryPromotionCandidate, provenance: {
|
|
30
|
-
sourceEntryIds?: string[];
|
|
31
|
-
correlationId?: string;
|
|
32
|
-
}, tier: MemoryWriteTier): MemoryOp;
|
|
33
|
-
export interface MemoryExtractionRequest extends MemoryExtractionPromptOptions {
|
|
34
|
-
name: string;
|
|
35
|
-
channelId?: string;
|
|
36
|
-
channelDir: string;
|
|
37
|
-
messages: AgentMessage[];
|
|
38
|
-
model: Model<Api>;
|
|
39
|
-
resolveApiKey: (model: Model<Api>) => Promise<string>;
|
|
40
|
-
timeoutMs: number;
|
|
41
|
-
transcriptMaxChars: number;
|
|
42
|
-
usageContext?: {
|
|
43
|
-
channelId: string;
|
|
44
|
-
correlationId?: string;
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Tool output never reaches this prompt: `sanitizeMessagesForMemory` drops every `toolResult`
|
|
49
|
-
* message before serialization (`transcript.ts`), an invariant pinned by
|
|
50
|
-
* `test/memory-transcript.test.ts` ("drops tool results ... before memory workers see them").
|
|
51
|
-
* That is why no additional untrusted-content filter is applied here — a window-level one used to
|
|
52
|
-
* exist and silently discarded every durable write from any tool-using conversation.
|
|
53
|
-
*/
|
|
54
|
-
export declare function runMemoryExtraction(request: MemoryExtractionRequest): Promise<MemoryExtractionResult>;
|
|
@@ -1,240 +0,0 @@
|
|
|
1
|
-
import { serializeConversation } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { parseJsonObject } from "../shared/llm-json.js";
|
|
3
|
-
import { clipText } from "../shared/text-utils.js";
|
|
4
|
-
import { isRecord } from "../shared/type-guards.js";
|
|
5
|
-
import { parseChannelMemoryEntries, readChannelHistory, readChannelMemory, readChannelSession, } from "./files.js";
|
|
6
|
-
import { readMemoryMetadata } from "./metadata.js";
|
|
7
|
-
import { probationDeadline } from "./probation.js";
|
|
8
|
-
import { MEMORY_INPUT_SAFETY_RULES } from "./prompt-safety.js";
|
|
9
|
-
import { tokenizeRecallText } from "./recall.js";
|
|
10
|
-
import { runRetriedSidecarTask } from "./sidecar-worker.js";
|
|
11
|
-
import { sanitizeMessagesForMemory } from "./transcript.js";
|
|
12
|
-
/**
|
|
13
|
-
* The single LLM extraction pass behind every durable-memory writer.
|
|
14
|
-
*
|
|
15
|
-
* Boundary consolidation, idle consolidation, and the growth review used to run three
|
|
16
|
-
* separate prompts with three schemas and three quality bars — and because two of them
|
|
17
|
-
* applied no confidence gate at all, the standard for MEMORY.md was set by whichever
|
|
18
|
-
* writer happened to fire. They now share this prompt, this schema, and (via
|
|
19
|
-
* `classifyMemoryWrite`) the same two-tier bar. Callers still own their own side effects: only
|
|
20
|
-
* boundaries write HISTORY.md.
|
|
21
|
-
*/
|
|
22
|
-
const MEMORY_OPS_RULES = `- memoryOps entries operate on the durable channel MEMORY.md:
|
|
23
|
-
- {"op":"add","content":"...","kind":"fact|preference|decision|constraint|open-loop|lesson"} for a genuinely new durable fact.
|
|
24
|
-
- {"op":"supersede","targetId":"m-xxxx","content":"...","kind":"..."} when new information updates or contradicts an existing entry (use its id).
|
|
25
|
-
- {"op":"invalidate","targetId":"m-xxxx","reason":"..."} when an existing entry is now obsolete or resolved.
|
|
26
|
-
- Only reference targetId values that appear in the current MEMORY.md entries shown below.
|
|
27
|
-
- Durable = stable facts, decisions, preferences, constraints, or medium-horizon open loops.
|
|
28
|
-
- Each content string must be a standalone, keyword-rich sentence fragment suitable for a Markdown bullet (no leading "-"). Write it so future keyword search can find it.
|
|
29
|
-
- Do not add content already present in SESSION.md or MEMORY.md; prefer supersede/invalidate over piling on near-duplicates.
|
|
30
|
-
- Do not promote active execution state, temporary debugging observations, completed worklog, raw transcript quotes, acknowledgements, or formatting instructions.
|
|
31
|
-
- Every memoryOp must carry a calibrated confidence (0.0-1.0) and a necessity of "low", "medium", or "high":
|
|
32
|
-
- "high": a hard constraint or rule — future turns would go wrong or redo work without this entry.
|
|
33
|
-
- "medium": day-to-day operating knowledge of the team/project that is not a hard constraint — who owns what, what a term or shorthand defaults to, a naming or release convention, who has to sign off on something, a contact for a recurring counterpart. Nothing breaks without it, but knowing it clearly saves rework.
|
|
34
|
-
- "low": one-off progress, transient state, or anything recoverable by re-reading a file.
|
|
35
|
-
- Do not pad "high" with material that is only "medium". Do not withhold genuine team/project operating knowledge just because a single missing turn would not break without it — that is exactly what "medium" is for.
|
|
36
|
-
- Empty arrays are correct when nothing should be stored; do not force items in. Put anything you considered and rejected in "discarded".`;
|
|
37
|
-
const HISTORY_BLOCK_RULES = `- historyBlock: concise Markdown summarizing the conversation chunk for later recovery.
|
|
38
|
-
- For any conversation that contains at least one meaningful user request and one meaningful assistant reply, return a non-empty historyBlock with at least one bullet.
|
|
39
|
-
- Prefer short bullets and short paragraphs. historyBlock is not gated by confidence, so it is the safe place for context that is real but not durable.`;
|
|
40
|
-
export function buildMemoryExtractionSystemPrompt(options) {
|
|
41
|
-
const schemaFields = [
|
|
42
|
-
` "memoryOps": [{"op": "add|supersede|invalidate", "targetId": "required for supersede/invalidate", "content": "standalone durable memory bullet without '-'", "kind": "fact|preference|decision|constraint|open-loop|lesson", "confidence": 0.0, "necessity": "low|medium|high", "reason": "why it should or should not be stored"}]`,
|
|
43
|
-
];
|
|
44
|
-
if (options.includeHistoryBlock) {
|
|
45
|
-
schemaFields.push(` "historyBlock": "string"`);
|
|
46
|
-
}
|
|
47
|
-
schemaFields.push(` "discarded": [{"content": "string", "reason": "string"}]`);
|
|
48
|
-
return [
|
|
49
|
-
"You are Pipiclaw's durable memory extraction worker.",
|
|
50
|
-
"",
|
|
51
|
-
"Return strict JSON only. Do not wrap in Markdown fences.",
|
|
52
|
-
"",
|
|
53
|
-
"Output schema:",
|
|
54
|
-
"{",
|
|
55
|
-
schemaFields.join(",\n"),
|
|
56
|
-
"}",
|
|
57
|
-
"",
|
|
58
|
-
"Rules:",
|
|
59
|
-
MEMORY_INPUT_SAFETY_RULES,
|
|
60
|
-
MEMORY_OPS_RULES,
|
|
61
|
-
...(options.includeHistoryBlock ? [HISTORY_BLOCK_RULES] : []),
|
|
62
|
-
].join("\n");
|
|
63
|
-
}
|
|
64
|
-
function normalizeConfidence(value) {
|
|
65
|
-
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0;
|
|
66
|
-
}
|
|
67
|
-
function normalizeNecessity(value) {
|
|
68
|
-
return value === "high" || value === "medium" || value === "low" ? value : "low";
|
|
69
|
-
}
|
|
70
|
-
export function normalizeMemoryEntryKind(value) {
|
|
71
|
-
return value === "preference" ||
|
|
72
|
-
value === "decision" ||
|
|
73
|
-
value === "constraint" ||
|
|
74
|
-
value === "open-loop" ||
|
|
75
|
-
value === "lesson"
|
|
76
|
-
? value
|
|
77
|
-
: "fact";
|
|
78
|
-
}
|
|
79
|
-
function normalizeMemoryCandidate(value) {
|
|
80
|
-
if (!isRecord(value)) {
|
|
81
|
-
return null;
|
|
82
|
-
}
|
|
83
|
-
// `target` is legacy: channel MEMORY.md is the only durable target. Reject an explicit
|
|
84
|
-
// foreign target, but do not require the field.
|
|
85
|
-
if (value.target !== undefined && value.target !== "channel-memory") {
|
|
86
|
-
return null;
|
|
87
|
-
}
|
|
88
|
-
const op = value.op === "supersede" || value.op === "invalidate" ? value.op : "add";
|
|
89
|
-
const targetId = typeof value.targetId === "string" ? value.targetId.trim() : undefined;
|
|
90
|
-
const content = typeof value.content === "string" ? value.content.trim() : undefined;
|
|
91
|
-
if ((op === "invalidate" && !targetId) || (op !== "invalidate" && !content)) {
|
|
92
|
-
return null;
|
|
93
|
-
}
|
|
94
|
-
return {
|
|
95
|
-
target: "channel-memory",
|
|
96
|
-
op,
|
|
97
|
-
targetId,
|
|
98
|
-
content,
|
|
99
|
-
kind: normalizeMemoryEntryKind(value.kind),
|
|
100
|
-
confidence: normalizeConfidence(value.confidence),
|
|
101
|
-
necessity: normalizeNecessity(value.necessity),
|
|
102
|
-
reason: typeof value.reason === "string" ? value.reason.trim() : "",
|
|
103
|
-
};
|
|
104
|
-
}
|
|
105
|
-
export function parseMemoryExtractionResult(value) {
|
|
106
|
-
const record = isRecord(value) ? value : {};
|
|
107
|
-
// `memoryCandidates` is an older field name still emitted by some models.
|
|
108
|
-
const rawMemoryOps = Array.isArray(record.memoryOps)
|
|
109
|
-
? record.memoryOps
|
|
110
|
-
: Array.isArray(record.memoryCandidates)
|
|
111
|
-
? record.memoryCandidates
|
|
112
|
-
: [];
|
|
113
|
-
return {
|
|
114
|
-
memoryOps: rawMemoryOps
|
|
115
|
-
.map(normalizeMemoryCandidate)
|
|
116
|
-
.filter((item) => item !== null),
|
|
117
|
-
historyBlock: typeof record.historyBlock === "string" ? record.historyBlock.trim() : "",
|
|
118
|
-
discarded: Array.isArray(record.discarded)
|
|
119
|
-
? record.discarded
|
|
120
|
-
.filter(isRecord)
|
|
121
|
-
.map((item) => ({
|
|
122
|
-
content: typeof item.content === "string" ? item.content : "",
|
|
123
|
-
reason: typeof item.reason === "string" ? item.reason : "",
|
|
124
|
-
}))
|
|
125
|
-
.filter((item) => item.content.trim() || item.reason.trim())
|
|
126
|
-
: [],
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
/**
|
|
130
|
-
* Turn an accepted candidate into a write op, stamping shared provenance metadata.
|
|
131
|
-
*
|
|
132
|
-
* `tier` stamps `probationUntil` (spec 037, D6/D7): a probationary `add` gets a 30-day deadline
|
|
133
|
-
* that is cancelled the first time the entry is recalled (`recordMemoryRecall`); a durable write
|
|
134
|
-
* stamps `null` to explicitly clear any prior probation — relevant when a durable `supersede`
|
|
135
|
-
* replaces a probationary entry in place (same entry id), which must not silently inherit the
|
|
136
|
-
* old deadline.
|
|
137
|
-
*/
|
|
138
|
-
export function toMemoryOp(candidate, provenance, tier) {
|
|
139
|
-
if (candidate.op === "invalidate") {
|
|
140
|
-
return { op: "invalidate", targetId: candidate.targetId ?? "", reason: candidate.reason };
|
|
141
|
-
}
|
|
142
|
-
const metadata = {
|
|
143
|
-
kind: candidate.kind,
|
|
144
|
-
sourceType: "agent",
|
|
145
|
-
necessity: candidate.necessity,
|
|
146
|
-
sourceCorrelationId: provenance.correlationId,
|
|
147
|
-
probationUntil: tier === "probationary" ? probationDeadline() : null,
|
|
148
|
-
};
|
|
149
|
-
if (candidate.op === "supersede") {
|
|
150
|
-
return {
|
|
151
|
-
op: "supersede",
|
|
152
|
-
targetId: candidate.targetId ?? "",
|
|
153
|
-
content: candidate.content ?? "",
|
|
154
|
-
sourceEntryIds: provenance.sourceEntryIds,
|
|
155
|
-
metadata,
|
|
156
|
-
};
|
|
157
|
-
}
|
|
158
|
-
return {
|
|
159
|
-
op: "add",
|
|
160
|
-
content: candidate.content ?? "",
|
|
161
|
-
sourceEntryIds: provenance.sourceEntryIds,
|
|
162
|
-
metadata,
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
/**
|
|
166
|
-
* Above this many entries, a full-corpus render stops being useful: MEMORY_ENTRIES clips at 8000
|
|
167
|
-
* chars anyway, so the model never sees enough of the tail to consider superseding it. Past the
|
|
168
|
-
* threshold, render only the entries most lexically similar to this window's transcript, plus
|
|
169
|
-
* every user-saved entry regardless of similarity (a user's explicit fact must always be a
|
|
170
|
-
* candidate for supersede, never silently excluded by relevance ranking).
|
|
171
|
-
*/
|
|
172
|
-
const MEMORY_ENTRIES_SIMILARITY_THRESHOLD = 40;
|
|
173
|
-
const MEMORY_ENTRIES_SIMILARITY_TOP_N = 20;
|
|
174
|
-
/**
|
|
175
|
-
* Entries rendered as `id — content` so supersede/invalidate can reference real ids.
|
|
176
|
-
*
|
|
177
|
-
* A lightweight local token-overlap score, not the full recall pipeline — extraction only has a
|
|
178
|
-
* `channelDir`, and reusing `recallRelevantMemory` here would mean threading `workspaceDir`
|
|
179
|
-
* through every consolidation call site just to rank entries already loaded in memory.
|
|
180
|
-
*/
|
|
181
|
-
async function renderSimilarMemoryEntriesForPrompt(channelDir, rawMemory, transcript) {
|
|
182
|
-
const entries = parseChannelMemoryEntries(rawMemory);
|
|
183
|
-
if (entries.length === 0) {
|
|
184
|
-
return "";
|
|
185
|
-
}
|
|
186
|
-
if (entries.length <= MEMORY_ENTRIES_SIMILARITY_THRESHOLD) {
|
|
187
|
-
return entries.map((entry) => `${entry.id} — ${entry.content}`).join("\n");
|
|
188
|
-
}
|
|
189
|
-
const transcriptTokens = new Set(tokenizeRecallText(transcript));
|
|
190
|
-
const scored = entries
|
|
191
|
-
.map((entry) => {
|
|
192
|
-
const entryTokens = tokenizeRecallText(entry.content);
|
|
193
|
-
const overlap = entryTokens.filter((token) => transcriptTokens.has(token)).length;
|
|
194
|
-
return { entry, overlap };
|
|
195
|
-
})
|
|
196
|
-
.sort((a, b) => b.overlap - a.overlap);
|
|
197
|
-
const metadata = await readMemoryMetadata(channelDir);
|
|
198
|
-
const mustKeepIds = new Set(entries.filter((entry) => metadata.entries[entry.id]?.sourceType === "user").map((entry) => entry.id));
|
|
199
|
-
const selectedIds = new Set(scored.slice(0, MEMORY_ENTRIES_SIMILARITY_TOP_N).map(({ entry }) => entry.id));
|
|
200
|
-
for (const id of mustKeepIds)
|
|
201
|
-
selectedIds.add(id);
|
|
202
|
-
const selected = entries.filter((entry) => selectedIds.has(entry.id));
|
|
203
|
-
const note = `[showing ${selected.length} of ${entries.length} entries most relevant to this conversation — not the full file]`;
|
|
204
|
-
return `${note}\n${selected.map((entry) => `${entry.id} — ${entry.content}`).join("\n")}`;
|
|
205
|
-
}
|
|
206
|
-
/**
|
|
207
|
-
* Tool output never reaches this prompt: `sanitizeMessagesForMemory` drops every `toolResult`
|
|
208
|
-
* message before serialization (`transcript.ts`), an invariant pinned by
|
|
209
|
-
* `test/memory-transcript.test.ts` ("drops tool results ... before memory workers see them").
|
|
210
|
-
* That is why no additional untrusted-content filter is applied here — a window-level one used to
|
|
211
|
-
* exist and silently discarded every durable write from any tool-using conversation.
|
|
212
|
-
*/
|
|
213
|
-
export async function runMemoryExtraction(request) {
|
|
214
|
-
const [currentSession, rawMemory, currentHistory] = await Promise.all([
|
|
215
|
-
readChannelSession(request.channelDir),
|
|
216
|
-
readChannelMemory(request.channelDir),
|
|
217
|
-
readChannelHistory(request.channelDir),
|
|
218
|
-
]);
|
|
219
|
-
const transcript = clipText(serializeConversation(sanitizeMessagesForMemory(request.messages)), request.transcriptMaxChars, { headRatio: 0.35 });
|
|
220
|
-
const currentMemory = clipText(await renderSimilarMemoryEntriesForPrompt(request.channelDir, rawMemory, transcript), 8_000, { headRatio: 0.35 });
|
|
221
|
-
const promptSections = [
|
|
222
|
-
`Current SESSION.md:\n${clipText(currentSession, 8_000, { headRatio: 0.35 }) || "(empty)"}`,
|
|
223
|
-
`Current MEMORY.md entries (id — content; reference ids in supersede/invalidate):\n${currentMemory || "(empty)"}`,
|
|
224
|
-
`Channel history file:\n${clipText(currentHistory, 8_000, { headRatio: 0.35 }) || "(empty)"}`,
|
|
225
|
-
`Conversation chunk to persist:\n${transcript || "(empty)"}`,
|
|
226
|
-
];
|
|
227
|
-
const result = await runRetriedSidecarTask({
|
|
228
|
-
name: request.name,
|
|
229
|
-
model: request.model,
|
|
230
|
-
resolveApiKey: request.resolveApiKey,
|
|
231
|
-
systemPrompt: buildMemoryExtractionSystemPrompt({
|
|
232
|
-
includeHistoryBlock: request.includeHistoryBlock,
|
|
233
|
-
}),
|
|
234
|
-
prompt: promptSections.join("\n\n"),
|
|
235
|
-
timeoutMs: request.timeoutMs,
|
|
236
|
-
usageContext: request.usageContext,
|
|
237
|
-
parse: (text) => parseMemoryExtractionResult(parseJsonObject(text)),
|
|
238
|
-
});
|
|
239
|
-
return result.output;
|
|
240
|
-
}
|
package/dist/memory/files.d.ts
DELETED
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
import { type MemoryWriteMetadataInput } from "./metadata.js";
|
|
2
|
-
export declare function generateMemoryEntryId(): string;
|
|
3
|
-
export declare function stripMemoryEntryIdComment(text: string): string;
|
|
4
|
-
export declare function parseUpdateHeadingTimestamp(heading: string): string | undefined;
|
|
5
|
-
export interface ParsedMemoryEntry {
|
|
6
|
-
id: string;
|
|
7
|
-
content: string;
|
|
8
|
-
sectionHeading: string;
|
|
9
|
-
timestamp?: string;
|
|
10
|
-
lineIndex: number;
|
|
11
|
-
hasExplicitId: boolean;
|
|
12
|
-
}
|
|
13
|
-
/** Parse durable MEMORY.md bullet entries with stable ids for op-based edits. */
|
|
14
|
-
export declare function parseChannelMemoryEntries(content: string): ParsedMemoryEntry[];
|
|
15
|
-
export type MemoryOp = {
|
|
16
|
-
op: "add";
|
|
17
|
-
content: string;
|
|
18
|
-
sourceEntryIds?: string[];
|
|
19
|
-
metadata?: MemoryWriteMetadataInput;
|
|
20
|
-
} | {
|
|
21
|
-
op: "supersede";
|
|
22
|
-
targetId: string;
|
|
23
|
-
content: string;
|
|
24
|
-
sourceEntryIds?: string[];
|
|
25
|
-
metadata?: MemoryWriteMetadataInput;
|
|
26
|
-
} | {
|
|
27
|
-
op: "invalidate";
|
|
28
|
-
targetId: string;
|
|
29
|
-
reason?: string;
|
|
30
|
-
} | {
|
|
31
|
-
op: "forget";
|
|
32
|
-
targetId: string;
|
|
33
|
-
reason?: string;
|
|
34
|
-
sourceEntryIds?: string[];
|
|
35
|
-
};
|
|
36
|
-
export interface ApplyMemoryOpsResult {
|
|
37
|
-
added: number;
|
|
38
|
-
superseded: number;
|
|
39
|
-
invalidated: number;
|
|
40
|
-
downgradedToAdd: number;
|
|
41
|
-
missingTarget: number;
|
|
42
|
-
forgotten: number;
|
|
43
|
-
blockedByPolicy: number;
|
|
44
|
-
blockedByTombstone: number;
|
|
45
|
-
skippedDuplicate: number;
|
|
46
|
-
/** Existing entries whose probation was cleared by a durable duplicate `add` (spec 037, D7). */
|
|
47
|
-
promotedFromProbation: number;
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* Apply add/supersede/invalidate ops to a channel MEMORY.md with line-level edits,
|
|
51
|
-
* preserving any surrounding markdown. Missing supersede targets downgrade to add;
|
|
52
|
-
* missing invalidate targets are skipped. Mutating edits are backed up first.
|
|
53
|
-
*/
|
|
54
|
-
export declare function applyChannelMemoryOps(channelDir: string, ops: MemoryOp[], timestamp?: string): Promise<ApplyMemoryOpsResult>;
|
|
55
|
-
export interface HistoryBlock {
|
|
56
|
-
timestamp: string;
|
|
57
|
-
content: string;
|
|
58
|
-
}
|
|
59
|
-
export declare function getChannelMemoryPath(channelDir: string): string;
|
|
60
|
-
export declare function getChannelHistoryPath(channelDir: string): string;
|
|
61
|
-
export declare function getChannelSessionPath(channelDir: string): string;
|
|
62
|
-
export declare function ensureChannelMemoryFilesSync(channelDir: string): void;
|
|
63
|
-
export declare function readChannelMemory(channelDir: string): Promise<string>;
|
|
64
|
-
export declare function readChannelHistory(channelDir: string): Promise<string>;
|
|
65
|
-
export declare function readChannelSession(channelDir: string): Promise<string>;
|
|
66
|
-
export declare function rewriteChannelMemory(channelDir: string, content: string): Promise<void>;
|
|
67
|
-
export declare function rewriteChannelHistory(channelDir: string, content: string): Promise<void>;
|
|
68
|
-
export declare function rewriteChannelSession(channelDir: string, content: string): Promise<void>;
|
|
69
|
-
export declare function getChannelHistoryArchivePath(channelDir: string): string;
|
|
70
|
-
export declare function appendChannelHistoryArchive(channelDir: string, block: HistoryBlock): Promise<void>;
|
|
71
|
-
export declare function appendChannelHistoryBlock(channelDir: string, block: HistoryBlock): Promise<void>;
|