@oyasmi/pipiclaw 0.8.10-beta.6 → 0.8.11-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/dist/agent/channel-runner.d.ts +10 -0
- package/dist/agent/channel-runner.js +56 -27
- package/dist/memory/commands.js +6 -1
- package/dist/memory/consolidation.d.ts +8 -1
- package/dist/memory/consolidation.js +34 -6
- package/dist/memory/extraction.d.ts +11 -3
- package/dist/memory/extraction.js +19 -6
- package/dist/memory/files.d.ts +2 -0
- package/dist/memory/files.js +14 -0
- package/dist/memory/maintenance-gates.d.ts +3 -0
- package/dist/memory/maintenance-gates.js +5 -2
- package/dist/memory/maintenance-jobs.js +19 -2
- package/dist/memory/maintenance-state.d.ts +29 -0
- package/dist/memory/maintenance-state.js +100 -8
- package/dist/memory/metadata.d.ts +9 -0
- package/dist/memory/metadata.js +5 -0
- package/dist/memory/probation.d.ts +21 -0
- package/dist/memory/probation.js +48 -0
- package/dist/memory/promotion.d.ts +26 -1
- package/dist/memory/promotion.js +34 -4
- package/dist/memory/recall.js +38 -19
- package/dist/memory/session-corpus.js +12 -11
- package/dist/memory/session-search.js +25 -6
- package/dist/memory/sidecar-worker.js +2 -0
- package/dist/memory/task-digest.js +6 -0
- package/dist/playbooks/memory-and-learning.md +7 -1
- package/dist/playbooks/task-driving.md +2 -2
- package/dist/playbooks/task-planning.md +14 -0
- package/dist/runtime/bootstrap.js +1 -1
- package/dist/runtime/delivery.js +8 -2
- package/dist/runtime/dingtalk.d.ts +5 -2
- package/dist/runtime/dingtalk.js +6 -39
- package/dist/runtime/store.d.ts +8 -2
- package/dist/runtime/store.js +12 -6
- package/dist/runtime/task-commands.js +15 -1
- package/dist/runtime/task-driver.js +10 -0
- package/dist/security/command-guard.js +51 -17
- package/dist/security/path-guard.js +72 -14
- package/dist/subagents/tool.js +2 -0
- package/dist/tasks/ledger.d.ts +74 -5
- package/dist/tasks/ledger.js +261 -7
- package/dist/tools/memory-manage.js +8 -1
- package/dist/tools/read.js +19 -5
- package/dist/tools/task-manage/lifecycle.js +8 -2
- package/dist/tools/task-manage/schema.d.ts +6 -0
- package/dist/tools/task-manage/schema.js +14 -0
- package/dist/tools/task-manage/shared.js +1 -0
- package/dist/tui/app.js +1 -1
- package/dist/tui/commands.d.ts +1 -1
- package/dist/tui/commands.js +1 -1
- package/dist/tui/turn-controller.d.ts +1 -1
- package/dist/usage/ledger.d.ts +1 -1
- package/dist/usage/ledger.js +47 -22
- package/dist/usage/render.d.ts +1 -1
- package/dist/usage/render.js +8 -6
- package/package.json +6 -6
|
@@ -24,6 +24,7 @@ export declare class ChannelRunner implements AgentRunner {
|
|
|
24
24
|
private readonly memoryLifecycle;
|
|
25
25
|
private readonly ledger;
|
|
26
26
|
private readonly memoryCandidateStore;
|
|
27
|
+
private readonly memoryActivityRecorder;
|
|
27
28
|
private readonly sessionResourceGate;
|
|
28
29
|
private readonly sessionReady;
|
|
29
30
|
private sessionRuntime;
|
|
@@ -88,7 +89,14 @@ export declare class ChannelRunner implements AgentRunner {
|
|
|
88
89
|
*/
|
|
89
90
|
private renderChannelTurnContext;
|
|
90
91
|
private sendCommandReply;
|
|
92
|
+
/**
|
|
93
|
+
* Buffer one activity event. The write itself is batched by the recorder (see
|
|
94
|
+
* `createMemoryActivityRecorder`); `run()` flushes at the end of every turn, which is the
|
|
95
|
+
* point the maintenance gates actually start looking at this state.
|
|
96
|
+
*/
|
|
91
97
|
private recordMemoryActivity;
|
|
98
|
+
/** Best-effort: a lost activity counter delays maintenance, it never breaks a turn. */
|
|
99
|
+
private flushMemoryActivity;
|
|
92
100
|
private requireQueuedMessage;
|
|
93
101
|
private shouldPreserveRawInput;
|
|
94
102
|
/**
|
|
@@ -165,5 +173,7 @@ export declare class ChannelRunner implements AgentRunner {
|
|
|
165
173
|
*/
|
|
166
174
|
private setSessionBaseToolsOverride;
|
|
167
175
|
private subscribeToSessionEvents;
|
|
176
|
+
/** Gated by the same master autonomy switch as task_manage and the TaskDriver. */
|
|
177
|
+
private buildTaskDigestForTurn;
|
|
168
178
|
private buildFirstTurnMemoryBootstrap;
|
|
169
179
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Agent } from "@earendil-works/pi-agent-core";
|
|
2
|
-
import { clampThinkingLevel } from "@earendil-works/pi-ai/compat";
|
|
2
|
+
import { clampThinkingLevel, streamSimple } from "@earendil-works/pi-ai/compat";
|
|
3
3
|
import { AgentSession, AgentSessionRuntime, convertToLlm, createExtensionRuntime, DefaultResourceLoader, SettingsManager as SDKSettingsManager, SessionManager, } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import { mkdir, readFile, writeFile } from "fs/promises";
|
|
5
5
|
import { dirname, join, resolve } from "path";
|
|
@@ -10,7 +10,7 @@ import { createMemoryCandidateStore } from "../memory/candidates.js";
|
|
|
10
10
|
import { handleMemoryCommand } from "../memory/commands.js";
|
|
11
11
|
import { getChannelMemoryPath } from "../memory/files.js";
|
|
12
12
|
import { MemoryLifecycle } from "../memory/lifecycle.js";
|
|
13
|
-
import {
|
|
13
|
+
import { createMemoryActivityRecorder, } from "../memory/maintenance-state.js";
|
|
14
14
|
import { MEMORY_RECALL_MAX_UNITS, recallRelevantMemory } from "../memory/recall.js";
|
|
15
15
|
import { buildTaskDigest, TASK_AGENDA_MAX_UNITS } from "../memory/task-digest.js";
|
|
16
16
|
import { getApiKeyForModel } from "../models/api-keys.js";
|
|
@@ -100,6 +100,10 @@ export class ChannelRunner {
|
|
|
100
100
|
this.settingsManager = new PipiclawSettingsManager(this.appHomeDir);
|
|
101
101
|
this.reportSettingsDiagnostics();
|
|
102
102
|
this.memoryCandidateStore = createMemoryCandidateStore();
|
|
103
|
+
this.memoryActivityRecorder = createMemoryActivityRecorder({
|
|
104
|
+
appHomeDir: this.appHomeDir,
|
|
105
|
+
onError: (channelId, error) => log.logWarning(`[${channelId}] Failed to record memory maintenance state`, errorMessage(error)),
|
|
106
|
+
});
|
|
103
107
|
// The real model/auth runtime is built asynchronously in initializeSession
|
|
104
108
|
// (ModelRuntime.create is async). Until then the agent runs on a placeholder
|
|
105
109
|
// model; initializeSession corrects it before any turn (via sessionReady).
|
|
@@ -114,6 +118,7 @@ export class ChannelRunner {
|
|
|
114
118
|
},
|
|
115
119
|
convertToLlm,
|
|
116
120
|
getApiKey: async () => getApiKeyForModel(this.modelRegistry, this.activeModel),
|
|
121
|
+
streamFn: streamSimple,
|
|
117
122
|
});
|
|
118
123
|
this.memoryLifecycle = new MemoryLifecycle({
|
|
119
124
|
channelId: this.channelId,
|
|
@@ -124,9 +129,7 @@ export class ChannelRunner {
|
|
|
124
129
|
getModel: () => this.session.model ?? this.activeModel,
|
|
125
130
|
resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
|
|
126
131
|
getSessionMemorySettings: () => this.settingsManager.getSessionMemorySettings(),
|
|
127
|
-
recordMemoryActivity: (event) =>
|
|
128
|
-
void this.recordMemoryActivity(event);
|
|
129
|
-
},
|
|
132
|
+
recordMemoryActivity: (event) => this.recordMemoryActivity(event),
|
|
130
133
|
});
|
|
131
134
|
this.sessionResourceGate = new SessionResourceGate(async () => {
|
|
132
135
|
await this.reloadSessionResources();
|
|
@@ -200,6 +203,13 @@ export class ChannelRunner {
|
|
|
200
203
|
// system prompt is what lets every channel in a workspace share one cached prefix.
|
|
201
204
|
channelCapsuleText = this.renderChannelTurnContext();
|
|
202
205
|
promptText = `${channelCapsuleText}\n\n<user_message>\n${promptText}\n</user_message>`;
|
|
206
|
+
// The task digest reads the whole tasks/ directory and depends on nothing the memory
|
|
207
|
+
// work below produces, so it runs alongside the bootstrap and recall rather than
|
|
208
|
+
// queuing behind them. Settled into a result object rather than left as a bare
|
|
209
|
+
// promise: if recall throws first we would otherwise leave a rejection unobserved,
|
|
210
|
+
// which Node's default policy turns into a process exit. Rethrown at the await, so a
|
|
211
|
+
// digest failure still fails the turn exactly as it did when this ran inline.
|
|
212
|
+
const taskDigestPromise = (this.tasksEnabled ? this.buildTaskDigestForTurn() : Promise.resolve("")).then((text) => ({ text }), (error) => ({ error }));
|
|
203
213
|
if (this.firstTurnMemoryBootstrapPending) {
|
|
204
214
|
const bootstrap = await this.buildFirstTurnMemoryBootstrap();
|
|
205
215
|
durableMemoryBootstrapText = bootstrap.renderedText;
|
|
@@ -220,9 +230,12 @@ export class ChannelRunner {
|
|
|
220
230
|
maxUnits: MEMORY_RECALL_MAX_UNITS,
|
|
221
231
|
rerankWithModel: recallSettings.rerankWithModel,
|
|
222
232
|
excludedCandidateIds: bootstrapCandidateIds,
|
|
223
|
-
//
|
|
224
|
-
//
|
|
225
|
-
//
|
|
233
|
+
// `rerankWithModel` is passed through as configured; `shouldUseModelRerank`
|
|
234
|
+
// owns the decision. Under "auto" it reranks whenever the shortlist is
|
|
235
|
+
// over-full *and* the local ranking has no clear winner — script-independent,
|
|
236
|
+
// so a Chinese turn is treated exactly like an English one. That rerank is an
|
|
237
|
+
// LLM call on the critical path of the turn, capped at
|
|
238
|
+
// MEMORY_RECALL_RERANK_TIMEOUT_MS and failing open to the local ranking.
|
|
226
239
|
model: this.session.model ?? this.activeModel,
|
|
227
240
|
resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
|
|
228
241
|
candidateStore: this.memoryCandidateStore,
|
|
@@ -232,18 +245,13 @@ export class ChannelRunner {
|
|
|
232
245
|
promptText = `${recall.renderedText}\n\n${promptText}`;
|
|
233
246
|
}
|
|
234
247
|
}
|
|
235
|
-
|
|
236
|
-
if (
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
maxUnits: TASK_AGENDA_MAX_UNITS,
|
|
243
|
-
});
|
|
244
|
-
if (taskDigestText) {
|
|
245
|
-
promptText = `${taskDigestText}\n\n${promptText}`;
|
|
246
|
-
}
|
|
248
|
+
const taskDigestResult = await taskDigestPromise;
|
|
249
|
+
if (taskDigestResult.error !== undefined) {
|
|
250
|
+
throw taskDigestResult.error;
|
|
251
|
+
}
|
|
252
|
+
taskDigestText = taskDigestResult.text ?? "";
|
|
253
|
+
if (taskDigestText) {
|
|
254
|
+
promptText = `${taskDigestText}\n\n${promptText}`;
|
|
247
255
|
}
|
|
248
256
|
if (durableMemoryBootstrapText) {
|
|
249
257
|
promptText = `${durableMemoryBootstrapText}\n\n${promptText}`;
|
|
@@ -455,6 +463,10 @@ export class ChannelRunner {
|
|
|
455
463
|
log.logInfo(`[${this.channelId}] Actual model: ${responseModel} (configured: ${formatModelReference(currentRunModel)})`);
|
|
456
464
|
}
|
|
457
465
|
}
|
|
466
|
+
// The turn is over, so the channel is about to look idle to the maintenance gates —
|
|
467
|
+
// which is exactly when this state has to be on disk. Everything buffered during the
|
|
468
|
+
// turn lands here in one write.
|
|
469
|
+
await this.flushMemoryActivity();
|
|
458
470
|
// Clear run state
|
|
459
471
|
this.runState.ctx = null;
|
|
460
472
|
this.runState.logCtx = null;
|
|
@@ -528,6 +540,7 @@ export class ChannelRunner {
|
|
|
528
540
|
await this.queueBusyMessage(this.requireQueuedMessage(text, "steer"), userName);
|
|
529
541
|
}
|
|
530
542
|
async flushMemoryForShutdown() {
|
|
543
|
+
await this.flushMemoryActivity();
|
|
531
544
|
await this.memoryLifecycle.flushForShutdown();
|
|
532
545
|
}
|
|
533
546
|
async getMemoryMaintenanceContext() {
|
|
@@ -608,21 +621,26 @@ export class ChannelRunner {
|
|
|
608
621
|
await ctx.flush();
|
|
609
622
|
}
|
|
610
623
|
}
|
|
611
|
-
|
|
624
|
+
/**
|
|
625
|
+
* Buffer one activity event. The write itself is batched by the recorder (see
|
|
626
|
+
* `createMemoryActivityRecorder`); `run()` flushes at the end of every turn, which is the
|
|
627
|
+
* point the maintenance gates actually start looking at this state.
|
|
628
|
+
*/
|
|
629
|
+
recordMemoryActivity(event) {
|
|
612
630
|
const maintenanceSettings = this.settingsManager.getMemoryMaintenanceSettings();
|
|
613
631
|
const eventTime = Date.parse(event.timestamp);
|
|
614
632
|
const eligibleAfter = Number.isFinite(eventTime)
|
|
615
633
|
? new Date(eventTime + Math.max(0, maintenanceSettings.minIdleMinutesBeforeLlmWork) * 60_000).toISOString()
|
|
616
634
|
: undefined;
|
|
635
|
+
this.memoryActivityRecorder.record({ ...event, eligibleAfter });
|
|
636
|
+
}
|
|
637
|
+
/** Best-effort: a lost activity counter delays maintenance, it never breaks a turn. */
|
|
638
|
+
async flushMemoryActivity() {
|
|
617
639
|
try {
|
|
618
|
-
await
|
|
619
|
-
...event,
|
|
620
|
-
eligibleAfter,
|
|
621
|
-
}));
|
|
640
|
+
await this.memoryActivityRecorder.flush(this.channelId);
|
|
622
641
|
}
|
|
623
642
|
catch (error) {
|
|
624
|
-
|
|
625
|
-
log.logWarning(`[${this.channelId}] Failed to record memory maintenance state`, message);
|
|
643
|
+
log.logWarning(`[${this.channelId}] Failed to flush memory maintenance state`, errorMessage(error));
|
|
626
644
|
}
|
|
627
645
|
}
|
|
628
646
|
requireQueuedMessage(text, commandName) {
|
|
@@ -1021,6 +1039,7 @@ export class ChannelRunner {
|
|
|
1021
1039
|
},
|
|
1022
1040
|
convertToLlm,
|
|
1023
1041
|
getApiKey: async () => getApiKeyForModel(this.modelRegistry, this.activeModel),
|
|
1042
|
+
streamFn: streamSimple,
|
|
1024
1043
|
});
|
|
1025
1044
|
this.initializeThinkingLevel(agent, this.activeModel, sessionManager);
|
|
1026
1045
|
const resourceLoader = this.createResourceLoader();
|
|
@@ -1130,6 +1149,16 @@ export class ChannelRunner {
|
|
|
1130
1149
|
});
|
|
1131
1150
|
});
|
|
1132
1151
|
}
|
|
1152
|
+
/** Gated by the same master autonomy switch as task_manage and the TaskDriver. */
|
|
1153
|
+
buildTaskDigestForTurn() {
|
|
1154
|
+
const taskDigestSettings = this.settingsManager.getTaskDigestSettings();
|
|
1155
|
+
return buildTaskDigest({
|
|
1156
|
+
channelDir: this.channelDir,
|
|
1157
|
+
maxTasks: taskDigestSettings.maxTasks,
|
|
1158
|
+
maxChars: taskDigestSettings.maxChars,
|
|
1159
|
+
maxUnits: TASK_AGENDA_MAX_UNITS,
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1133
1162
|
async buildFirstTurnMemoryBootstrap() {
|
|
1134
1163
|
const readOptionalFile = async (path) => {
|
|
1135
1164
|
try {
|
package/dist/memory/commands.js
CHANGED
|
@@ -41,6 +41,9 @@ export async function handleMemoryCommand(options) {
|
|
|
41
41
|
const tombstones = await readMemoryTombstones(options.channelDir);
|
|
42
42
|
const records = Object.values(metadata.entries);
|
|
43
43
|
const active = records.filter((entry) => entry.status === "active");
|
|
44
|
+
const probationary = active
|
|
45
|
+
.filter((entry) => entry.probationUntil)
|
|
46
|
+
.sort((a, b) => (a.probationUntil ?? "").localeCompare(b.probationUntil ?? ""));
|
|
44
47
|
const since = new Date();
|
|
45
48
|
since.setDate(since.getDate() - 29);
|
|
46
49
|
const sinceDay = localDayKey(since);
|
|
@@ -55,6 +58,7 @@ export async function handleMemoryCommand(options) {
|
|
|
55
58
|
"",
|
|
56
59
|
`- Active entries: \`${entries.length}\``,
|
|
57
60
|
`- Metadata records: \`${records.length}\``,
|
|
61
|
+
`- Probationary: \`${probationary.length}\`${probationary.length > 0 ? ` (earliest expiry \`${probationary[0].probationUntil}\`)` : ""}`,
|
|
58
62
|
`- Pending suggestions: \`${pending.length}\``,
|
|
59
63
|
`- Tombstones: \`${tombstones.length}\``,
|
|
60
64
|
`- Total recalls: \`${active.reduce((sum, entry) => sum + entry.recallCount, 0)}\``,
|
|
@@ -75,7 +79,8 @@ export async function handleMemoryCommand(options) {
|
|
|
75
79
|
const visible = entries.slice(0, 50);
|
|
76
80
|
const lines = visible.map((entry) => {
|
|
77
81
|
const record = metadata.entries[entry.id];
|
|
78
|
-
|
|
82
|
+
const probation = record?.probationUntil ? ` (probation until \`${record.probationUntil}\`)` : "";
|
|
83
|
+
return `- \`${entry.id}\` [${record?.kind ?? "fact"}]${probation} ${clipText(entry.content, 180, { headRatio: 1 })}`;
|
|
79
84
|
});
|
|
80
85
|
if (entries.length > visible.length) {
|
|
81
86
|
lines.push(`- ${entries.length - visible.length} more omitted; use \`/memory show <entry-id>\` after narrowing the file.`);
|
|
@@ -21,8 +21,15 @@ export interface ConsolidationRunOptions {
|
|
|
21
21
|
export interface InlineConsolidationResult {
|
|
22
22
|
skipped: boolean;
|
|
23
23
|
appendedMemoryEntries: number;
|
|
24
|
+
/**
|
|
25
|
+
* Ops sent per tier (spec 037, D6), for review-log breakdown. Pre-application tallies — like
|
|
26
|
+
* `rejectedMemoryOps`, these describe what the gate decided, not what ultimately landed after
|
|
27
|
+
* dedup/tombstone checks inside `applyChannelMemoryOps`.
|
|
28
|
+
*/
|
|
29
|
+
appendedDurableEntries: number;
|
|
30
|
+
appendedProbationaryEntries: number;
|
|
24
31
|
appendedHistoryBlock: boolean;
|
|
25
|
-
/** Candidates the confidence gate turned down, surfaced for the review log. */
|
|
32
|
+
/** Candidates the confidence gate turned down (including probation over the per-run cap), surfaced for the review log. */
|
|
26
33
|
rejectedMemoryOps: MemoryPromotionCandidate[];
|
|
27
34
|
}
|
|
28
35
|
export interface StructuralMaintenanceStats {
|
|
@@ -3,7 +3,7 @@ import { formatLocalTime } from "../shared/local-time.js";
|
|
|
3
3
|
import { splitH2Sections } from "../shared/markdown-sections.js";
|
|
4
4
|
import { runMemoryExtraction, toMemoryOp } from "./extraction.js";
|
|
5
5
|
import { appendChannelHistoryArchive, appendChannelHistoryBlock, applyChannelMemoryOps, parseChannelMemoryEntries, rewriteChannelHistory, rewriteChannelMemory, } from "./files.js";
|
|
6
|
-
import { DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE,
|
|
6
|
+
import { classifyMemoryWrite, DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE, MAX_PROBATION_WRITES_PER_RUN, } from "./promotion.js";
|
|
7
7
|
import { MEMORY_INPUT_SAFETY_RULES } from "./prompt-safety.js";
|
|
8
8
|
import { runSidecarTask } from "./sidecar-worker.js";
|
|
9
9
|
import { sanitizeMessagesForMemory } from "./transcript.js";
|
|
@@ -133,7 +133,14 @@ export async function runInlineConsolidation(options) {
|
|
|
133
133
|
const relevantMessages = options.sourceWindow?.messages ??
|
|
134
134
|
(sourceEntries.length > 0 ? extractMessagesFromSessionEntries(sourceEntries) : options.messages);
|
|
135
135
|
if (!hasMeaningfulMessages(sanitizeMessagesForMemory(relevantMessages))) {
|
|
136
|
-
return {
|
|
136
|
+
return {
|
|
137
|
+
skipped: true,
|
|
138
|
+
appendedMemoryEntries: 0,
|
|
139
|
+
appendedDurableEntries: 0,
|
|
140
|
+
appendedProbationaryEntries: 0,
|
|
141
|
+
appendedHistoryBlock: false,
|
|
142
|
+
rejectedMemoryOps: [],
|
|
143
|
+
};
|
|
137
144
|
}
|
|
138
145
|
const correlationId = options.sourceWindow?.windowId ?? options.usageCorrelationId;
|
|
139
146
|
const response = await runMemoryExtraction({
|
|
@@ -154,16 +161,35 @@ export async function runInlineConsolidation(options) {
|
|
|
154
161
|
// returned, which is how transient state reached durable memory: the strictest reviewer
|
|
155
162
|
// was gated behind a keyword scan while the ungated paths wrote freely. Rejected material
|
|
156
163
|
// is not lost — historyBlock and cold storage still carry it.
|
|
164
|
+
//
|
|
165
|
+
// Two tiers (spec 037, D6): durable is unlimited, exactly as before; probationary is capped
|
|
166
|
+
// per run so a single talkative window cannot flood MEMORY.md with unconfirmed entries.
|
|
167
|
+
// Overflow beyond the cap is rejected, not deferred — the next idle window gets its own
|
|
168
|
+
// extraction pass and its own cap.
|
|
157
169
|
const threshold = options.minAutoWriteConfidence ?? DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE;
|
|
158
|
-
const
|
|
170
|
+
const durableCandidates = [];
|
|
171
|
+
const probationaryCandidates = [];
|
|
159
172
|
const rejectedMemoryOps = [];
|
|
160
173
|
for (const candidate of response.memoryOps) {
|
|
161
|
-
(
|
|
174
|
+
const tier = classifyMemoryWrite(candidate, threshold);
|
|
175
|
+
if (tier === "durable")
|
|
176
|
+
durableCandidates.push(candidate);
|
|
177
|
+
else if (tier === "probationary")
|
|
178
|
+
probationaryCandidates.push(candidate);
|
|
179
|
+
else
|
|
180
|
+
rejectedMemoryOps.push(candidate);
|
|
162
181
|
}
|
|
182
|
+
const acceptedProbationary = probationaryCandidates.slice(0, MAX_PROBATION_WRITES_PER_RUN);
|
|
183
|
+
rejectedMemoryOps.push(...probationaryCandidates.slice(MAX_PROBATION_WRITES_PER_RUN));
|
|
163
184
|
let appliedMemoryOps = 0;
|
|
164
|
-
if (
|
|
185
|
+
if ((durableCandidates.length > 0 || acceptedProbationary.length > 0) &&
|
|
186
|
+
!options.sourceWindow?.hasExternalToolContent) {
|
|
165
187
|
const sourceEntryIds = options.sourceWindow?.entries.map((entry) => entry.id) ?? [];
|
|
166
|
-
const
|
|
188
|
+
const ops = [
|
|
189
|
+
...durableCandidates.map((candidate) => toMemoryOp(candidate, { sourceEntryIds, correlationId }, "durable")),
|
|
190
|
+
...acceptedProbationary.map((candidate) => toMemoryOp(candidate, { sourceEntryIds, correlationId }, "probationary")),
|
|
191
|
+
];
|
|
192
|
+
const applied = await applyChannelMemoryOps(options.channelDir, ops, timestamp);
|
|
167
193
|
appliedMemoryOps = applied.added + applied.superseded + applied.invalidated + applied.downgradedToAdd;
|
|
168
194
|
}
|
|
169
195
|
if (mode === "boundary" && response.historyBlock.trim()) {
|
|
@@ -175,6 +201,8 @@ export async function runInlineConsolidation(options) {
|
|
|
175
201
|
return {
|
|
176
202
|
skipped: false,
|
|
177
203
|
appendedMemoryEntries: appliedMemoryOps,
|
|
204
|
+
appendedDurableEntries: durableCandidates.length,
|
|
205
|
+
appendedProbationaryEntries: acceptedProbationary.length,
|
|
178
206
|
appendedHistoryBlock: mode === "boundary" && response.historyBlock.trim().length > 0,
|
|
179
207
|
rejectedMemoryOps,
|
|
180
208
|
};
|
|
@@ -2,7 +2,7 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
|
2
2
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
3
3
|
import { type MemoryOp } from "./files.js";
|
|
4
4
|
import type { MemoryEntryKind } from "./metadata.js";
|
|
5
|
-
import type { MemoryPromotionCandidate } from "./promotion.js";
|
|
5
|
+
import type { MemoryPromotionCandidate, MemoryWriteTier } from "./promotion.js";
|
|
6
6
|
export interface MemoryExtractionPromptOptions {
|
|
7
7
|
includeHistoryBlock: boolean;
|
|
8
8
|
}
|
|
@@ -17,11 +17,19 @@ export interface MemoryExtractionResult {
|
|
|
17
17
|
}
|
|
18
18
|
export declare function normalizeMemoryEntryKind(value: unknown): MemoryEntryKind;
|
|
19
19
|
export declare function parseMemoryExtractionResult(value: unknown): MemoryExtractionResult;
|
|
20
|
-
/**
|
|
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
|
+
*/
|
|
21
29
|
export declare function toMemoryOp(candidate: MemoryPromotionCandidate, provenance: {
|
|
22
30
|
sourceEntryIds?: string[];
|
|
23
31
|
correlationId?: string;
|
|
24
|
-
}): MemoryOp;
|
|
32
|
+
}, tier: MemoryWriteTier): MemoryOp;
|
|
25
33
|
export interface MemoryExtractionRequest extends MemoryExtractionPromptOptions {
|
|
26
34
|
name: string;
|
|
27
35
|
channelId?: string;
|
|
@@ -3,6 +3,7 @@ import { parseJsonObject } from "../shared/llm-json.js";
|
|
|
3
3
|
import { clipText } from "../shared/text-utils.js";
|
|
4
4
|
import { isRecord } from "../shared/type-guards.js";
|
|
5
5
|
import { parseChannelMemoryEntries, readChannelHistory, readChannelMemory, readChannelSession, } from "./files.js";
|
|
6
|
+
import { probationDeadline } from "./probation.js";
|
|
6
7
|
import { MEMORY_INPUT_SAFETY_RULES } from "./prompt-safety.js";
|
|
7
8
|
import { runRetriedSidecarTask } from "./sidecar-worker.js";
|
|
8
9
|
import { sanitizeMessagesForMemory } from "./transcript.js";
|
|
@@ -13,7 +14,7 @@ import { sanitizeMessagesForMemory } from "./transcript.js";
|
|
|
13
14
|
* separate prompts with three schemas and three quality bars — and because two of them
|
|
14
15
|
* applied no confidence gate at all, the standard for MEMORY.md was set by whichever
|
|
15
16
|
* writer happened to fire. They now share this prompt, this schema, and (via
|
|
16
|
-
* `
|
|
17
|
+
* `classifyMemoryWrite`) the same two-tier bar. Callers still own their own side effects: only
|
|
17
18
|
* boundaries write HISTORY.md.
|
|
18
19
|
*/
|
|
19
20
|
const MEMORY_OPS_RULES = `- memoryOps entries operate on the durable channel MEMORY.md:
|
|
@@ -25,9 +26,12 @@ const MEMORY_OPS_RULES = `- memoryOps entries operate on the durable channel MEM
|
|
|
25
26
|
- 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.
|
|
26
27
|
- Do not add content already present in SESSION.md or MEMORY.md; prefer supersede/invalidate over piling on near-duplicates.
|
|
27
28
|
- Do not promote active execution state, temporary debugging observations, completed worklog, raw transcript quotes, acknowledgements, or formatting instructions.
|
|
28
|
-
- Every memoryOp must carry a calibrated confidence (0.0-1.0) and a necessity of "low", "medium", or "high"
|
|
29
|
-
-
|
|
30
|
-
-
|
|
29
|
+
- Every memoryOp must carry a calibrated confidence (0.0-1.0) and a necessity of "low", "medium", or "high":
|
|
30
|
+
- "high": a hard constraint or rule — future turns would go wrong or redo work without this entry.
|
|
31
|
+
- "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.
|
|
32
|
+
- "low": one-off progress, transient state, or anything recoverable by re-reading a file.
|
|
33
|
+
- 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.
|
|
34
|
+
- Empty arrays are correct when nothing should be stored; do not force items in. Put anything you considered and rejected in "discarded".`;
|
|
31
35
|
const HISTORY_BLOCK_RULES = `- historyBlock: concise Markdown summarizing the conversation chunk for later recovery.
|
|
32
36
|
- 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.
|
|
33
37
|
- 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.`;
|
|
@@ -120,8 +124,16 @@ export function parseMemoryExtractionResult(value) {
|
|
|
120
124
|
: [],
|
|
121
125
|
};
|
|
122
126
|
}
|
|
123
|
-
/**
|
|
124
|
-
|
|
127
|
+
/**
|
|
128
|
+
* Turn an accepted candidate into a write op, stamping shared provenance metadata.
|
|
129
|
+
*
|
|
130
|
+
* `tier` stamps `probationUntil` (spec 037, D6/D7): a probationary `add` gets a 30-day deadline
|
|
131
|
+
* that is cancelled the first time the entry is recalled (`recordMemoryRecall`); a durable write
|
|
132
|
+
* stamps `null` to explicitly clear any prior probation — relevant when a durable `supersede`
|
|
133
|
+
* replaces a probationary entry in place (same entry id), which must not silently inherit the
|
|
134
|
+
* old deadline.
|
|
135
|
+
*/
|
|
136
|
+
export function toMemoryOp(candidate, provenance, tier) {
|
|
125
137
|
if (candidate.op === "invalidate") {
|
|
126
138
|
return { op: "invalidate", targetId: candidate.targetId ?? "", reason: candidate.reason };
|
|
127
139
|
}
|
|
@@ -130,6 +142,7 @@ export function toMemoryOp(candidate, provenance) {
|
|
|
130
142
|
sourceType: "agent",
|
|
131
143
|
trust: "inferred",
|
|
132
144
|
sourceCorrelationId: provenance.correlationId,
|
|
145
|
+
probationUntil: tier === "probationary" ? probationDeadline() : null,
|
|
133
146
|
};
|
|
134
147
|
if (candidate.op === "supersede") {
|
|
135
148
|
return {
|
package/dist/memory/files.d.ts
CHANGED
|
@@ -43,6 +43,8 @@ export interface ApplyMemoryOpsResult {
|
|
|
43
43
|
blockedByPolicy: number;
|
|
44
44
|
blockedByTombstone: number;
|
|
45
45
|
skippedDuplicate: number;
|
|
46
|
+
/** Existing entries whose probation was cleared by a durable duplicate `add` (spec 037, D7). */
|
|
47
|
+
promotedFromProbation: number;
|
|
46
48
|
}
|
|
47
49
|
/**
|
|
48
50
|
* Apply add/supersede/invalidate ops to a channel MEMORY.md with line-level edits,
|
package/dist/memory/files.js
CHANGED
|
@@ -141,6 +141,7 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = formatL
|
|
|
141
141
|
blockedByPolicy: 0,
|
|
142
142
|
blockedByTombstone: 0,
|
|
143
143
|
skippedDuplicate: 0,
|
|
144
|
+
promotedFromProbation: 0,
|
|
144
145
|
};
|
|
145
146
|
if (ops.length === 0) {
|
|
146
147
|
return result;
|
|
@@ -158,6 +159,7 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = formatL
|
|
|
158
159
|
const tombstoneHashes = new Set(tombstones.map((tombstone) => tombstone.contentHash));
|
|
159
160
|
const tombstoneSourceIds = new Set(tombstones.flatMap((tombstone) => tombstone.sourceEntryIds ?? []));
|
|
160
161
|
const activeContentHashes = new Set(existingEntries.map((entry) => hashMemoryContent(entry.content)));
|
|
162
|
+
const activeEntryIdByContentHash = new Map(existingEntries.map((entry) => [hashMemoryContent(entry.content), entry.id]));
|
|
161
163
|
const appliedSourceCorrelationIds = new Set(Object.values(currentMetadata.entries).flatMap((entry) => entry.sourceCorrelationIds));
|
|
162
164
|
const removals = new Set();
|
|
163
165
|
const replacements = new Map();
|
|
@@ -184,6 +186,18 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = formatL
|
|
|
184
186
|
const contentHash = hashMemoryContent(op.content);
|
|
185
187
|
if (activeContentHashes.has(contentHash)) {
|
|
186
188
|
result.skippedDuplicate++;
|
|
189
|
+
// A durable write (explicit `probationUntil: null`) restating a fact that is
|
|
190
|
+
// already stored, possibly on probation, is itself evidence the fact matters —
|
|
191
|
+
// promote the existing entry in place (spec 037, D7 path 2). A probationary
|
|
192
|
+
// restatement leaves the existing entry's deadline untouched: seeing the same
|
|
193
|
+
// medium-necessity thing twice does not by itself earn it a permanent slot.
|
|
194
|
+
if (op.metadata?.probationUntil === null) {
|
|
195
|
+
const existingId = activeEntryIdByContentHash.get(contentHash);
|
|
196
|
+
if (existingId) {
|
|
197
|
+
metadataUpdates.push({ id: existingId, metadata: { probationUntil: null } });
|
|
198
|
+
result.promotedFromProbation++;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
187
201
|
continue;
|
|
188
202
|
}
|
|
189
203
|
const id = generateMemoryEntryId();
|
|
@@ -41,6 +41,8 @@ export interface StructuralMaintenanceMaterial {
|
|
|
41
41
|
historyFoldingNeeded: boolean;
|
|
42
42
|
hasMemoryContent: boolean;
|
|
43
43
|
hasHistoryContent: boolean;
|
|
44
|
+
/** Active entries whose probation lapsed or `expiresAt` was reached (spec 037, D8). */
|
|
45
|
+
expiredEntryCount: number;
|
|
44
46
|
}
|
|
45
47
|
export interface StructuralMaintenanceGateInput {
|
|
46
48
|
now: Date;
|
|
@@ -52,6 +54,7 @@ export interface StructuralMaintenanceGateInput {
|
|
|
52
54
|
export interface StructuralMaintenanceGateDecision extends MaintenanceGateDecision {
|
|
53
55
|
runMemoryCleanup: boolean;
|
|
54
56
|
runHistoryFolding: boolean;
|
|
57
|
+
runProbationExpiry: boolean;
|
|
55
58
|
}
|
|
56
59
|
export declare function shouldRunSessionRefresh(input: SessionRefreshGateInput): MaintenanceGateDecision;
|
|
57
60
|
export declare function shouldRunMemoryCheckpoint(input: MemoryCheckpointGateInput): MaintenanceGateDecision;
|
|
@@ -96,6 +96,7 @@ export async function shouldRunStructuralMaintenance(input) {
|
|
|
96
96
|
skipReason,
|
|
97
97
|
runMemoryCleanup: false,
|
|
98
98
|
runHistoryFolding: false,
|
|
99
|
+
runProbationExpiry: false,
|
|
99
100
|
});
|
|
100
101
|
if (input.channelActive) {
|
|
101
102
|
return denyStructural("channel-active");
|
|
@@ -107,12 +108,13 @@ export async function shouldRunStructuralMaintenance(input) {
|
|
|
107
108
|
return denyStructural("backoff-active");
|
|
108
109
|
}
|
|
109
110
|
const material = await input.material();
|
|
110
|
-
|
|
111
|
+
const runProbationExpiry = material.expiredEntryCount > 0;
|
|
112
|
+
if (!material.hasMemoryContent && !material.hasHistoryContent && !runProbationExpiry) {
|
|
111
113
|
return denyStructural("empty-template-files");
|
|
112
114
|
}
|
|
113
115
|
const runMemoryCleanup = material.memoryCleanupNeeded;
|
|
114
116
|
const runHistoryFolding = material.historyFoldingNeeded;
|
|
115
|
-
if (!runMemoryCleanup && !runHistoryFolding) {
|
|
117
|
+
if (!runMemoryCleanup && !runHistoryFolding && !runProbationExpiry) {
|
|
116
118
|
return denyStructural("nothing-to-maintain");
|
|
117
119
|
}
|
|
118
120
|
return {
|
|
@@ -120,5 +122,6 @@ export async function shouldRunStructuralMaintenance(input) {
|
|
|
120
122
|
jobKind,
|
|
121
123
|
runMemoryCleanup,
|
|
122
124
|
runHistoryFolding,
|
|
125
|
+
runProbationExpiry,
|
|
123
126
|
};
|
|
124
127
|
}
|
|
@@ -5,6 +5,8 @@ import { cleanupChannelMemory, foldChannelHistory, getStructuralMaintenanceStats
|
|
|
5
5
|
import { readChannelHistory, readChannelMemory } from "./files.js";
|
|
6
6
|
import { shouldRunMemoryCheckpoint, shouldRunSessionRefresh, shouldRunStructuralMaintenance, } from "./maintenance-gates.js";
|
|
7
7
|
import { readMemoryMaintenanceState, updateMemoryMaintenanceState } from "./maintenance-state.js";
|
|
8
|
+
import { readMemoryMetadata } from "./metadata.js";
|
|
9
|
+
import { collectExpiredEntryIds, expireMemoryEntries } from "./probation.js";
|
|
8
10
|
import { appendMemoryReviewLog } from "./review-log.js";
|
|
9
11
|
import { updateChannelSessionMemory } from "./session.js";
|
|
10
12
|
import { buildIncrementalMemorySourceWindow } from "./source-window.js";
|
|
@@ -222,21 +224,35 @@ export async function runStructuralMaintenanceJob(input) {
|
|
|
222
224
|
const now = input.now ?? new Date();
|
|
223
225
|
const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
|
|
224
226
|
const loadFiles = once(() => Promise.all([readChannelMemory(input.channelDir), readChannelHistory(input.channelDir)]));
|
|
227
|
+
const loadExpiredCount = once(async () => {
|
|
228
|
+
const metadata = await readMemoryMetadata(input.channelDir);
|
|
229
|
+
return collectExpiredEntryIds(metadata, now).length;
|
|
230
|
+
});
|
|
225
231
|
const decision = await shouldRunStructuralMaintenance({
|
|
226
232
|
now,
|
|
227
233
|
state,
|
|
228
234
|
maintenance: input.settings.memoryMaintenance,
|
|
229
235
|
channelActive: input.channelActive,
|
|
230
|
-
material: async () =>
|
|
236
|
+
material: async () => ({
|
|
237
|
+
...getStructuralMaintenanceStats(...(await loadFiles())),
|
|
238
|
+
expiredEntryCount: await loadExpiredCount(),
|
|
239
|
+
}),
|
|
231
240
|
});
|
|
232
241
|
if (!decision.allowed) {
|
|
233
242
|
await appendJobReviewLog(input.channelDir, input.channelId, "structural-maintenance-job", { skipped: [{ target: "structural-maintenance", reason: decision.skipReason }] }, now);
|
|
234
243
|
return skipped(decision.jobKind, decision.skipReason ?? "skipped");
|
|
235
244
|
}
|
|
236
|
-
const [currentMemory, currentHistory] = await loadFiles();
|
|
237
245
|
try {
|
|
238
246
|
const correlationId = `structural-maintenance:${formatLocalTime(now)}`;
|
|
239
247
|
const options = makeRunOptions(input, correlationId);
|
|
248
|
+
// Probation/expiresAt eviction runs first, deterministically, before the LLM cleanup
|
|
249
|
+
// pass sees the file — no point spending a cleanup prompt on entries about to be
|
|
250
|
+
// invalidated (spec 037, D8).
|
|
251
|
+
const expiredCount = decision.runProbationExpiry ? await expireMemoryEntries(input.channelDir, now) : 0;
|
|
252
|
+
const [cachedMemory, currentHistory] = await loadFiles();
|
|
253
|
+
// `loadFiles`'s cached read predates the expiry write above, so a fresh read is needed
|
|
254
|
+
// whenever expiry actually changed the file; otherwise the cache is still accurate.
|
|
255
|
+
const currentMemory = expiredCount > 0 ? await readChannelMemory(input.channelDir) : cachedMemory;
|
|
240
256
|
const cleanedMemory = decision.runMemoryCleanup
|
|
241
257
|
? await cleanupChannelMemory(options, currentMemory, {
|
|
242
258
|
cleanupShrinkGuardMinRatio: input.settings.memoryMaintenance.cleanupShrinkGuardMinRatio,
|
|
@@ -252,6 +268,7 @@ export async function runStructuralMaintenanceJob(input) {
|
|
|
252
268
|
await appendJobReviewLog(input.channelDir, input.channelId, "structural-maintenance-job", {
|
|
253
269
|
correlationId,
|
|
254
270
|
actions: [
|
|
271
|
+
...(expiredCount > 0 ? [{ target: "MEMORY.md", action: "expire", entries: expiredCount }] : []),
|
|
255
272
|
...(cleanedMemory ? [{ target: "MEMORY.md", action: "rewrite" }] : []),
|
|
256
273
|
...(foldedHistory ? [{ target: "HISTORY.md", action: "rewrite" }] : []),
|
|
257
274
|
],
|
|
@@ -25,4 +25,33 @@ export declare function getMemoryMaintenanceStateDir(appHomeDir: string): string
|
|
|
25
25
|
export declare function getMemoryMaintenanceStatePath(appHomeDir: string, channelId: string): string;
|
|
26
26
|
export declare function readMemoryMaintenanceState(appHomeDir: string, channelId: string): Promise<MemoryMaintenanceState>;
|
|
27
27
|
export declare function updateMemoryMaintenanceState(appHomeDir: string, channelId: string, update: (state: MemoryMaintenanceState) => MemoryMaintenanceState): Promise<MemoryMaintenanceState>;
|
|
28
|
+
/** Apply a single activity event. The buffered path folds a whole burst through the same core. */
|
|
28
29
|
export declare function applyMemoryActivityToState(state: MemoryMaintenanceState, event: MemoryActivityEvent): MemoryMaintenanceState;
|
|
30
|
+
/**
|
|
31
|
+
* Buffers activity events and writes them out in batches.
|
|
32
|
+
*
|
|
33
|
+
* Activity is recorded on *every* tool call, and each write used to be a read-modify-write of a
|
|
34
|
+
* JSON file through `writeFileAtomically` — two fsyncs apiece. A thirty-step turn paid that thirty
|
|
35
|
+
* times, on storage whose fsync latency the runtime does not control.
|
|
36
|
+
*
|
|
37
|
+
* Batching is safe because nothing consumes this state promptly: every gate in
|
|
38
|
+
* `maintenance-gates.ts` denies outright while the channel is active, and `eligibleAfter` holds
|
|
39
|
+
* maintenance off for `minIdleMinutesBeforeLlmWork` after that. The scheduler then polls once a
|
|
40
|
+
* minute. So the state only has to be accurate by the time a channel goes *idle* — which is why
|
|
41
|
+
* the runner also flushes explicitly at the end of every turn, on top of the debounce here. The
|
|
42
|
+
* debounce bounds what a crash can lose to a few seconds of counters, never a checkpoint: those
|
|
43
|
+
* are written directly, and the serial queue keeps a flush from reordering against them.
|
|
44
|
+
*/
|
|
45
|
+
export interface MemoryActivityRecorder {
|
|
46
|
+
record(event: MemoryActivityEvent): void;
|
|
47
|
+
/** Write out buffered activity for one channel, or for all of them when `channelId` is omitted. */
|
|
48
|
+
flush(channelId?: string): Promise<void>;
|
|
49
|
+
}
|
|
50
|
+
export declare const DEFAULT_ACTIVITY_FLUSH_DEBOUNCE_MS = 5000;
|
|
51
|
+
export interface CreateMemoryActivityRecorderOptions {
|
|
52
|
+
appHomeDir: string;
|
|
53
|
+
/** Override the flush debounce; tests use a short one. */
|
|
54
|
+
debounceMs?: number;
|
|
55
|
+
onError?: (channelId: string, error: unknown) => void;
|
|
56
|
+
}
|
|
57
|
+
export declare function createMemoryActivityRecorder(options: CreateMemoryActivityRecorderOptions): MemoryActivityRecorder;
|