notesoup 0.0.0-stage → 0.40.0
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/LICENSE +21 -0
- package/README.md +94 -2
- package/dist/src/boot/render.d.ts +16 -0
- package/dist/src/boot/render.js +95 -0
- package/dist/src/boot/snapshot.d.ts +32 -0
- package/dist/src/boot/snapshot.js +36 -0
- package/dist/src/boot/text.d.ts +17 -0
- package/dist/src/boot/text.js +48 -0
- package/dist/src/budget/constants.d.ts +9 -0
- package/dist/src/budget/constants.js +9 -0
- package/dist/src/budget/policy.d.ts +19 -0
- package/dist/src/budget/policy.js +36 -0
- package/dist/src/budget/text.d.ts +8 -0
- package/dist/src/budget/text.js +10 -0
- package/dist/src/claude/helper.d.ts +15 -0
- package/dist/src/claude/helper.js +87 -0
- package/dist/src/dream/doctor.d.ts +2 -0
- package/dist/src/dream/doctor.js +160 -0
- package/dist/src/dream/gates.d.ts +10 -0
- package/dist/src/dream/gates.js +26 -0
- package/dist/src/dream/git.d.ts +21 -0
- package/dist/src/dream/git.js +71 -0
- package/dist/src/dream/jail.d.ts +11 -0
- package/dist/src/dream/jail.js +71 -0
- package/dist/src/dream/lock.d.ts +31 -0
- package/dist/src/dream/lock.js +99 -0
- package/dist/src/dream/playbook.d.ts +1 -0
- package/dist/src/dream/playbook.js +2 -0
- package/dist/src/dream/report.d.ts +7 -0
- package/dist/src/dream/report.js +43 -0
- package/dist/src/dream/result.d.ts +9 -0
- package/dist/src/dream/result.js +1 -0
- package/dist/src/dream/settings.d.ts +10 -0
- package/dist/src/dream/settings.js +14 -0
- package/dist/src/history/history.d.ts +156 -0
- package/dist/src/history/history.js +212 -0
- package/dist/src/history/query.d.ts +63 -0
- package/dist/src/history/query.js +201 -0
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.js +1 -0
- package/dist/src/notes/address.d.ts +31 -0
- package/dist/src/notes/address.js +123 -0
- package/dist/src/notes/constants.d.ts +3 -0
- package/dist/src/notes/constants.js +3 -0
- package/dist/src/notes/errors.d.ts +11 -0
- package/dist/src/notes/errors.js +13 -0
- package/dist/src/notes/frontmatter.d.ts +44 -0
- package/dist/src/notes/frontmatter.js +145 -0
- package/dist/src/notes/fs-error.d.ts +2 -0
- package/dist/src/notes/fs-error.js +5 -0
- package/dist/src/notes/identity.d.ts +10 -0
- package/dist/src/notes/identity.js +33 -0
- package/dist/src/notes/index.d.ts +5 -0
- package/dist/src/notes/index.js +3 -0
- package/dist/src/notes/paths.d.ts +21 -0
- package/dist/src/notes/paths.js +113 -0
- package/dist/src/notes/store.d.ts +103 -0
- package/dist/src/notes/store.js +474 -0
- package/dist/src/pi/boot.d.ts +24 -0
- package/dist/src/pi/boot.js +56 -0
- package/dist/src/pi/budget.d.ts +13 -0
- package/dist/src/pi/budget.js +178 -0
- package/dist/src/pi/dream/cli.d.ts +10 -0
- package/dist/src/pi/dream/cli.js +140 -0
- package/dist/src/pi/dream/runner.d.ts +27 -0
- package/dist/src/pi/dream/runner.js +90 -0
- package/dist/src/pi/dream/settings.d.ts +7 -0
- package/dist/src/pi/dream/settings.js +17 -0
- package/dist/src/pi/entries.d.ts +7 -0
- package/dist/src/pi/entries.js +7 -0
- package/dist/src/pi/estimate.d.ts +16 -0
- package/dist/src/pi/estimate.js +99 -0
- package/dist/src/pi/extension.d.ts +10 -0
- package/dist/src/pi/extension.js +24 -0
- package/dist/src/pi/history-tools.d.ts +3 -0
- package/dist/src/pi/history-tools.js +9 -0
- package/dist/src/pi/history.d.ts +4 -0
- package/dist/src/pi/history.js +150 -0
- package/dist/src/pi/notes/adapter.d.ts +10 -0
- package/dist/src/pi/notes/adapter.js +27 -0
- package/dist/src/pi/notes/tools.d.ts +3 -0
- package/dist/src/pi/notes/tools.js +15 -0
- package/dist/src/pi/reset/artifacts.d.ts +24 -0
- package/dist/src/pi/reset/artifacts.js +84 -0
- package/dist/src/pi/reset/committed.d.ts +7 -0
- package/dist/src/pi/reset/committed.js +28 -0
- package/dist/src/pi/reset/lifecycle.d.ts +101 -0
- package/dist/src/pi/reset/lifecycle.js +277 -0
- package/dist/src/pi/reset/text.d.ts +5 -0
- package/dist/src/pi/reset/text.js +6 -0
- package/dist/src/pi/runtime.d.ts +3 -0
- package/dist/src/pi/runtime.js +206 -0
- package/dist/src/pi/session-reader.d.ts +5 -0
- package/dist/src/pi/session-reader.js +1 -0
- package/dist/src/pi/thresholds.d.ts +17 -0
- package/dist/src/pi/thresholds.js +33 -0
- package/dist/src/pi/tool-names.d.ts +7 -0
- package/dist/src/pi/tool-names.js +7 -0
- package/dist/src/pi/tool-result.d.ts +15 -0
- package/dist/src/pi/tool-result.js +29 -0
- package/dist/src/pi/window.d.ts +41 -0
- package/dist/src/pi/window.js +127 -0
- package/dist/src/settings.d.ts +9 -0
- package/dist/src/settings.js +18 -0
- package/dist/src/text-match.d.ts +5 -0
- package/dist/src/text-match.js +16 -0
- package/dist/src/tools/history.d.ts +58 -0
- package/dist/src/tools/history.js +210 -0
- package/dist/src/tools/notes.d.ts +250 -0
- package/dist/src/tools/notes.js +360 -0
- package/dist/src/tools/output.d.ts +23 -0
- package/dist/src/tools/output.js +39 -0
- package/dist/src/tools/result.d.ts +82 -0
- package/dist/src/tools/result.js +104 -0
- package/dist/src/tools/schema.d.ts +18 -0
- package/dist/src/tools/schema.js +31 -0
- package/dist/test/agent-loop.test.d.ts +1 -0
- package/dist/test/agent-loop.test.js +1497 -0
- package/dist/test/boot.integration.test.d.ts +1 -0
- package/dist/test/boot.integration.test.js +294 -0
- package/dist/test/budget-settings.integration.test.d.ts +1 -0
- package/dist/test/budget-settings.integration.test.js +144 -0
- package/dist/test/claude-mod.test.d.ts +1 -0
- package/dist/test/claude-mod.test.js +404 -0
- package/dist/test/dependencies.test.d.ts +1 -0
- package/dist/test/dependencies.test.js +101 -0
- package/dist/test/doctor.test.d.ts +1 -0
- package/dist/test/doctor.test.js +37 -0
- package/dist/test/dream-skill.test.d.ts +1 -0
- package/dist/test/dream-skill.test.js +72 -0
- package/dist/test/dream.test.d.ts +1 -0
- package/dist/test/dream.test.js +136 -0
- package/dist/test/helpers/dependency-graph.d.ts +5 -0
- package/dist/test/helpers/dependency-graph.js +73 -0
- package/dist/test/helpers/extension-test-environment.d.ts +1 -0
- package/dist/test/helpers/extension-test-environment.js +9 -0
- package/dist/test/helpers/extension.d.ts +119 -0
- package/dist/test/helpers/extension.js +367 -0
- package/dist/test/helpers/notes.d.ts +6 -0
- package/dist/test/helpers/notes.js +13 -0
- package/dist/test/history.integration.test.d.ts +1 -0
- package/dist/test/history.integration.test.js +633 -0
- package/dist/test/host-neutral.test.d.ts +1 -0
- package/dist/test/host-neutral.test.js +274 -0
- package/dist/test/notes-library.test.d.ts +1 -0
- package/dist/test/notes-library.test.js +214 -0
- package/dist/test/notes.integration.test.d.ts +1 -0
- package/dist/test/notes.integration.test.js +515 -0
- package/dist/test/notes.test.d.ts +1 -0
- package/dist/test/notes.test.js +530 -0
- package/dist/test/reset-lifecycle.test.d.ts +1 -0
- package/dist/test/reset-lifecycle.test.js +605 -0
- package/docs/architecture.md +63 -0
- package/docs/claude-code-mod.md +9 -0
- package/docs/notes-library.md +74 -0
- package/docs/reset-lifecycle.md +75 -0
- package/docs/sdk-integration.md +39 -0
- package/docs/skills.md +30 -0
- package/docs/tool-results.md +78 -0
- package/mods/notesoup/.claude-plugin/plugin.json +8 -0
- package/mods/notesoup/dist/claude/helper.js +9265 -0
- package/mods/notesoup/hooks/hooks.json +4 -0
- package/mods/notesoup/hooks/register.ts +240 -0
- package/mods/notesoup/playbook.md +34 -0
- package/mods/notesoup/skills/dream/SKILL.md +12 -0
- package/mods/pi-context/dist/claude/helper.js +9324 -0
- package/package.json +89 -5
- package/playbook.md +34 -0
- package/skills/dream/SKILL.md +12 -0
- package/skills/memory/SKILL.md +59 -0
- package/src/boot/render.ts +115 -0
- package/src/boot/snapshot.ts +46 -0
- package/src/boot/text.ts +58 -0
- package/src/budget/constants.ts +9 -0
- package/src/budget/policy.ts +36 -0
- package/src/budget/text.ts +11 -0
- package/src/claude/helper.ts +94 -0
- package/src/dream/doctor.ts +117 -0
- package/src/dream/gates.ts +26 -0
- package/src/dream/git.ts +73 -0
- package/src/dream/jail.ts +62 -0
- package/src/dream/lock.ts +82 -0
- package/src/dream/playbook.ts +3 -0
- package/src/dream/report.ts +36 -0
- package/src/dream/result.ts +2 -0
- package/src/dream/settings.ts +16 -0
- package/src/history/history.ts +286 -0
- package/src/history/query.ts +222 -0
- package/src/index.ts +1 -0
- package/src/notes/address.ts +110 -0
- package/src/notes/constants.ts +3 -0
- package/src/notes/errors.ts +15 -0
- package/src/notes/frontmatter.ts +166 -0
- package/src/notes/fs-error.ts +5 -0
- package/src/notes/identity.ts +40 -0
- package/src/notes/index.ts +24 -0
- package/src/notes/paths.ts +109 -0
- package/src/notes/store.ts +494 -0
- package/src/pi/boot.ts +88 -0
- package/src/pi/budget.ts +178 -0
- package/src/pi/dream/cli.ts +92 -0
- package/src/pi/dream/runner.ts +91 -0
- package/src/pi/dream/settings.ts +17 -0
- package/src/pi/entries.ts +7 -0
- package/src/pi/estimate.ts +116 -0
- package/src/pi/extension.ts +27 -0
- package/src/pi/history-tools.ts +11 -0
- package/src/pi/history.ts +162 -0
- package/src/pi/notes/adapter.ts +33 -0
- package/src/pi/notes/tools.ts +18 -0
- package/src/pi/reset/artifacts.ts +100 -0
- package/src/pi/reset/committed.ts +26 -0
- package/src/pi/reset/lifecycle.ts +342 -0
- package/src/pi/reset/text.ts +10 -0
- package/src/pi/runtime.ts +200 -0
- package/src/pi/session-reader.ts +6 -0
- package/src/pi/thresholds.ts +50 -0
- package/src/pi/tool-names.ts +9 -0
- package/src/pi/tool-result.ts +41 -0
- package/src/pi/window.ts +133 -0
- package/src/settings.ts +22 -0
- package/src/text-match.ts +14 -0
- package/src/tools/history.ts +234 -0
- package/src/tools/notes.ts +381 -0
- package/src/tools/output.ts +41 -0
- package/src/tools/result.ts +144 -0
- package/src/tools/schema.ts +31 -0
|
@@ -0,0 +1,1497 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { createAssistantMessageEventStream, getCurrentSystemMessage } from "@earendil-works/pi-ai";
|
|
7
|
+
import { createAgentSession, createCodemodeExtension, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import notesoup, { createNotesoup } from "../src/pi/extension.js";
|
|
9
|
+
import { BOOT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, MANUAL_WIPE_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../src/pi/entries.js";
|
|
10
|
+
import { CONTEXT_WINDOW_OPEN_TAG } from "../src/boot/text.js";
|
|
11
|
+
import { CONTINUATION, WARNING_CONTENT, WARNING_PROMPT } from "../src/pi/reset/text.js";
|
|
12
|
+
import { GUIDANCE_OPEN_TAG } from "../src/budget/text.js";
|
|
13
|
+
async function openFixture(options) {
|
|
14
|
+
const dir = options.cwd ?? mkdtempSync(join(tmpdir(), "notesoup-agent-loop-"));
|
|
15
|
+
const ownsDir = options.cwd === undefined;
|
|
16
|
+
const notesRoot = options.notesRoot ?? mkdtempSync(join(tmpdir(), "notesoup-agent-loop-notes-"));
|
|
17
|
+
const ownsNotesRoot = options.notesRoot === undefined;
|
|
18
|
+
const agentDir = options.agentDir ?? dir;
|
|
19
|
+
const managesEnvironment = options.manageEnvironment ?? true;
|
|
20
|
+
const previousDir = managesEnvironment ? process.env.PI_CODING_AGENT_DIR : undefined;
|
|
21
|
+
const previousNotesRoot = managesEnvironment ? process.env.PI_NOTES_HOME : undefined;
|
|
22
|
+
if (managesEnvironment) {
|
|
23
|
+
process.env.PI_CODING_AGENT_DIR = agentDir;
|
|
24
|
+
process.env.PI_NOTES_HOME = notesRoot;
|
|
25
|
+
}
|
|
26
|
+
if (options.notesRootFile) {
|
|
27
|
+
rmSync(notesRoot, { recursive: true, force: true });
|
|
28
|
+
writeFileSync(notesRoot, "blocked notes root");
|
|
29
|
+
}
|
|
30
|
+
const runtime = await ModelRuntime.create({
|
|
31
|
+
authPath: join(dir, "auth.json"),
|
|
32
|
+
modelsPath: null,
|
|
33
|
+
modelsStorePath: join(dir, "models"),
|
|
34
|
+
refreshOnCreate: false,
|
|
35
|
+
});
|
|
36
|
+
await runtime.setRuntimeApiKey("openai", "scripted-test-key");
|
|
37
|
+
const base = runtime.getModels("openai")[0];
|
|
38
|
+
assert.ok(base, "the installed SDK exposes a scripted model");
|
|
39
|
+
const model = { ...base, contextWindow: options.contextWindow ?? 100_000, maxTokens: 4096 };
|
|
40
|
+
runtime.stream = (() => { throw new Error("unexpected native model request"); });
|
|
41
|
+
runtime.complete = (() => { throw new Error("unexpected native model request"); });
|
|
42
|
+
runtime.streamSimple = (() => { throw new Error("unexpected native model request"); });
|
|
43
|
+
runtime.completeSimple = (() => { throw new Error("unexpected native model request"); });
|
|
44
|
+
if (options.writeSettings !== false)
|
|
45
|
+
writeFileSync(join(agentDir, "settings.json"), JSON.stringify({
|
|
46
|
+
compaction: {
|
|
47
|
+
enabled: options.defaultCompactionEnabled ?? options.compactionEnabled ?? true,
|
|
48
|
+
reserveTokens: options.defaultReserveTokens ?? 32_768,
|
|
49
|
+
keepRecentTokens: options.keepRecentTokens ?? 200,
|
|
50
|
+
},
|
|
51
|
+
retry: { enabled: false },
|
|
52
|
+
}));
|
|
53
|
+
if (options.projectSettings !== undefined) {
|
|
54
|
+
mkdirSync(join(dir, ".pi"), { recursive: true });
|
|
55
|
+
writeFileSync(join(dir, ".pi", "settings.json"), JSON.stringify(options.projectSettings));
|
|
56
|
+
}
|
|
57
|
+
const settingsManager = typeof options.settingsManager === "function"
|
|
58
|
+
? options.settingsManager(model)
|
|
59
|
+
: options.settingsManager ?? SettingsManager.create(dir, agentDir, { projectTrusted: options.projectTrusted ?? true });
|
|
60
|
+
const requests = [];
|
|
61
|
+
const streamContexts = [];
|
|
62
|
+
const streamSignals = [];
|
|
63
|
+
const events = [];
|
|
64
|
+
const notices = [];
|
|
65
|
+
let budgetNotices = 0;
|
|
66
|
+
let session;
|
|
67
|
+
const loader = new DefaultResourceLoader({
|
|
68
|
+
cwd: dir,
|
|
69
|
+
agentDir,
|
|
70
|
+
settingsManager,
|
|
71
|
+
noExtensions: true,
|
|
72
|
+
noSkills: true,
|
|
73
|
+
noThemes: true,
|
|
74
|
+
noPromptTemplates: true,
|
|
75
|
+
systemPromptOverride: () => options.systemPrompt ?? "Use the tools as requested.",
|
|
76
|
+
agentsFilesOverride: () => ({ agentsFiles: [] }),
|
|
77
|
+
extensionFactories: [...(options.codemode ? [createCodemodeExtension({ models: false })] : []), options.settingsManager ? createNotesoup({ settingsManager }) : notesoup, (pi) => {
|
|
78
|
+
options.hook?.(pi, () => session, requests);
|
|
79
|
+
}],
|
|
80
|
+
});
|
|
81
|
+
await loader.reload();
|
|
82
|
+
const sessionManager = options.sessionManager ?? (options.sessionDir ? SessionManager.create(dir, options.sessionDir) : SessionManager.inMemory(dir));
|
|
83
|
+
options.seed?.(sessionManager);
|
|
84
|
+
const created = await createAgentSession({
|
|
85
|
+
cwd: dir,
|
|
86
|
+
agentDir,
|
|
87
|
+
modelRuntime: runtime,
|
|
88
|
+
model,
|
|
89
|
+
settingsManager,
|
|
90
|
+
sessionManager,
|
|
91
|
+
resourceLoader: loader,
|
|
92
|
+
tools: options.tools ?? ["clear_memory", "notes_write", "get_context_remaining"],
|
|
93
|
+
});
|
|
94
|
+
session = created.session;
|
|
95
|
+
session.subscribe((event) => events.push(event));
|
|
96
|
+
session.agent.streamFunction = async (_model, context, streamOptions) => {
|
|
97
|
+
const aborted = streamOptions?.signal?.aborted === true;
|
|
98
|
+
streamContexts.push(context);
|
|
99
|
+
streamSignals.push(aborted);
|
|
100
|
+
if (aborted) {
|
|
101
|
+
const message = {
|
|
102
|
+
role: "assistant",
|
|
103
|
+
api: model.api,
|
|
104
|
+
provider: model.provider,
|
|
105
|
+
model: model.id,
|
|
106
|
+
content: [],
|
|
107
|
+
stopReason: "aborted",
|
|
108
|
+
errorMessage: "scripted request aborted",
|
|
109
|
+
timestamp: Date.now(),
|
|
110
|
+
usage: usage(0, 0),
|
|
111
|
+
};
|
|
112
|
+
const stream = createAssistantMessageEventStream();
|
|
113
|
+
stream.push({ type: "error", reason: "aborted", error: message });
|
|
114
|
+
stream.end();
|
|
115
|
+
return stream;
|
|
116
|
+
}
|
|
117
|
+
requests.push(context);
|
|
118
|
+
const request = requests.length;
|
|
119
|
+
const message = await options.script(request, context);
|
|
120
|
+
const stream = createAssistantMessageEventStream();
|
|
121
|
+
stream.push({ type: "done", reason: (message.stopReason === "error" || message.stopReason === "aborted" ? "stop" : message.stopReason), message });
|
|
122
|
+
stream.end();
|
|
123
|
+
return stream;
|
|
124
|
+
};
|
|
125
|
+
await session.bindExtensions({
|
|
126
|
+
uiContext: {
|
|
127
|
+
notify(message, type) {
|
|
128
|
+
if (message.startsWith("notesoup: memory cleared · ")) {
|
|
129
|
+
const windowId = message.split(" · ")[1];
|
|
130
|
+
assert.ok(sessionManager.getBranch().some((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE && entry.data?.windowId === windowId), "notification follows the reset marker commit");
|
|
131
|
+
assert.ok(sessionManager.getBranch().some((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE && entry.details?.windowId === windowId), "notification follows the reset boot commit");
|
|
132
|
+
}
|
|
133
|
+
if (type === "warning" && /^notesoup: context (?:almost full|running low)/.test(message))
|
|
134
|
+
budgetNotices++;
|
|
135
|
+
notices.push(message);
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
return {
|
|
140
|
+
dir,
|
|
141
|
+
notesRoot,
|
|
142
|
+
sessionManager,
|
|
143
|
+
session,
|
|
144
|
+
model,
|
|
145
|
+
requests,
|
|
146
|
+
streamContexts,
|
|
147
|
+
streamSignals,
|
|
148
|
+
events,
|
|
149
|
+
notices,
|
|
150
|
+
budgetNotices: () => budgetNotices,
|
|
151
|
+
close: () => {
|
|
152
|
+
session.dispose();
|
|
153
|
+
if (managesEnvironment) {
|
|
154
|
+
if (previousDir === undefined)
|
|
155
|
+
delete process.env.PI_CODING_AGENT_DIR;
|
|
156
|
+
else
|
|
157
|
+
process.env.PI_CODING_AGENT_DIR = previousDir;
|
|
158
|
+
if (previousNotesRoot === undefined)
|
|
159
|
+
delete process.env.PI_NOTES_HOME;
|
|
160
|
+
else
|
|
161
|
+
process.env.PI_NOTES_HOME = previousNotesRoot;
|
|
162
|
+
}
|
|
163
|
+
if (ownsDir)
|
|
164
|
+
rmSync(dir, { recursive: true, force: true });
|
|
165
|
+
if (ownsNotesRoot)
|
|
166
|
+
rmSync(notesRoot, { recursive: true, force: true });
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
function usage(input, output = 1) {
|
|
171
|
+
return {
|
|
172
|
+
input,
|
|
173
|
+
output,
|
|
174
|
+
cacheRead: 0,
|
|
175
|
+
cacheWrite: 0,
|
|
176
|
+
totalTokens: input + output,
|
|
177
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
function assistant(fixture, content, stopReason = "stop", extra = {}) {
|
|
181
|
+
return {
|
|
182
|
+
role: "assistant",
|
|
183
|
+
api: fixture.model.api,
|
|
184
|
+
provider: fixture.model.provider,
|
|
185
|
+
model: fixture.model.id,
|
|
186
|
+
content,
|
|
187
|
+
stopReason,
|
|
188
|
+
timestamp: Date.now(),
|
|
189
|
+
usage: usage(100),
|
|
190
|
+
...extra,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
function text(message) {
|
|
194
|
+
return JSON.stringify(message?.messages ?? []);
|
|
195
|
+
}
|
|
196
|
+
function resetMarkers(fixture) {
|
|
197
|
+
return fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE);
|
|
198
|
+
}
|
|
199
|
+
function contextRemainingResults(fixture) {
|
|
200
|
+
const results = [];
|
|
201
|
+
for (const entry of fixture.sessionManager.getBranch()) {
|
|
202
|
+
if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.toolName !== "get_context_remaining")
|
|
203
|
+
continue;
|
|
204
|
+
const content = entry.message.content.find((part) => part.type === "text")?.text;
|
|
205
|
+
if (content === undefined)
|
|
206
|
+
continue;
|
|
207
|
+
const value = JSON.parse(content);
|
|
208
|
+
if (typeof value.remaining_tokens === "number" || value.remaining_tokens === null)
|
|
209
|
+
results.push(value.remaining_tokens);
|
|
210
|
+
}
|
|
211
|
+
return results;
|
|
212
|
+
}
|
|
213
|
+
function assertFreshRequest(fixture, requestIndex, oldSentinel) {
|
|
214
|
+
const body = text(fixture.requests[requestIndex]);
|
|
215
|
+
assert.equal(body.includes(oldSentinel), false, "the new provider request excludes the old window transcript");
|
|
216
|
+
assert.ok(body.includes(CONTEXT_WINDOW_OPEN_TAG), "the new provider request includes the fresh context-window boot");
|
|
217
|
+
assert.equal(body.split(CONTINUATION).length - 1, 1, "the fresh window carries exactly one reset message");
|
|
218
|
+
}
|
|
219
|
+
test("real Pi codemode receives typed notes/history outcomes, including expected errors", { timeout: 20000 }, async () => {
|
|
220
|
+
let fixture;
|
|
221
|
+
fixture = await openFixture({
|
|
222
|
+
codemode: true,
|
|
223
|
+
compactionEnabled: false,
|
|
224
|
+
tools: ["codemode", "notes_write", "notes_read", "notes_list", "history_list", "history_read"],
|
|
225
|
+
script: (request) => {
|
|
226
|
+
if (request === 1)
|
|
227
|
+
return assistant(fixture, [{ type: "toolCall", id: "structured-smoke", name: "codemode", arguments: { code: `
|
|
228
|
+
const written = await tools.notes_write({ address: "smoke.md", content: "A😀界Z" });
|
|
229
|
+
const listed = await tools.notes_list({});
|
|
230
|
+
const read = await tools.notes_read({ address: "smoke.md", offset_chars: 1, max_chars: 2 });
|
|
231
|
+
const refused = await tools.notes_read({ address: "missing.md" });
|
|
232
|
+
if ("error" in written || "error" in listed || "error" in read || !("error" in refused)) throw new Error("wrong outcome");
|
|
233
|
+
if (read.text !== "😀界" || read.next_offset_chars !== 3) throw new Error("wrong window");
|
|
234
|
+
if (refused.code !== "not_found") throw new Error("missing typed refusal");
|
|
235
|
+
text({ marker: "TYPED_SMOKE", files: listed.files.map(f => f.address), body: read.text, error: refused.code });
|
|
236
|
+
` } }], "toolUse");
|
|
237
|
+
if (request === 2)
|
|
238
|
+
return assistant(fixture, [{ type: "toolCall", id: "structured-history-smoke", name: "codemode", arguments: { code: `
|
|
239
|
+
const page = await tools.history_list({ roles: ["tool"] });
|
|
240
|
+
if ("error" in page) throw new Error("history list failed");
|
|
241
|
+
const parent = page.items.find(item => item.tool === "codemode");
|
|
242
|
+
if (!parent) throw new Error("missing codemode parent");
|
|
243
|
+
const read = await tools.history_read({ seq: parent.seq });
|
|
244
|
+
if ("error" in read || read.tool !== "codemode") throw new Error("missing typed tool summary");
|
|
245
|
+
const calls = read.nested_calls;
|
|
246
|
+
if (!calls || !read.text.includes("notes_read [error]")) throw new Error("missing nested refusal evidence");
|
|
247
|
+
text({ marker: "HISTORY_SMOKE", calls: calls.call_count, complete: calls.complete });
|
|
248
|
+
` } }], "toolUse");
|
|
249
|
+
return assistant(fixture, [{ type: "text", text: "structured smoke complete" }]);
|
|
250
|
+
},
|
|
251
|
+
});
|
|
252
|
+
try {
|
|
253
|
+
await fixture.session.prompt("Exercise the structured tools through real codemode.");
|
|
254
|
+
const results = fixture.sessionManager.getBranch().flatMap(entry => entry.type === "message" && entry.message.role === "toolResult" ? [entry.message] : []);
|
|
255
|
+
assert.equal(results.length, 2, "nested calls are not separate transcript events");
|
|
256
|
+
assert.ok(results.every(result => !result.isError), JSON.stringify(results));
|
|
257
|
+
const output = results.map(result => result.content.filter(part => part.type === "text").map(part => part.text).join("\n")).join("\n");
|
|
258
|
+
assert.match(output, /TYPED_SMOKE/);
|
|
259
|
+
assert.match(output, /HISTORY_SMOKE/);
|
|
260
|
+
assert.equal(results[0].nestedCalls?.calls.length, 4);
|
|
261
|
+
assert.equal(results[0].nestedCalls?.complete, true);
|
|
262
|
+
}
|
|
263
|
+
finally {
|
|
264
|
+
fixture.close();
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
test("real AgentSession: aborted early guidance retries silently with automatic reset disabled", async () => {
|
|
268
|
+
let fixture;
|
|
269
|
+
fixture = await openFixture({
|
|
270
|
+
compactionEnabled: false,
|
|
271
|
+
script: (request) => assistant(fixture, [{ type: "text", text: `response ${request}` }], request === 2 ? "aborted" : "stop", { usage: usage(50_000) }),
|
|
272
|
+
});
|
|
273
|
+
try {
|
|
274
|
+
const guidance = () => fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === GUIDANCE_TYPE);
|
|
275
|
+
const notices = () => fixture.budgetNotices();
|
|
276
|
+
await fixture.session.prompt("Establish usage below the reminder line.");
|
|
277
|
+
await fixture.session.waitForIdle();
|
|
278
|
+
assert.equal(guidance().length, 0);
|
|
279
|
+
await fixture.session.prompt("Abort this low-budget request.");
|
|
280
|
+
await fixture.session.waitForIdle();
|
|
281
|
+
assert.equal(guidance().length, 0, "an aborted turn does not commit early guidance");
|
|
282
|
+
assert.equal(notices(), 0, "early guidance never notifies");
|
|
283
|
+
await fixture.session.prompt("Retry successfully.");
|
|
284
|
+
await fixture.session.waitForIdle();
|
|
285
|
+
assert.equal(guidance().length, 1, "the successful retry commits the model guidance");
|
|
286
|
+
assert.equal(notices(), 0, "committed early guidance stays UI-silent");
|
|
287
|
+
await fixture.session.prompt("Continue in the same window.");
|
|
288
|
+
await fixture.session.waitForIdle();
|
|
289
|
+
assert.equal(guidance().length, 1);
|
|
290
|
+
assert.equal(notices(), 0, "later turns cannot toast the early reminder");
|
|
291
|
+
}
|
|
292
|
+
finally {
|
|
293
|
+
fixture.close();
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
test("real AgentSession: an aborted final warning stays silent until a successful retry commits it", async () => {
|
|
297
|
+
let fixture;
|
|
298
|
+
fixture = await openFixture({
|
|
299
|
+
compactionEnabled: true,
|
|
300
|
+
script: (request, context) => {
|
|
301
|
+
if (request === 1)
|
|
302
|
+
return assistant(fixture, [{ type: "toolCall", id: "abort-budget-probe-1", name: "get_context_remaining", arguments: {} }], "toolUse", { usage: usage(50_000) });
|
|
303
|
+
if (request === 2)
|
|
304
|
+
return assistant(fixture, [{ type: "toolCall", id: "abort-budget-probe-2", name: "get_context_remaining", arguments: {} }], "toolUse", { usage: usage(60_000) });
|
|
305
|
+
assert.ok(text(context).includes(WARNING_PROMPT), "the final warning reaches the model on both attempts");
|
|
306
|
+
return assistant(fixture, [{ type: "text", text: `response ${request}` }], request === 3 ? "aborted" : "stop", { usage: usage(60_000) });
|
|
307
|
+
},
|
|
308
|
+
});
|
|
309
|
+
try {
|
|
310
|
+
const warnings = () => fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === WARNING_TYPE);
|
|
311
|
+
const notices = () => fixture.budgetNotices();
|
|
312
|
+
await fixture.session.prompt("Establish usage and reach the final runway.");
|
|
313
|
+
await fixture.session.waitForIdle();
|
|
314
|
+
assert.equal(fixture.requests.length, 3, "budget probes reach one final-warning attempt");
|
|
315
|
+
assert.equal(warnings().length, 0, "the aborted attempt leaves no durable warning");
|
|
316
|
+
assert.equal(notices(), 0, "an uncommitted warning never notifies");
|
|
317
|
+
await fixture.session.prompt("Retry successfully.");
|
|
318
|
+
await fixture.session.waitForIdle();
|
|
319
|
+
assert.equal(warnings().length, 1, "the successful retry commits one hidden warning");
|
|
320
|
+
assert.equal(resetMarkers(fixture).length, 0, "committing the warning does not authorize a reset at normal stop");
|
|
321
|
+
assert.equal(fixture.requests.length, 4, "the retry settles without a fresh-window continuation");
|
|
322
|
+
assert.equal(notices(), 1, "the committed warning notifies once");
|
|
323
|
+
assert.equal(fixture.notices.some((notice) => notice.includes("Context running low")), false, "early guidance remains UI-silent");
|
|
324
|
+
}
|
|
325
|
+
finally {
|
|
326
|
+
fixture.close();
|
|
327
|
+
}
|
|
328
|
+
});
|
|
329
|
+
test("real AgentSession: final warning survives its reset boundary and notifies once", { timeout: 20000 }, async () => {
|
|
330
|
+
let fixture;
|
|
331
|
+
fixture = await openFixture({
|
|
332
|
+
compactionEnabled: true,
|
|
333
|
+
script: (request, context) => {
|
|
334
|
+
if (request === 1)
|
|
335
|
+
return assistant(fixture, [{ type: "toolCall", id: "final-budget-probe-1", name: "get_context_remaining", arguments: {} }], "toolUse", { usage: usage(50_000) });
|
|
336
|
+
if (request === 2)
|
|
337
|
+
return assistant(fixture, [{ type: "toolCall", id: "final-budget-probe-2", name: "get_context_remaining", arguments: {} }], "toolUse", { usage: usage(60_000) });
|
|
338
|
+
if (request === 3) {
|
|
339
|
+
assert.ok(text(context).includes(WARNING_PROMPT), "the final warning reaches the model");
|
|
340
|
+
return assistant(fixture, [{ type: "toolCall", id: "final-budget-wipe", name: "clear_memory", arguments: {} }], "toolUse", { usage: usage(60_000) });
|
|
341
|
+
}
|
|
342
|
+
return assistant(fixture, [{ type: "text", text: "fresh window ready" }]);
|
|
343
|
+
},
|
|
344
|
+
});
|
|
345
|
+
try {
|
|
346
|
+
assert.equal(fixture.notices.length, 0, "boot is silent");
|
|
347
|
+
await fixture.session.prompt("FINAL_WARNING_RESET_SENTINEL");
|
|
348
|
+
await fixture.session.waitForIdle();
|
|
349
|
+
assert.equal(fixture.requests.length, 4, "two budget probes, close-out tool, and fresh-window request run");
|
|
350
|
+
assertFreshRequest(fixture, 3, "FINAL_WARNING_RESET_SENTINEL");
|
|
351
|
+
assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === WARNING_TYPE).length, 1);
|
|
352
|
+
assert.equal(resetMarkers(fixture).length, 1, "the reset commits in the same boundary as the final warning");
|
|
353
|
+
assert.equal(fixture.budgetNotices(), 1, "the old-window committed warning reaches the UI after reset");
|
|
354
|
+
assert.equal(fixture.notices.filter((notice) => notice.startsWith("notesoup: memory cleared · ")).length, 1, "reset notification remains intact");
|
|
355
|
+
assert.equal(fixture.notices.some((notice) => notice.includes("Context running low")), false, "early guidance stays silent");
|
|
356
|
+
await fixture.session.prompt("Continue after reset.");
|
|
357
|
+
await fixture.session.waitForIdle();
|
|
358
|
+
assert.equal(fixture.budgetNotices(), 1, "later turns cannot repeat the consumed final warning");
|
|
359
|
+
assert.equal(fixture.notices.filter((notice) => notice.startsWith("notesoup: memory cleared · ")).length, 1, "the prior reset notification is also deduplicated");
|
|
360
|
+
}
|
|
361
|
+
finally {
|
|
362
|
+
fixture.close();
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
test("real AgentSession: explicit tiny-session wipe ignores keepRecentTokens and preserves raw history", async () => {
|
|
366
|
+
let fixture;
|
|
367
|
+
fixture = await openFixture({
|
|
368
|
+
compactionEnabled: false,
|
|
369
|
+
keepRecentTokens: 1_000_000,
|
|
370
|
+
script: (request, context) => request === 1
|
|
371
|
+
? assistant(fixture, [{ type: "toolCall", id: "wipe-1", name: "clear_memory", arguments: {} }], "toolUse")
|
|
372
|
+
: assistant(fixture, [{ type: "text", text: "resumed in a new window" }]),
|
|
373
|
+
});
|
|
374
|
+
try {
|
|
375
|
+
assert.equal(fixture.requests.length, 0, "startup boot does not trigger a model request");
|
|
376
|
+
assert.equal(fixture.notices.length, 0, "startup boot is silent");
|
|
377
|
+
await fixture.session.prompt("OLD_CONTEXT_SENTINEL: retain this only in durable history.");
|
|
378
|
+
await fixture.session.waitForIdle();
|
|
379
|
+
assert.equal(fixture.notices.filter((message) => message.includes("memory cleared")).length, 1, "the reset notifies once");
|
|
380
|
+
assert.equal(fixture.requests.length, 2, "the tool starts exactly one continuation");
|
|
381
|
+
assert.ok(text(fixture.requests[0]).includes("OLD_CONTEXT_SENTINEL"));
|
|
382
|
+
assertFreshRequest(fixture, 1, "OLD_CONTEXT_SENTINEL");
|
|
383
|
+
assert.equal(resetMarkers(fixture).length, 1, "explicit wipe does not depend on Pi's compaction keep window");
|
|
384
|
+
const marker = resetMarkers(fixture)[0];
|
|
385
|
+
assert.equal(marker.type, "custom");
|
|
386
|
+
assert.deepEqual(Object.keys(marker.data), ["windowId"]);
|
|
387
|
+
const windowId = marker.data.windowId;
|
|
388
|
+
const boot = fixture.sessionManager.getBranch().find((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE && entry.details && typeof entry.details === "object" && entry.details.windowId === windowId);
|
|
389
|
+
assert.ok(boot && boot.type === "custom_message", "the reset boot is persisted after the marker");
|
|
390
|
+
assert.equal(boot.details.windowId, windowId);
|
|
391
|
+
const checkpoint = fixture.sessionManager.getBranch().find((entry) => entry.type === "compaction");
|
|
392
|
+
assert.ok(checkpoint && checkpoint.type === "compaction", "explicit wipe commits a native checkpoint without a summary model call");
|
|
393
|
+
assert.equal(checkpoint.summary, "");
|
|
394
|
+
assert.equal(checkpoint.firstKeptEntryId, checkpoint.id, "the checkpoint retains none of the preceding context");
|
|
395
|
+
assert.ok(JSON.stringify(fixture.sessionManager.getBranch()).includes("OLD_CONTEXT_SENTINEL"), "raw history remains readable");
|
|
396
|
+
}
|
|
397
|
+
finally {
|
|
398
|
+
fixture.close();
|
|
399
|
+
}
|
|
400
|
+
});
|
|
401
|
+
test("real AgentSession: manual command spans its tool batch and stops at settlement", { timeout: 20000 }, async () => {
|
|
402
|
+
let fixture;
|
|
403
|
+
fixture = await openFixture({
|
|
404
|
+
compactionEnabled: false,
|
|
405
|
+
script: (request, context) => {
|
|
406
|
+
if (request === 1)
|
|
407
|
+
return assistant(fixture, [{ type: "text", text: "before manual reset" }]);
|
|
408
|
+
if (request === 2) {
|
|
409
|
+
assert.ok(text(context).includes(WARNING_PROMPT), "idle /clear-memory sends the shared checkpoint prompt");
|
|
410
|
+
return assistant(fixture, [{ type: "toolCall", id: "manual-note", name: "notes_write", arguments: { address: "manual-a.md", content: "MANUAL_NOTE_ALPHA" } }], "toolUse");
|
|
411
|
+
}
|
|
412
|
+
assert.equal(request, 3, "the close-out turn finishes in the old window");
|
|
413
|
+
assert.ok(text(context).includes("MANUAL_CLOSEOUT_OLD_SENTINEL"), "no reset commits before settlement");
|
|
414
|
+
return assistant(fixture, [{ type: "text", text: "close-out complete" }]);
|
|
415
|
+
},
|
|
416
|
+
});
|
|
417
|
+
try {
|
|
418
|
+
await fixture.session.prompt("MANUAL_CLOSEOUT_OLD_SENTINEL");
|
|
419
|
+
await fixture.session.waitForIdle();
|
|
420
|
+
await fixture.session.prompt("/clear-memory");
|
|
421
|
+
await fixture.session.waitForIdle();
|
|
422
|
+
assert.equal(fixture.requests.length, 3, "the run stops at settlement instead of continuing in the fresh window");
|
|
423
|
+
assert.equal(resetMarkers(fixture).length, 1);
|
|
424
|
+
const branch = fixture.sessionManager.getBranch();
|
|
425
|
+
const warningIndex = branch.findIndex((entry) => entry.type === "custom_message" && entry.customType === MANUAL_WIPE_TYPE);
|
|
426
|
+
const checkpointIndex = branch.findIndex((entry) => entry.type === "compaction");
|
|
427
|
+
const markerIndex = branch.findIndex((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE);
|
|
428
|
+
assert.ok(warningIndex >= 0 && warningIndex < checkpointIndex, "the idle warning is durable before the checkpoint");
|
|
429
|
+
const warning = branch[warningIndex];
|
|
430
|
+
assert.ok(warning?.type === "custom_message");
|
|
431
|
+
assert.equal(warning.content, WARNING_CONTENT);
|
|
432
|
+
assert.equal(branch[markerIndex - 1]?.id, branch[checkpointIndex]?.id);
|
|
433
|
+
assert.ok(branch.slice(0, checkpointIndex).some((entry) => entry.type === "message" && entry.message.role === "toolResult" && entry.message.toolName === "notes_write"), "note write finishes before the checkpoint");
|
|
434
|
+
const marker = resetMarkers(fixture)[0];
|
|
435
|
+
assert.equal(marker.type, "custom");
|
|
436
|
+
const windowId = marker.data.windowId;
|
|
437
|
+
const boot = branch.find((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE && entry.details?.windowId === windowId);
|
|
438
|
+
assert.ok(boot && boot.type === "custom_message");
|
|
439
|
+
assert.ok(typeof boot.content === "string" && boot.content.includes("manual-a.md"), "fresh boot indexes the completed note");
|
|
440
|
+
assert.equal(boot.display, false);
|
|
441
|
+
assert.equal(JSON.stringify(fixture.sessionManager.buildSessionProjection().messages).includes("MANUAL_CLOSEOUT_OLD_SENTINEL"), false);
|
|
442
|
+
assert.ok(JSON.stringify(branch).includes("MANUAL_CLOSEOUT_OLD_SENTINEL"), "raw history remains intact");
|
|
443
|
+
}
|
|
444
|
+
finally {
|
|
445
|
+
fixture.close();
|
|
446
|
+
}
|
|
447
|
+
});
|
|
448
|
+
test("real AgentSession: clear commands append a prompt after continuation and resume once", { timeout: 25000 }, async () => {
|
|
449
|
+
for (const mode of ["clear-memory", "cm", "hard-reserve", "overflow"]) {
|
|
450
|
+
let fixture;
|
|
451
|
+
const prompt = 'AFTER_CLEAR_PROMPT /cm "literal text"';
|
|
452
|
+
fixture = await openFixture({
|
|
453
|
+
compactionEnabled: mode === "hard-reserve",
|
|
454
|
+
script: (request, context) => {
|
|
455
|
+
if (request === 1)
|
|
456
|
+
return assistant(fixture, [{ type: "text", text: "initial work" }]);
|
|
457
|
+
if (request === 2) {
|
|
458
|
+
assert.equal(text(context).includes(prompt), false, "the old window never sees the trailing prompt");
|
|
459
|
+
if (mode === "overflow")
|
|
460
|
+
return assistant(fixture, [], "error", { errorMessage: "Prompt too long: context exceeds maximum context length" });
|
|
461
|
+
return mode === "hard-reserve"
|
|
462
|
+
? assistant(fixture, [{ type: "toolCall", id: "prompt-note", name: "notes_write", arguments: { address: "prompt-note.md", content: "saved" } }], "toolUse", { usage: usage(80_000) })
|
|
463
|
+
: assistant(fixture, [{ type: "text", text: "notes complete" }]);
|
|
464
|
+
}
|
|
465
|
+
assert.equal(request, 3, "exactly one fresh-window request");
|
|
466
|
+
assert.equal(text(context).includes("PROMPT_RESET_OLD_SENTINEL"), false);
|
|
467
|
+
assert.equal(text(context).split(prompt).length - 1, 1);
|
|
468
|
+
assert.ok(text(context).indexOf(CONTINUATION) < text(context).indexOf(prompt), "wake-up prose precedes the appended prompt");
|
|
469
|
+
return assistant(fixture, [{ type: "text", text: "prompt handled" }]);
|
|
470
|
+
},
|
|
471
|
+
});
|
|
472
|
+
try {
|
|
473
|
+
await fixture.session.prompt("PROMPT_RESET_OLD_SENTINEL");
|
|
474
|
+
await fixture.session.prompt(`/${mode === "clear-memory" ? "clear-memory" : "cm"} ${prompt} `);
|
|
475
|
+
await fixture.session.waitForIdle();
|
|
476
|
+
assert.equal(fixture.requests.length, 3);
|
|
477
|
+
assert.equal(resetMarkers(fixture).length, 1);
|
|
478
|
+
const branch = fixture.sessionManager.getBranch();
|
|
479
|
+
const continuationIndex = branch.findIndex((entry) => entry.type === "custom_message" && entry.customType === CONTINUATION_TYPE);
|
|
480
|
+
const appended = branch[continuationIndex + 1];
|
|
481
|
+
assert.ok(appended?.type === "custom_message");
|
|
482
|
+
assert.equal(appended.customType, "notesoup/reset-prompt");
|
|
483
|
+
assert.equal(appended.content, prompt);
|
|
484
|
+
assert.equal(appended.display, true);
|
|
485
|
+
assert.ok(fixture.notices.some((notice) => notice.includes("memory cleared")));
|
|
486
|
+
}
|
|
487
|
+
finally {
|
|
488
|
+
fixture.close();
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
});
|
|
492
|
+
test("real AgentSession: whitespace-only /cm clears and stops", { timeout: 20000 }, async () => {
|
|
493
|
+
let fixture;
|
|
494
|
+
fixture = await openFixture({
|
|
495
|
+
compactionEnabled: false,
|
|
496
|
+
script: (request) => {
|
|
497
|
+
assert.equal(request, 1, "bare alias never starts a fresh-window request");
|
|
498
|
+
return assistant(fixture, [{ type: "text", text: "notes complete" }]);
|
|
499
|
+
},
|
|
500
|
+
});
|
|
501
|
+
try {
|
|
502
|
+
await fixture.session.prompt("/cm ");
|
|
503
|
+
await fixture.session.waitForIdle();
|
|
504
|
+
assert.equal(resetMarkers(fixture).length, 1);
|
|
505
|
+
assert.equal(fixture.sessionManager.getBranch().some((entry) => entry.type === "custom_message" && entry.customType === "notesoup/reset-prompt"), false);
|
|
506
|
+
}
|
|
507
|
+
finally {
|
|
508
|
+
fixture.close();
|
|
509
|
+
}
|
|
510
|
+
});
|
|
511
|
+
test("real AgentSession: streaming clear prompt keeps the first request", { timeout: 20000 }, async () => {
|
|
512
|
+
let fixture;
|
|
513
|
+
let started;
|
|
514
|
+
let release;
|
|
515
|
+
const ready = new Promise((resolve) => { started = resolve; });
|
|
516
|
+
const gate = new Promise((resolve) => { release = resolve; });
|
|
517
|
+
fixture = await openFixture({
|
|
518
|
+
compactionEnabled: false,
|
|
519
|
+
script: async (request, context) => {
|
|
520
|
+
if (request === 1) {
|
|
521
|
+
started();
|
|
522
|
+
await gate;
|
|
523
|
+
}
|
|
524
|
+
if (request <= 2)
|
|
525
|
+
assert.equal(text(context).includes("FIRST_RESET_PROMPT"), false);
|
|
526
|
+
if (request === 3) {
|
|
527
|
+
assert.ok(text(context).includes("FIRST_RESET_PROMPT"));
|
|
528
|
+
assert.equal(text(context).includes("IGNORED_RESET_PROMPT"), false);
|
|
529
|
+
}
|
|
530
|
+
assert.ok(request <= 3);
|
|
531
|
+
return assistant(fixture, [{ type: "text", text: "done" }]);
|
|
532
|
+
},
|
|
533
|
+
});
|
|
534
|
+
try {
|
|
535
|
+
const running = fixture.session.prompt("streaming old work");
|
|
536
|
+
await ready;
|
|
537
|
+
await fixture.session.prompt("/cm FIRST_RESET_PROMPT", { streamingBehavior: "steer" });
|
|
538
|
+
await fixture.session.prompt("/clear-memory IGNORED_RESET_PROMPT", { streamingBehavior: "steer" });
|
|
539
|
+
release();
|
|
540
|
+
await running;
|
|
541
|
+
await fixture.session.waitForIdle();
|
|
542
|
+
assert.equal(fixture.requests.length, 3);
|
|
543
|
+
assert.equal(resetMarkers(fixture).length, 1);
|
|
544
|
+
assert.ok(fixture.notices.some((notice) => notice.includes("already pending")));
|
|
545
|
+
}
|
|
546
|
+
finally {
|
|
547
|
+
release();
|
|
548
|
+
fixture.close();
|
|
549
|
+
}
|
|
550
|
+
});
|
|
551
|
+
test("real AgentSession: manual hard-reserve reset stops clean and mixed-tool turns without fresh provider work", { timeout: 20000 }, async () => {
|
|
552
|
+
for (const mixed of [false, true]) {
|
|
553
|
+
let fixture;
|
|
554
|
+
let newUserAllowed = false;
|
|
555
|
+
fixture = await openFixture({
|
|
556
|
+
script: (request) => {
|
|
557
|
+
if (newUserAllowed)
|
|
558
|
+
return assistant(fixture, [{ type: "text", text: "new user turn handled" }]);
|
|
559
|
+
if (request === 1)
|
|
560
|
+
return assistant(fixture, [{ type: "text", text: "before wipe" }]);
|
|
561
|
+
assert.equal(request, 2, "no provider work follows the manual safety reset");
|
|
562
|
+
return assistant(fixture, mixed ? [
|
|
563
|
+
{ type: "toolCall", id: "pressure-note", name: "notes_write", arguments: { address: "pressure.md", content: "PRESERVED_PRESSURE_NOTE" } },
|
|
564
|
+
{ type: "toolCall", id: "pressure-wipe", name: "clear_memory", arguments: {} },
|
|
565
|
+
] : [{ type: "text", text: "close-out complete" }], mixed ? "toolUse" : "stop", { usage: usage(80_000) });
|
|
566
|
+
},
|
|
567
|
+
});
|
|
568
|
+
try {
|
|
569
|
+
await fixture.session.prompt("HARD_RESERVE_OLD_SENTINEL");
|
|
570
|
+
await fixture.session.prompt("/clear-memory");
|
|
571
|
+
await fixture.session.waitForIdle();
|
|
572
|
+
assert.equal(fixture.requests.length, 2);
|
|
573
|
+
assert.equal(resetMarkers(fixture).length, 1, "the safety wipe is not repeated at settlement");
|
|
574
|
+
assert.equal(JSON.stringify(fixture.sessionManager.buildSessionProjection().messages).includes("HARD_RESERVE_OLD_SENTINEL"), false);
|
|
575
|
+
assert.ok(fixture.notices.some((notice) => notice.includes("memory cleared")));
|
|
576
|
+
if (mixed) {
|
|
577
|
+
assert.ok(existsSync(join(fixture.notesRoot, "pi", "session", fixture.sessionManager.getSessionId(), "pressure.md")), "the whole tool batch completes before the cut");
|
|
578
|
+
assert.equal(fixture.streamSignals.at(-1), true, "Pi's unavoidable tool follow-up is cancelled before provider work");
|
|
579
|
+
}
|
|
580
|
+
// The stop latch belongs only to this run, not to future user input.
|
|
581
|
+
newUserAllowed = true;
|
|
582
|
+
await fixture.session.prompt("NEW_USER_AFTER_MANUAL_STOP");
|
|
583
|
+
await fixture.session.waitForIdle();
|
|
584
|
+
assert.equal(fixture.requests.length, 3);
|
|
585
|
+
assert.equal(fixture.streamSignals.at(-1), false);
|
|
586
|
+
assert.equal(resetMarkers(fixture).length, 1);
|
|
587
|
+
assert.ok(JSON.stringify(fixture.sessionManager.getBranch()).includes("new user turn handled"));
|
|
588
|
+
}
|
|
589
|
+
finally {
|
|
590
|
+
fixture.close();
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
});
|
|
594
|
+
test("real AgentSession: manual safety reset answers queued user input once before stopping", { timeout: 20000 }, async () => {
|
|
595
|
+
let fixture;
|
|
596
|
+
fixture = await openFixture({
|
|
597
|
+
hook: (pi, getSession) => pi.on("tool_call", async (event) => {
|
|
598
|
+
if (event.toolName === "notes_write")
|
|
599
|
+
await getSession().followUp("PRESSURE_QUEUED_USER_INPUT");
|
|
600
|
+
}),
|
|
601
|
+
script: (request, context) => {
|
|
602
|
+
if (request === 1)
|
|
603
|
+
return assistant(fixture, [{ type: "text", text: "before wipe" }]);
|
|
604
|
+
if (request === 2)
|
|
605
|
+
return assistant(fixture, [{ type: "toolCall", id: "queued-pressure-note", name: "notes_write", arguments: { address: "queued-pressure.md", content: "checkpoint" } }], "toolUse", { usage: usage(80_000) });
|
|
606
|
+
assert.equal(text(context).includes("QUEUED_SAFETY_OLD_SENTINEL"), false);
|
|
607
|
+
if (request === 3) {
|
|
608
|
+
assert.equal(text(context).includes("PRESSURE_QUEUED_USER_INPUT"), false, "Pi's tool follow-up precedes followUp queue delivery");
|
|
609
|
+
return assistant(fixture, [{ type: "text", text: "wipe complete; waiting for queued input" }]);
|
|
610
|
+
}
|
|
611
|
+
assert.equal(request, 4);
|
|
612
|
+
assert.equal(text(context).split("PRESSURE_QUEUED_USER_INPUT").length - 1, 1);
|
|
613
|
+
return assistant(fixture, [{ type: "text", text: "queued user input handled" }]);
|
|
614
|
+
},
|
|
615
|
+
});
|
|
616
|
+
try {
|
|
617
|
+
await fixture.session.prompt("QUEUED_SAFETY_OLD_SENTINEL");
|
|
618
|
+
await fixture.session.prompt("/clear-memory");
|
|
619
|
+
await fixture.session.waitForIdle();
|
|
620
|
+
assert.equal(fixture.requests.length, 4, "queued input is answered once after Pi's tool follow-up, then the stop lands");
|
|
621
|
+
assert.equal(resetMarkers(fixture).length, 1);
|
|
622
|
+
assert.equal(fixture.streamSignals.at(-1), false, "real user input must not be cancelled as an automatic follow-up");
|
|
623
|
+
}
|
|
624
|
+
finally {
|
|
625
|
+
fixture.close();
|
|
626
|
+
}
|
|
627
|
+
});
|
|
628
|
+
test("real AgentSession: manual overflow wipes and stops even with automatic reset disabled", { timeout: 20000 }, async () => {
|
|
629
|
+
let fixture;
|
|
630
|
+
fixture = await openFixture({
|
|
631
|
+
compactionEnabled: false,
|
|
632
|
+
script: (request) => {
|
|
633
|
+
if (request === 1)
|
|
634
|
+
return assistant(fixture, [{ type: "text", text: "before overflow" }]);
|
|
635
|
+
assert.equal(request, 2, "manual overflow must not trigger a recovery request");
|
|
636
|
+
return assistant(fixture, [], "error", { errorMessage: "Prompt too long: context exceeds maximum context length" });
|
|
637
|
+
},
|
|
638
|
+
});
|
|
639
|
+
try {
|
|
640
|
+
await fixture.session.prompt("MANUAL_OVERFLOW_OLD_SENTINEL");
|
|
641
|
+
await fixture.session.prompt("/clear-memory");
|
|
642
|
+
await fixture.session.waitForIdle();
|
|
643
|
+
assert.equal(fixture.requests.length, 2);
|
|
644
|
+
assert.equal(resetMarkers(fixture).length, 1);
|
|
645
|
+
assert.equal(JSON.stringify(fixture.sessionManager.buildSessionProjection().messages).includes("MANUAL_OVERFLOW_OLD_SENTINEL"), false);
|
|
646
|
+
assert.ok(fixture.notices.some((notice) => notice.includes("memory cleared")));
|
|
647
|
+
}
|
|
648
|
+
finally {
|
|
649
|
+
fixture.close();
|
|
650
|
+
}
|
|
651
|
+
});
|
|
652
|
+
test("real AgentSession: streaming /clear-memory steers a close-out and stops at settlement", { timeout: 20000 }, async () => {
|
|
653
|
+
let fixture;
|
|
654
|
+
let announceStarted;
|
|
655
|
+
let releaseResponse;
|
|
656
|
+
const started = new Promise((resolve) => { announceStarted = resolve; });
|
|
657
|
+
const gate = new Promise((resolve) => { releaseResponse = resolve; });
|
|
658
|
+
fixture = await openFixture({
|
|
659
|
+
compactionEnabled: false,
|
|
660
|
+
script: async (request, context) => {
|
|
661
|
+
if (request === 1) {
|
|
662
|
+
announceStarted();
|
|
663
|
+
await gate;
|
|
664
|
+
return assistant(fixture, [{ type: "text", text: "current response finished" }]);
|
|
665
|
+
}
|
|
666
|
+
assert.equal(request, 2, "the steered warning gets exactly one close-out turn before the run stops");
|
|
667
|
+
assert.ok(text(context).includes(WARNING_PROMPT), "the busy warning is delivered to the running agent");
|
|
668
|
+
return assistant(fixture, [{ type: "text", text: "close-out complete" }]);
|
|
669
|
+
},
|
|
670
|
+
});
|
|
671
|
+
try {
|
|
672
|
+
const running = fixture.session.prompt("STREAMING_WIPE_OLD_SENTINEL");
|
|
673
|
+
await started;
|
|
674
|
+
await fixture.session.prompt("/clear-memory", { streamingBehavior: "steer" });
|
|
675
|
+
await fixture.session.prompt("/clear-memory", { streamingBehavior: "followUp" });
|
|
676
|
+
assert.equal(fixture.notices.filter((notice) => notice.includes("queued; the agent is asked to close out")).length, 1, "the user is notified once while output is ongoing");
|
|
677
|
+
assert.equal(resetMarkers(fixture).length, 0, "the ongoing turn is not interrupted");
|
|
678
|
+
releaseResponse();
|
|
679
|
+
await running;
|
|
680
|
+
await fixture.session.waitForIdle();
|
|
681
|
+
assert.equal(resetMarkers(fixture).length, 1);
|
|
682
|
+
assert.equal(fixture.requests.length, 2, "the warning closes out and the run stops — no continuation in the fresh window");
|
|
683
|
+
assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === MANUAL_WIPE_TYPE).length, 1, "the busy warning is persisted once");
|
|
684
|
+
assert.equal(JSON.stringify(fixture.sessionManager.buildSessionProjection().messages).includes("STREAMING_WIPE_OLD_SENTINEL"), false);
|
|
685
|
+
assert.ok(fixture.notices.some((notice) => notice.includes("memory cleared")), "the committed boundary has a separate success notice");
|
|
686
|
+
}
|
|
687
|
+
finally {
|
|
688
|
+
releaseResponse();
|
|
689
|
+
fixture.close();
|
|
690
|
+
}
|
|
691
|
+
});
|
|
692
|
+
test("real AgentSession: repeated manual commands share one pending window", { timeout: 20000 }, async () => {
|
|
693
|
+
let fixture;
|
|
694
|
+
let announceStarted;
|
|
695
|
+
let releaseResponse;
|
|
696
|
+
const started = new Promise((resolve) => { announceStarted = resolve; });
|
|
697
|
+
const gate = new Promise((resolve) => { releaseResponse = resolve; });
|
|
698
|
+
fixture = await openFixture({
|
|
699
|
+
compactionEnabled: false,
|
|
700
|
+
script: async (request) => {
|
|
701
|
+
if (request === 1) {
|
|
702
|
+
announceStarted();
|
|
703
|
+
await gate;
|
|
704
|
+
}
|
|
705
|
+
return assistant(fixture, [{ type: "text", text: "close-out complete" }]);
|
|
706
|
+
},
|
|
707
|
+
});
|
|
708
|
+
try {
|
|
709
|
+
const first = fixture.session.prompt("/clear-memory");
|
|
710
|
+
await started;
|
|
711
|
+
const second = fixture.session.prompt("/clear-memory");
|
|
712
|
+
releaseResponse();
|
|
713
|
+
await Promise.all([first, second]);
|
|
714
|
+
await fixture.session.waitForIdle();
|
|
715
|
+
assert.equal(fixture.requests.length, 1, "duplicate command waits do not schedule another model request");
|
|
716
|
+
assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === MANUAL_WIPE_TYPE).length, 1, "the same pending-window warning is deduplicated");
|
|
717
|
+
assert.equal(resetMarkers(fixture).length, 1, "normal stop commits exactly one reset");
|
|
718
|
+
assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "compaction").length, 1);
|
|
719
|
+
}
|
|
720
|
+
finally {
|
|
721
|
+
releaseResponse();
|
|
722
|
+
fixture.close();
|
|
723
|
+
}
|
|
724
|
+
});
|
|
725
|
+
test("real AgentSession: user abort, synthetic aborted response, and generic error never fall back", { timeout: 25000 }, async () => {
|
|
726
|
+
for (const mode of ["ctx-abort", "synthetic-abort", "generic-error"]) {
|
|
727
|
+
let fixture;
|
|
728
|
+
let didAbort = false;
|
|
729
|
+
fixture = await openFixture({
|
|
730
|
+
compactionEnabled: false,
|
|
731
|
+
hook: mode === "ctx-abort" ? (pi) => pi.on("context", (_event, ctx) => {
|
|
732
|
+
if (!didAbort) {
|
|
733
|
+
didAbort = true;
|
|
734
|
+
ctx.abort();
|
|
735
|
+
}
|
|
736
|
+
}) : undefined,
|
|
737
|
+
script: (request) => {
|
|
738
|
+
if (request === 1 && mode === "synthetic-abort")
|
|
739
|
+
return assistant(fixture, [{ type: "text", text: "synthetic aborted" }], "aborted");
|
|
740
|
+
if (request === 1 && mode === "generic-error")
|
|
741
|
+
return assistant(fixture, [{ type: "text", text: "request failed" }], "error", { errorMessage: "synthetic generic provider failure" });
|
|
742
|
+
return assistant(fixture, [{ type: "text", text: "later user turn" }]);
|
|
743
|
+
},
|
|
744
|
+
});
|
|
745
|
+
try {
|
|
746
|
+
await fixture.session.prompt("/cm SHOULD_NOT_RUN_AFTER_FAILURE");
|
|
747
|
+
await fixture.session.waitForIdle();
|
|
748
|
+
assert.equal(resetMarkers(fixture).length, 0, `${mode} does not force a reset`);
|
|
749
|
+
assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "compaction").length, 0);
|
|
750
|
+
assert.equal(fixture.notices.some((notice) => notice.includes("memory cleared")), false);
|
|
751
|
+
if (mode === "ctx-abort")
|
|
752
|
+
assert.equal(fixture.streamSignals.at(-1), true, "this case aborts the real Pi operation signal");
|
|
753
|
+
else
|
|
754
|
+
assert.equal(fixture.streamSignals.at(-1), false, "synthetic abort/error is not a user abort signal");
|
|
755
|
+
await fixture.session.prompt("AFTER_UNSUCCESSFUL_CLOSEOUT");
|
|
756
|
+
await fixture.session.waitForIdle();
|
|
757
|
+
assert.equal(resetMarkers(fixture).length, 0, "no pending close-out leaks into a later prompt");
|
|
758
|
+
assert.equal(JSON.stringify(fixture.sessionManager.getBranch()).includes("SHOULD_NOT_RUN_AFTER_FAILURE"), false, "cancelled prompt is never appended");
|
|
759
|
+
}
|
|
760
|
+
finally {
|
|
761
|
+
fixture.close();
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
});
|
|
765
|
+
test("real AgentSession: steering and follow-up queued during a manual reset are answered before the stop", { timeout: 25000 }, async () => {
|
|
766
|
+
for (const delivery of ["steer", "followUp"]) {
|
|
767
|
+
let fixture;
|
|
768
|
+
let announceStarted;
|
|
769
|
+
let releaseResponse;
|
|
770
|
+
const started = new Promise((resolve) => { announceStarted = resolve; });
|
|
771
|
+
const gate = new Promise((resolve) => { releaseResponse = resolve; });
|
|
772
|
+
fixture = await openFixture({
|
|
773
|
+
compactionEnabled: false,
|
|
774
|
+
script: async (request, context) => {
|
|
775
|
+
if (request === 1) {
|
|
776
|
+
assert.ok(text(context).includes(WARNING_PROMPT));
|
|
777
|
+
announceStarted();
|
|
778
|
+
await gate;
|
|
779
|
+
}
|
|
780
|
+
if (request === 2) {
|
|
781
|
+
assert.ok(text(context).includes(WARNING_PROMPT), `${delivery} is answered in the old window before the reset commits`);
|
|
782
|
+
assert.equal(text(context).split("QUEUED_DURING_FALLBACK").length - 1, 1, `${delivery} is delivered once`);
|
|
783
|
+
}
|
|
784
|
+
return assistant(fixture, [{ type: "text", text: `response ${request}` }]);
|
|
785
|
+
},
|
|
786
|
+
});
|
|
787
|
+
try {
|
|
788
|
+
const command = fixture.session.prompt("/clear-memory");
|
|
789
|
+
await started;
|
|
790
|
+
if (delivery === "steer")
|
|
791
|
+
fixture.session.steer("QUEUED_DURING_FALLBACK");
|
|
792
|
+
else
|
|
793
|
+
fixture.session.followUp("QUEUED_DURING_FALLBACK");
|
|
794
|
+
releaseResponse();
|
|
795
|
+
await command;
|
|
796
|
+
await fixture.session.waitForIdle();
|
|
797
|
+
assert.equal(fixture.requests.length, 2, `${delivery} is answered, then the reset commits at settlement with no continuation`);
|
|
798
|
+
assert.equal(resetMarkers(fixture).length, 1, `${delivery} does not duplicate the reset`);
|
|
799
|
+
assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "message" && JSON.stringify(entry.message).includes("QUEUED_DURING_FALLBACK")).length, 1);
|
|
800
|
+
}
|
|
801
|
+
finally {
|
|
802
|
+
releaseResponse();
|
|
803
|
+
fixture.close();
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
});
|
|
807
|
+
test("real AgentSession: a reset survives all notes-home read failures with an incomplete boot", { timeout: 15000 }, async () => {
|
|
808
|
+
let fixture;
|
|
809
|
+
fixture = await openFixture({
|
|
810
|
+
compactionEnabled: false,
|
|
811
|
+
notesRootFile: true,
|
|
812
|
+
script: (request) => request === 1
|
|
813
|
+
? assistant(fixture, [{ type: "toolCall", id: "wipe-notes-failure", name: "clear_memory", arguments: {} }], "toolUse")
|
|
814
|
+
: assistant(fixture, [{ type: "text", text: "resumed despite notes failure" }]),
|
|
815
|
+
});
|
|
816
|
+
try {
|
|
817
|
+
await fixture.session.prompt("NOTES_FAILURE_RESET_SENTINEL");
|
|
818
|
+
await fixture.session.waitForIdle();
|
|
819
|
+
assert.equal(fixture.requests.length, 2, "the failed notes index does not cancel the continuation");
|
|
820
|
+
assertFreshRequest(fixture, 1, "NOTES_FAILURE_RESET_SENTINEL");
|
|
821
|
+
assert.equal(resetMarkers(fixture).length, 1, "one reset marker is committed");
|
|
822
|
+
const marker = resetMarkers(fixture)[0];
|
|
823
|
+
assert.equal(marker.type, "custom");
|
|
824
|
+
const windowId = marker.data.windowId;
|
|
825
|
+
const boot = fixture.sessionManager.getBranch().find((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE && entry.details && typeof entry.details === "object" && entry.details.windowId === windowId);
|
|
826
|
+
assert.ok(boot && boot.type === "custom_message");
|
|
827
|
+
const bootText = typeof boot.content === "string" ? boot.content : JSON.stringify(boot.content);
|
|
828
|
+
assert.ok(bootText.includes("THE HUMAN · @human"));
|
|
829
|
+
assert.equal(bootText.match(/This drawer wouldn't open/g)?.length, 5, "each failed section gets one recovery line");
|
|
830
|
+
assert.ok(bootText.includes("<context_window_protocol>"));
|
|
831
|
+
}
|
|
832
|
+
finally {
|
|
833
|
+
fixture.close();
|
|
834
|
+
}
|
|
835
|
+
});
|
|
836
|
+
test("real AgentSession: reset projection drops legacy message shapes but keeps raw history and equal/backwards new timestamps", { timeout: 15000 }, async () => {
|
|
837
|
+
let fixture;
|
|
838
|
+
const legacyTimestamp = Date.now();
|
|
839
|
+
const legacyTexts = [
|
|
840
|
+
"OLD_BASH_EXECUTION",
|
|
841
|
+
"OLD_TOOL_RESULT",
|
|
842
|
+
"OLD_COMPACTION_SUMMARY_WRAPPER",
|
|
843
|
+
"OLD_BRANCH_SUMMARY",
|
|
844
|
+
];
|
|
845
|
+
fixture = await openFixture({
|
|
846
|
+
compactionEnabled: false,
|
|
847
|
+
seed: (sessionManager) => {
|
|
848
|
+
sessionManager.appendMessage({ role: "user", content: [{ type: "text", text: "OLD_USER_BEFORE_LEGACY_ENTRIES" }], timestamp: legacyTimestamp });
|
|
849
|
+
sessionManager.appendMessage({ role: "bashExecution", command: legacyTexts[0], output: legacyTexts[0], exitCode: 0, cancelled: false, truncated: false, timestamp: legacyTimestamp });
|
|
850
|
+
sessionManager.appendMessage({ role: "toolResult", content: [{ type: "text", text: legacyTexts[1] }], toolCallId: "legacy-tool", toolName: "bash", isError: false, timestamp: legacyTimestamp });
|
|
851
|
+
const compactionParent = sessionManager.getLeafId();
|
|
852
|
+
sessionManager.appendCompaction(legacyTexts[2], compactionParent, 123, { legacy: true }, true);
|
|
853
|
+
sessionManager.branchWithSummary(sessionManager.getLeafId(), legacyTexts[3], { legacy: true }, true);
|
|
854
|
+
},
|
|
855
|
+
script: (request, context) => {
|
|
856
|
+
if (request === 1)
|
|
857
|
+
return assistant(fixture, [{ type: "toolCall", id: "wipe-legacy", name: "clear_memory", arguments: {} }], "toolUse");
|
|
858
|
+
if (request === 2) {
|
|
859
|
+
const body = text(context);
|
|
860
|
+
for (const legacy of legacyTexts)
|
|
861
|
+
assert.equal(body.includes(legacy), false, `${legacy} is cut from the reset projection`);
|
|
862
|
+
return assistant(fixture, [{ type: "toolCall", id: "new-timestamp", name: "notes_write", arguments: { address: "equal-timestamp.md", content: "NEW_EQUAL_BACKWARDS_MESSAGE" } }], "toolUse", { timestamp: legacyTimestamp - 1 });
|
|
863
|
+
}
|
|
864
|
+
const body = text(context);
|
|
865
|
+
for (const legacy of legacyTexts)
|
|
866
|
+
assert.equal(body.includes(legacy), false, `${legacy} stays absent after another fresh-window turn`);
|
|
867
|
+
assert.ok(body.includes("NEW_EQUAL_BACKWARDS_MESSAGE"), "a new message with an equal/backwards timestamp survives the projection");
|
|
868
|
+
const newAssistant = context.messages.find((message) => message.role === "assistant" && JSON.stringify(message).includes("NEW_EQUAL_BACKWARDS_MESSAGE"));
|
|
869
|
+
assert.equal(newAssistant?.timestamp, legacyTimestamp - 1, "projection preserves the new message timestamp");
|
|
870
|
+
return assistant(fixture, [{ type: "text", text: "legacy projection clean" }]);
|
|
871
|
+
},
|
|
872
|
+
});
|
|
873
|
+
try {
|
|
874
|
+
await fixture.session.prompt("NEW_WINDOW_PROJECTION_SENTINEL");
|
|
875
|
+
await fixture.session.waitForIdle();
|
|
876
|
+
assert.equal(fixture.requests.length, 3, "the fresh window accepts one additional new-window tool turn");
|
|
877
|
+
assert.equal(resetMarkers(fixture).length, 1);
|
|
878
|
+
const raw = JSON.stringify(fixture.sessionManager.getBranch());
|
|
879
|
+
for (const legacy of legacyTexts)
|
|
880
|
+
assert.ok(raw.includes(legacy), `${legacy} remains in durable raw history`);
|
|
881
|
+
}
|
|
882
|
+
finally {
|
|
883
|
+
fixture.close();
|
|
884
|
+
}
|
|
885
|
+
});
|
|
886
|
+
test("real AgentSession: successive resets and a mixed tool batch cut only after every tool result", async () => {
|
|
887
|
+
for (const scenario of ["successive", "mixed"]) {
|
|
888
|
+
let fixture;
|
|
889
|
+
fixture = await openFixture({
|
|
890
|
+
compactionEnabled: false,
|
|
891
|
+
script: (request) => {
|
|
892
|
+
if (scenario === "successive" && request < 3)
|
|
893
|
+
return assistant(fixture, [{ type: "toolCall", id: `wipe-${request}`, name: "clear_memory", arguments: {} }], "toolUse");
|
|
894
|
+
if (scenario === "mixed" && request === 1)
|
|
895
|
+
return assistant(fixture, [
|
|
896
|
+
{ type: "toolCall", id: "wipe-1", name: "clear_memory", arguments: {} },
|
|
897
|
+
{ type: "toolCall", id: "note-1", name: "notes_write", arguments: { address: "batch.md", content: "MIXED_BATCH_NOTE" } },
|
|
898
|
+
], "toolUse");
|
|
899
|
+
return assistant(fixture, [{ type: "text", text: "fresh completion" }]);
|
|
900
|
+
},
|
|
901
|
+
});
|
|
902
|
+
try {
|
|
903
|
+
await fixture.session.prompt(`OLD_${scenario.toUpperCase()}_SENTINEL`);
|
|
904
|
+
await fixture.session.waitForIdle();
|
|
905
|
+
const expected = scenario === "successive" ? 2 : 1;
|
|
906
|
+
assert.equal(resetMarkers(fixture).length, expected);
|
|
907
|
+
assert.equal(fixture.requests.length, expected + 1);
|
|
908
|
+
assertFreshRequest(fixture, fixture.requests.length - 1, `OLD_${scenario.toUpperCase()}_SENTINEL`);
|
|
909
|
+
if (scenario === "mixed") {
|
|
910
|
+
const branch = fixture.sessionManager.getBranch();
|
|
911
|
+
const markerIndex = branch.findIndex((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE);
|
|
912
|
+
assert.ok(markerIndex > 0, "the marker follows the completed tool batch");
|
|
913
|
+
assert.ok(branch.slice(0, markerIndex).some((entry) => entry.type === "message" && entry.message.role === "toolResult" && entry.message.toolName === "notes_write"), "notes_write completes before the cut");
|
|
914
|
+
assert.ok(existsSync(join(fixture.notesRoot, "pi", "session", fixture.sessionManager.getSessionId(), "batch.md")));
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
finally {
|
|
918
|
+
fixture.close();
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
});
|
|
922
|
+
test("real AgentSession: two retain-none checkpoints survive session-file reopen", { timeout: 20000 }, async () => {
|
|
923
|
+
const sessionDir = mkdtempSync(join(tmpdir(), "notesoup-persisted-session-"));
|
|
924
|
+
let fixture;
|
|
925
|
+
let sessionFile = "";
|
|
926
|
+
let sessionId = "";
|
|
927
|
+
fixture = await openFixture({
|
|
928
|
+
compactionEnabled: false,
|
|
929
|
+
sessionDir,
|
|
930
|
+
script: (request) => request < 3
|
|
931
|
+
? assistant(fixture, [{ type: "toolCall", id: `persisted-wipe-${request}`, name: "clear_memory", arguments: {} }], "toolUse")
|
|
932
|
+
: assistant(fixture, [{ type: "text", text: "second reset window complete" }]),
|
|
933
|
+
});
|
|
934
|
+
try {
|
|
935
|
+
await fixture.session.prompt("PERSISTED_OLD_WINDOW_SENTINEL");
|
|
936
|
+
await fixture.session.waitForIdle();
|
|
937
|
+
assert.equal(fixture.requests.length, 3, "two explicit requests and one final continuation, with no summary-model request");
|
|
938
|
+
assert.equal(resetMarkers(fixture).length, 2);
|
|
939
|
+
assertFreshRequest(fixture, 2, "PERSISTED_OLD_WINDOW_SENTINEL");
|
|
940
|
+
const branch = fixture.sessionManager.getBranch();
|
|
941
|
+
const checkpoints = branch.filter((entry) => entry.type === "compaction");
|
|
942
|
+
assert.equal(checkpoints.length, 2);
|
|
943
|
+
const markers = resetMarkers(fixture);
|
|
944
|
+
assert.equal(markers[0]?.parentId, checkpoints[0]?.id);
|
|
945
|
+
assert.equal(markers[1]?.parentId, checkpoints[1]?.id);
|
|
946
|
+
assert.equal(checkpoints[0]?.type === "compaction" ? checkpoints[0].firstKeptEntryId : undefined, checkpoints[0]?.id);
|
|
947
|
+
assert.equal(checkpoints[1]?.type === "compaction" ? checkpoints[1].firstKeptEntryId : undefined, checkpoints[1]?.id);
|
|
948
|
+
sessionFile = fixture.sessionManager.getSessionFile() ?? "";
|
|
949
|
+
sessionId = fixture.sessionManager.getSessionId();
|
|
950
|
+
assert.ok(sessionFile && existsSync(sessionFile), "the SDK persisted the real session file");
|
|
951
|
+
}
|
|
952
|
+
finally {
|
|
953
|
+
fixture.close();
|
|
954
|
+
}
|
|
955
|
+
try {
|
|
956
|
+
const reopened = SessionManager.open(sessionFile, sessionDir);
|
|
957
|
+
assert.equal(reopened.getSessionId(), sessionId);
|
|
958
|
+
const branch = reopened.getBranch();
|
|
959
|
+
assert.equal(branch.filter((entry) => entry.type === "compaction").length, 2);
|
|
960
|
+
assert.equal(branch.filter((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE).length, 2);
|
|
961
|
+
assert.ok(JSON.stringify(branch).includes("PERSISTED_OLD_WINDOW_SENTINEL"), "raw history survives disk reopen");
|
|
962
|
+
const canonical = reopened.buildSessionProjection().messages;
|
|
963
|
+
assert.equal(JSON.stringify(canonical).includes("PERSISTED_OLD_WINDOW_SENTINEL"), false, "disk-loaded canonical context agrees with the fresh request");
|
|
964
|
+
assert.ok(canonical.some((message) => message.role === "compactionSummary"), "the accepted empty-summary wrapper survives reload");
|
|
965
|
+
const system = getCurrentSystemMessage(canonical);
|
|
966
|
+
assert.ok(JSON.stringify(system).includes("Use the tools as requested."), "the complete system prompt survives the checkpoint");
|
|
967
|
+
assert.ok(system?.toolsAdded?.some((tool) => tool.name === "clear_memory"), "the active tool loadout survives reopen");
|
|
968
|
+
const reopenedMarkers = branch.filter((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE);
|
|
969
|
+
const latestMarker = reopenedMarkers.at(-1);
|
|
970
|
+
const previousMarker = reopenedMarkers[0];
|
|
971
|
+
assert.ok(latestMarker?.type === "custom" && previousMarker?.type === "custom");
|
|
972
|
+
const latestWindowId = latestMarker.data.windowId;
|
|
973
|
+
const previousWindowId = previousMarker.data.windowId;
|
|
974
|
+
const latestBoot = branch.find((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE && entry.details?.windowId === latestWindowId);
|
|
975
|
+
assert.ok(latestBoot && latestBoot.type === "custom_message" && typeof latestBoot.content === "string");
|
|
976
|
+
assert.ok(latestBoot.content.includes(`Previous context window id: ${previousWindowId}`));
|
|
977
|
+
}
|
|
978
|
+
finally {
|
|
979
|
+
rmSync(sessionDir, { recursive: true, force: true });
|
|
980
|
+
}
|
|
981
|
+
});
|
|
982
|
+
test("real AgentSession: steering and follow-up are delivered exactly once in the fresh window", async () => {
|
|
983
|
+
for (const deliverAs of ["steer", "followUp"]) {
|
|
984
|
+
let fixture;
|
|
985
|
+
fixture = await openFixture({
|
|
986
|
+
compactionEnabled: false,
|
|
987
|
+
hook: (pi, getSession) => {
|
|
988
|
+
pi.on("tool_call", async (event) => {
|
|
989
|
+
if (event.toolName !== "clear_memory")
|
|
990
|
+
return;
|
|
991
|
+
if (deliverAs === "steer")
|
|
992
|
+
await getSession().steer("QUEUED_ONCE");
|
|
993
|
+
else
|
|
994
|
+
await getSession().followUp("QUEUED_ONCE");
|
|
995
|
+
});
|
|
996
|
+
},
|
|
997
|
+
script: (request) => request === 1
|
|
998
|
+
? assistant(fixture, [{ type: "toolCall", id: "wipe-queue", name: "clear_memory", arguments: {} }], "toolUse")
|
|
999
|
+
: assistant(fixture, [{ type: "text", text: "queued message handled" }]),
|
|
1000
|
+
});
|
|
1001
|
+
try {
|
|
1002
|
+
await fixture.session.prompt(`OLD_${deliverAs}_SENTINEL`);
|
|
1003
|
+
await fixture.session.waitForIdle();
|
|
1004
|
+
assert.equal(fixture.requests.length, 2, `${deliverAs} does not duplicate the resumed request`);
|
|
1005
|
+
assertFreshRequest(fixture, 1, `OLD_${deliverAs}_SENTINEL`);
|
|
1006
|
+
assert.equal(text(fixture.requests[1]).split("QUEUED_ONCE").length - 1, 1, `${deliverAs} arrives once in the new window`);
|
|
1007
|
+
const queued = fixture.sessionManager.getBranch().filter((entry) => entry.type === "message" && JSON.stringify(entry.message).includes("QUEUED_ONCE"));
|
|
1008
|
+
assert.equal(queued.length, 1, `${deliverAs} has one durable user message`);
|
|
1009
|
+
}
|
|
1010
|
+
finally {
|
|
1011
|
+
fixture.close();
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
});
|
|
1015
|
+
test("real AgentSession: hidden or missing reset boots refuse to move the boundary", { timeout: 15000 }, async () => {
|
|
1016
|
+
let fixture;
|
|
1017
|
+
fixture = await openFixture({
|
|
1018
|
+
compactionEnabled: false,
|
|
1019
|
+
script: () => assistant(fixture, [{ type: "text", text: "scripted acknowledgement" }]),
|
|
1020
|
+
});
|
|
1021
|
+
try {
|
|
1022
|
+
await fixture.session.prompt("ROOT_BEFORE_HIDDEN_BOOT");
|
|
1023
|
+
await fixture.session.waitForIdle();
|
|
1024
|
+
await fixture.session.prompt("/clear-memory");
|
|
1025
|
+
await fixture.session.waitForIdle();
|
|
1026
|
+
await fixture.session.prompt("VALID_POST_MARKER_WORK");
|
|
1027
|
+
await fixture.session.waitForIdle();
|
|
1028
|
+
const marker = resetMarkers(fixture)[0];
|
|
1029
|
+
assert.ok(marker && marker.type === "custom");
|
|
1030
|
+
const windowId = marker.data.windowId;
|
|
1031
|
+
const boot = fixture.sessionManager.getBranch().find((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE && entry.details && typeof entry.details === "object" && entry.details.windowId === windowId);
|
|
1032
|
+
assert.ok(boot && boot.type === "custom_message");
|
|
1033
|
+
fixture.sessionManager.appendContextEdit(boot.id, null);
|
|
1034
|
+
const bootCount = () => fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE && entry.details && typeof entry.details === "object" && entry.details.windowId === windowId).length;
|
|
1035
|
+
assert.equal(bootCount(), 1);
|
|
1036
|
+
await fixture.session.reload();
|
|
1037
|
+
assert.equal(bootCount(), 1, "a raw boot hidden by context_edit is not replaced at the tail");
|
|
1038
|
+
const requestsBeforeRefusal = fixture.requests.length;
|
|
1039
|
+
await fixture.session.prompt("MISSING_PROJECTED_BOOT_SENTINEL");
|
|
1040
|
+
await fixture.session.waitForIdle();
|
|
1041
|
+
assert.equal(bootCount(), 1, "a refused active window never receives a replacement boot");
|
|
1042
|
+
assert.ok(fixture.requests.length <= requestsBeforeRefusal, "the normal provider request is not generated from a shortened window");
|
|
1043
|
+
const safeContext = fixture.streamContexts.at(-1);
|
|
1044
|
+
assert.ok(safeContext, "the SDK may still invoke the stream function with an aborted signal");
|
|
1045
|
+
assert.ok(safeContext.messages.every((message) => message.role === "system"), "a refused request receives system-only safe context");
|
|
1046
|
+
assert.equal(fixture.streamSignals.at(-1), true, "the refused request is aborted before provider work");
|
|
1047
|
+
assert.ok(JSON.stringify(fixture.sessionManager.getBranch()).includes("VALID_POST_MARKER_WORK"), "raw post-marker work remains durable");
|
|
1048
|
+
}
|
|
1049
|
+
finally {
|
|
1050
|
+
fixture.close();
|
|
1051
|
+
}
|
|
1052
|
+
let missingRaw;
|
|
1053
|
+
missingRaw = await openFixture({
|
|
1054
|
+
compactionEnabled: false,
|
|
1055
|
+
seed: (sessionManager) => {
|
|
1056
|
+
sessionManager.appendCustomEntry(RESET_MARKER_TYPE, { windowId: "pcw:missing:boot" });
|
|
1057
|
+
sessionManager.appendMessage({ role: "user", content: [{ type: "text", text: "RAW_POST_MARKER_WORK" }], timestamp: Date.now() });
|
|
1058
|
+
},
|
|
1059
|
+
script: () => assistant(missingRaw, [{ type: "text", text: "must not be called normally" }]),
|
|
1060
|
+
});
|
|
1061
|
+
try {
|
|
1062
|
+
assert.equal(missingRaw.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE).length, 0, "post-marker conversation blocks startup repair");
|
|
1063
|
+
await missingRaw.session.prompt("MISSING_RAW_BOOT_SENTINEL");
|
|
1064
|
+
await missingRaw.session.waitForIdle();
|
|
1065
|
+
assert.equal(missingRaw.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE).length, 0, "later conversation without a boot is refused, not repaired");
|
|
1066
|
+
assert.equal(missingRaw.streamSignals.at(-1), true);
|
|
1067
|
+
assert.ok(missingRaw.streamContexts.at(-1)?.messages.every((message) => message.role === "system"));
|
|
1068
|
+
}
|
|
1069
|
+
finally {
|
|
1070
|
+
missingRaw.close();
|
|
1071
|
+
}
|
|
1072
|
+
});
|
|
1073
|
+
test("real AgentSession: the complete system message and a changed tool loadout survive the reset projection", async () => {
|
|
1074
|
+
let fixture;
|
|
1075
|
+
fixture = await openFixture({
|
|
1076
|
+
compactionEnabled: false,
|
|
1077
|
+
systemPrompt: ["SYSTEM_SECTION_ALPHA", "SYSTEM_SECTION_BETA", "SYSTEM_TOOLS_SECTION", "SYSTEM_LOADOUT_SECTION"].join("\n"),
|
|
1078
|
+
tools: ["clear_memory"],
|
|
1079
|
+
script: (request, context) => {
|
|
1080
|
+
const systemText = JSON.stringify(context.messages.filter((message) => message.role === "system"));
|
|
1081
|
+
const currentSystem = getCurrentSystemMessage(context.messages);
|
|
1082
|
+
const effectiveToolNames = (currentSystem?.toolsAdded ?? []).map((tool) => tool.name).sort();
|
|
1083
|
+
assert.ok(systemText.includes("SYSTEM_SECTION_ALPHA"));
|
|
1084
|
+
assert.ok(systemText.includes("SYSTEM_SECTION_BETA"));
|
|
1085
|
+
assert.ok(systemText.includes("SYSTEM_TOOLS_SECTION"));
|
|
1086
|
+
assert.ok(systemText.includes("SYSTEM_LOADOUT_SECTION"));
|
|
1087
|
+
if (request === 1) {
|
|
1088
|
+
assert.deepEqual(effectiveToolNames, ["clear_memory"]);
|
|
1089
|
+
fixture.session.setActiveToolsByName(["clear_memory", "get_context_remaining"]);
|
|
1090
|
+
return assistant(fixture, [{ type: "toolCall", id: "wipe-system", name: "clear_memory", arguments: {} }], "toolUse");
|
|
1091
|
+
}
|
|
1092
|
+
assert.deepEqual(effectiveToolNames, ["get_context_remaining", "clear_memory"]);
|
|
1093
|
+
assert.ok(JSON.stringify(context.messages).includes(CONTEXT_WINDOW_OPEN_TAG));
|
|
1094
|
+
return assistant(fixture, [{ type: "text", text: "all system sections survived" }]);
|
|
1095
|
+
},
|
|
1096
|
+
});
|
|
1097
|
+
try {
|
|
1098
|
+
await fixture.session.prompt("SYSTEM_LOADOUT_SENTINEL");
|
|
1099
|
+
await fixture.session.waitForIdle();
|
|
1100
|
+
assert.equal(fixture.requests.length, 2);
|
|
1101
|
+
assertFreshRequest(fixture, 1, "SYSTEM_LOADOUT_SENTINEL");
|
|
1102
|
+
}
|
|
1103
|
+
finally {
|
|
1104
|
+
fixture.close();
|
|
1105
|
+
}
|
|
1106
|
+
});
|
|
1107
|
+
test("real AgentSession: overflow and recoverable length reset and retry once; repeated failure is bounded", { timeout: 15000 }, async () => {
|
|
1108
|
+
for (const failure of ["overflow", "length"]) {
|
|
1109
|
+
let fixture;
|
|
1110
|
+
fixture = await openFixture({
|
|
1111
|
+
script: (request) => {
|
|
1112
|
+
if (request === 1 && failure === "overflow")
|
|
1113
|
+
return assistant(fixture, [{ type: "text", text: "overflow response" }], "error", { errorMessage: "Prompt too long: context exceeds maximum context length" });
|
|
1114
|
+
if (request === 1)
|
|
1115
|
+
return assistant(fixture, [{ type: "text", text: "truncated" }], "length", { usage: usage(99_000, 1) });
|
|
1116
|
+
return assistant(fixture, [{ type: "text", text: "recovered" }]);
|
|
1117
|
+
},
|
|
1118
|
+
});
|
|
1119
|
+
try {
|
|
1120
|
+
await fixture.session.prompt(`RECOVER_${failure}_SENTINEL`);
|
|
1121
|
+
await fixture.session.waitForIdle();
|
|
1122
|
+
assert.equal(resetMarkers(fixture).length, 1, `${failure} performs one reset`);
|
|
1123
|
+
assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "compaction").length, 1, `${failure} commits one native reset checkpoint`);
|
|
1124
|
+
assert.equal(fixture.requests.length, 2, `${failure} resumes once`);
|
|
1125
|
+
assertFreshRequest(fixture, 1, `RECOVER_${failure}_SENTINEL`);
|
|
1126
|
+
}
|
|
1127
|
+
finally {
|
|
1128
|
+
fixture.close();
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
let repeated;
|
|
1132
|
+
repeated = await openFixture({
|
|
1133
|
+
script: (request) => assistant(repeated, [{ type: "text", text: `overflow-${request}` }], "error", { errorMessage: "Prompt too long: context exceeds maximum context length" }),
|
|
1134
|
+
});
|
|
1135
|
+
try {
|
|
1136
|
+
await repeated.session.prompt("REPEATED_OVERFLOW_SENTINEL");
|
|
1137
|
+
await repeated.session.waitForIdle();
|
|
1138
|
+
assert.equal(resetMarkers(repeated).length, 1, "repeated overflow does not create repeated windows");
|
|
1139
|
+
assert.equal(repeated.sessionManager.getBranch().filter((entry) => entry.type === "compaction").length, 1, "bounded overflow recovery commits one retain-none checkpoint");
|
|
1140
|
+
assert.equal(repeated.requests.length, 2, "repeated overflow stops after one recovery request");
|
|
1141
|
+
}
|
|
1142
|
+
finally {
|
|
1143
|
+
repeated.close();
|
|
1144
|
+
}
|
|
1145
|
+
});
|
|
1146
|
+
test("real AgentSession: concurrent trusted projects keep reserve and automatic policy isolated", { timeout: 20000 }, async () => {
|
|
1147
|
+
const agentDir = mkdtempSync(join(tmpdir(), "notesoup-shared-agent-"));
|
|
1148
|
+
const notesRoot = mkdtempSync(join(tmpdir(), "notesoup-shared-notes-"));
|
|
1149
|
+
const cwdAutomatic = mkdtempSync(join(tmpdir(), "notesoup-project-automatic-"));
|
|
1150
|
+
const cwdModel = mkdtempSync(join(tmpdir(), "notesoup-project-model-"));
|
|
1151
|
+
const cwdSession = mkdtempSync(join(tmpdir(), "notesoup-project-session-"));
|
|
1152
|
+
writeFileSync(join(agentDir, "settings.json"), JSON.stringify({
|
|
1153
|
+
compaction: { enabled: true, reserveTokens: 70_000, keepRecentTokens: 200 },
|
|
1154
|
+
retry: { enabled: false },
|
|
1155
|
+
}));
|
|
1156
|
+
let automatic;
|
|
1157
|
+
let modelInvalidated;
|
|
1158
|
+
let sessionInvalidated;
|
|
1159
|
+
const script = (fixture, highUsage) => () => {
|
|
1160
|
+
const response = assistant(fixture(), [{ type: "text", text: "policy isolation response" }], "stop", { usage: usage(highUsage.next ? 85_000 : 100) });
|
|
1161
|
+
highUsage.next = false;
|
|
1162
|
+
return response;
|
|
1163
|
+
};
|
|
1164
|
+
const automaticUsage = { next: true };
|
|
1165
|
+
const modelUsage = { next: true };
|
|
1166
|
+
const sessionUsage = { next: true };
|
|
1167
|
+
try {
|
|
1168
|
+
// All three sessions share one stable global settings root. Only their trusted
|
|
1169
|
+
// project settings differ, so this cannot pass by rotating PI_CODING_AGENT_DIR.
|
|
1170
|
+
automatic = await openFixture({
|
|
1171
|
+
contextWindow: 100_000,
|
|
1172
|
+
cwd: cwdAutomatic,
|
|
1173
|
+
agentDir,
|
|
1174
|
+
notesRoot,
|
|
1175
|
+
writeSettings: false,
|
|
1176
|
+
projectSettings: { compaction: { enabled: true, reserveTokens: 20_000 } },
|
|
1177
|
+
script: script(() => automatic, automaticUsage),
|
|
1178
|
+
});
|
|
1179
|
+
modelInvalidated = await openFixture({
|
|
1180
|
+
contextWindow: 100_000,
|
|
1181
|
+
cwd: cwdModel,
|
|
1182
|
+
agentDir,
|
|
1183
|
+
notesRoot,
|
|
1184
|
+
writeSettings: false,
|
|
1185
|
+
projectSettings: { compaction: { enabled: false, reserveTokens: 80_000 } },
|
|
1186
|
+
script: script(() => modelInvalidated, modelUsage),
|
|
1187
|
+
});
|
|
1188
|
+
sessionInvalidated = await openFixture({
|
|
1189
|
+
contextWindow: 100_000,
|
|
1190
|
+
cwd: cwdSession,
|
|
1191
|
+
agentDir,
|
|
1192
|
+
notesRoot,
|
|
1193
|
+
writeSettings: false,
|
|
1194
|
+
projectSettings: { compaction: { enabled: false, reserveTokens: 80_000 } },
|
|
1195
|
+
script: script(() => sessionInvalidated, sessionUsage),
|
|
1196
|
+
});
|
|
1197
|
+
await Promise.all([
|
|
1198
|
+
automatic.session.prompt("AUTOMATIC_POLICY_PROJECT"),
|
|
1199
|
+
modelInvalidated.session.prompt("MODEL_POLICY_PROJECT"),
|
|
1200
|
+
sessionInvalidated.session.prompt("SESSION_POLICY_PROJECT"),
|
|
1201
|
+
]);
|
|
1202
|
+
await Promise.all([automatic.session.waitForIdle(), modelInvalidated.session.waitForIdle(), sessionInvalidated.session.waitForIdle()]);
|
|
1203
|
+
assert.equal(resetMarkers(automatic).length, 1, "the low reserve and enabled project resets automatically");
|
|
1204
|
+
assert.equal(automatic.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CONTINUATION_TYPE).length, 1, "the automatic reset persists exactly one continuation");
|
|
1205
|
+
assert.equal(resetMarkers(modelInvalidated).length, 0, "the high reserve and disabled project does not reset");
|
|
1206
|
+
assert.equal(resetMarkers(sessionInvalidated).length, 0, "the second high reserve and disabled session does not reset");
|
|
1207
|
+
writeFileSync(join(cwdModel, ".pi", "settings.json"), JSON.stringify({ compaction: { enabled: true, reserveTokens: 20_000 } }));
|
|
1208
|
+
modelUsage.next = true;
|
|
1209
|
+
const changedModel = { ...modelInvalidated.model, id: `${modelInvalidated.model.id}-changed` };
|
|
1210
|
+
modelInvalidated.model = changedModel;
|
|
1211
|
+
await modelInvalidated.session.setModel(changedModel, { persist: false });
|
|
1212
|
+
await modelInvalidated.session.prompt("MODEL_POLICY_AFTER_INVALIDATION");
|
|
1213
|
+
await modelInvalidated.session.waitForIdle();
|
|
1214
|
+
assert.equal(resetMarkers(modelInvalidated).length, 1, "model_select invalidates the instance policy cache");
|
|
1215
|
+
writeFileSync(join(cwdSession, ".pi", "settings.json"), JSON.stringify({ compaction: { enabled: true, reserveTokens: 20_000 } }));
|
|
1216
|
+
sessionUsage.next = true;
|
|
1217
|
+
await sessionInvalidated.session.reload();
|
|
1218
|
+
await sessionInvalidated.session.prompt("SESSION_POLICY_AFTER_INVALIDATION");
|
|
1219
|
+
await sessionInvalidated.session.waitForIdle();
|
|
1220
|
+
assert.equal(resetMarkers(sessionInvalidated).length, 1, "session reload invalidates the instance policy cache");
|
|
1221
|
+
}
|
|
1222
|
+
finally {
|
|
1223
|
+
sessionInvalidated?.close();
|
|
1224
|
+
modelInvalidated?.close();
|
|
1225
|
+
automatic?.close();
|
|
1226
|
+
rmSync(agentDir, { recursive: true, force: true });
|
|
1227
|
+
rmSync(notesRoot, { recursive: true, force: true });
|
|
1228
|
+
rmSync(cwdAutomatic, { recursive: true, force: true });
|
|
1229
|
+
rmSync(cwdModel, { recursive: true, force: true });
|
|
1230
|
+
rmSync(cwdSession, { recursive: true, force: true });
|
|
1231
|
+
}
|
|
1232
|
+
});
|
|
1233
|
+
test("real AgentSession: injected settings managers own live policy and ignore conflicting default files", { timeout: 20000 }, async () => {
|
|
1234
|
+
const firstManager = SettingsManager.inMemory({ compaction: { enabled: true, reserveTokens: 80_000 } });
|
|
1235
|
+
const secondManager = SettingsManager.inMemory({ compaction: { enabled: false, reserveTokens: 20_000 } });
|
|
1236
|
+
const defaultAgentDir = mkdtempSync(join(tmpdir(), "notesoup-injected-default-agent-"));
|
|
1237
|
+
const notesRoot = mkdtempSync(join(tmpdir(), "notesoup-injected-notes-"));
|
|
1238
|
+
const previousAgentDir = process.env.PI_CODING_AGENT_DIR;
|
|
1239
|
+
const previousNotesRoot = process.env.PI_NOTES_HOME;
|
|
1240
|
+
writeFileSync(join(defaultAgentDir, "settings.json"), JSON.stringify({ compaction: { enabled: false, reserveTokens: 1_000 } }));
|
|
1241
|
+
process.env.PI_CODING_AGENT_DIR = defaultAgentDir;
|
|
1242
|
+
process.env.PI_NOTES_HOME = notesRoot;
|
|
1243
|
+
let first;
|
|
1244
|
+
let second;
|
|
1245
|
+
const firstHighUsage = { next: false };
|
|
1246
|
+
const secondHighUsage = { next: false };
|
|
1247
|
+
const script = (getFixture, highUsage) => (request) => {
|
|
1248
|
+
const fixture = getFixture();
|
|
1249
|
+
if (request === 1) {
|
|
1250
|
+
highUsage.next = false;
|
|
1251
|
+
return assistant(fixture, [{ type: "toolCall", id: "remaining", name: "get_context_remaining", arguments: {} }], "toolUse", { usage: usage(20_000) });
|
|
1252
|
+
}
|
|
1253
|
+
// Leave 20k free: above the low reserve plus the 16k warning runway.
|
|
1254
|
+
const input = highUsage.next ? 80_000 : 100;
|
|
1255
|
+
highUsage.next = false;
|
|
1256
|
+
return assistant(fixture, [{ type: "text", text: "scripted policy response" }], "stop", { usage: usage(input) });
|
|
1257
|
+
};
|
|
1258
|
+
try {
|
|
1259
|
+
first = await openFixture({
|
|
1260
|
+
contextWindow: 100_000,
|
|
1261
|
+
agentDir: defaultAgentDir,
|
|
1262
|
+
notesRoot,
|
|
1263
|
+
writeSettings: false,
|
|
1264
|
+
defaultCompactionEnabled: false,
|
|
1265
|
+
defaultReserveTokens: 1_000,
|
|
1266
|
+
settingsManager: firstManager,
|
|
1267
|
+
manageEnvironment: false,
|
|
1268
|
+
tools: ["get_context_remaining"],
|
|
1269
|
+
script: script(() => first, firstHighUsage),
|
|
1270
|
+
});
|
|
1271
|
+
second = await openFixture({
|
|
1272
|
+
contextWindow: 100_000,
|
|
1273
|
+
agentDir: defaultAgentDir,
|
|
1274
|
+
notesRoot,
|
|
1275
|
+
writeSettings: false,
|
|
1276
|
+
defaultCompactionEnabled: true,
|
|
1277
|
+
defaultReserveTokens: 95_000,
|
|
1278
|
+
settingsManager: secondManager,
|
|
1279
|
+
manageEnvironment: false,
|
|
1280
|
+
tools: ["get_context_remaining"],
|
|
1281
|
+
script: script(() => second, secondHighUsage),
|
|
1282
|
+
});
|
|
1283
|
+
await Promise.all([first.session.prompt("INJECTED_FIRST"), second.session.prompt("INJECTED_SECOND")]);
|
|
1284
|
+
await Promise.all([first.session.waitForIdle(), second.session.waitForIdle()]);
|
|
1285
|
+
assert.deepEqual(contextRemainingResults(first), [0], "the injected high reserve reaches the warning line in the real tool result");
|
|
1286
|
+
assert.ok((contextRemainingResults(second)[0] ?? 0) > 0, "the second injected reserve produces a distinct real tool result");
|
|
1287
|
+
assert.equal(resetMarkers(first).length, 1, "enabled injected policy resets at the first session's reserve");
|
|
1288
|
+
assert.equal(resetMarkers(second).length, 0, "disabled injected policy does not inherit the first session's reset decision");
|
|
1289
|
+
firstHighUsage.next = true;
|
|
1290
|
+
firstManager.setCompactionEnabled(false);
|
|
1291
|
+
firstManager.applyOverrides({ compaction: { reserveTokens: 90_000 } });
|
|
1292
|
+
await first.session.prompt("INJECTED_LIVE_DISABLE");
|
|
1293
|
+
await first.session.waitForIdle();
|
|
1294
|
+
assert.equal(resetMarkers(first).length, 1, "a public setter disables the next turn without reload");
|
|
1295
|
+
assert.equal(resetMarkers(second).length, 0, "the second live manager remains unchanged");
|
|
1296
|
+
firstHighUsage.next = true;
|
|
1297
|
+
firstManager.setCompactionEnabled(true);
|
|
1298
|
+
firstManager.applyOverrides({ compaction: { reserveTokens: 1_000 } });
|
|
1299
|
+
await first.session.prompt("INJECTED_LIVE_ENABLE_LOW_RESERVE");
|
|
1300
|
+
await first.session.waitForIdle();
|
|
1301
|
+
assert.equal(resetMarkers(first).length, 1, "live enablement and a lower reserve apply on the next turn");
|
|
1302
|
+
firstHighUsage.next = true;
|
|
1303
|
+
firstManager.applyOverrides({ compaction: { reserveTokens: 80_000 } });
|
|
1304
|
+
await first.session.prompt("INJECTED_LIVE_HIGH_RESERVE");
|
|
1305
|
+
await first.session.waitForIdle();
|
|
1306
|
+
assert.equal(resetMarkers(first).length, 2, "a live reserve increase drives the next reset decision");
|
|
1307
|
+
}
|
|
1308
|
+
finally {
|
|
1309
|
+
second?.close();
|
|
1310
|
+
first?.close();
|
|
1311
|
+
if (previousAgentDir === undefined)
|
|
1312
|
+
delete process.env.PI_CODING_AGENT_DIR;
|
|
1313
|
+
else
|
|
1314
|
+
process.env.PI_CODING_AGENT_DIR = previousAgentDir;
|
|
1315
|
+
if (previousNotesRoot === undefined)
|
|
1316
|
+
delete process.env.PI_NOTES_HOME;
|
|
1317
|
+
else
|
|
1318
|
+
process.env.PI_NOTES_HOME = previousNotesRoot;
|
|
1319
|
+
rmSync(defaultAgentDir, { recursive: true, force: true });
|
|
1320
|
+
rmSync(notesRoot, { recursive: true, force: true });
|
|
1321
|
+
}
|
|
1322
|
+
});
|
|
1323
|
+
test("real AgentSession: injected model overrides select the active model's reserve", { timeout: 20000 }, async () => {
|
|
1324
|
+
let settingsManager;
|
|
1325
|
+
let modelBId = "";
|
|
1326
|
+
const notesRoot = mkdtempSync(join(tmpdir(), "notesoup-model-override-notes-"));
|
|
1327
|
+
const previousNotesRoot = process.env.PI_NOTES_HOME;
|
|
1328
|
+
process.env.PI_NOTES_HOME = notesRoot;
|
|
1329
|
+
let fixture;
|
|
1330
|
+
fixture = await openFixture({
|
|
1331
|
+
contextWindow: 100_000,
|
|
1332
|
+
notesRoot,
|
|
1333
|
+
settingsManager: (model) => {
|
|
1334
|
+
modelBId = `${model.id}-changed`;
|
|
1335
|
+
settingsManager = SettingsManager.inMemory({
|
|
1336
|
+
compaction: {
|
|
1337
|
+
enabled: false,
|
|
1338
|
+
reserveTokens: 10_000,
|
|
1339
|
+
modelOverrides: {
|
|
1340
|
+
[`${model.provider}/${model.id}`]: { reserveTokens: 70_000 },
|
|
1341
|
+
[`${model.provider}/${modelBId}`]: { reserveTokens: 1_000 },
|
|
1342
|
+
},
|
|
1343
|
+
},
|
|
1344
|
+
});
|
|
1345
|
+
return settingsManager;
|
|
1346
|
+
},
|
|
1347
|
+
manageEnvironment: false,
|
|
1348
|
+
tools: ["get_context_remaining"],
|
|
1349
|
+
script: (request) => request === 1 || request === 3
|
|
1350
|
+
? assistant(fixture, [{ type: "toolCall", id: `remaining-${request}`, name: "get_context_remaining", arguments: {} }], "toolUse", { usage: usage(30_000) })
|
|
1351
|
+
: assistant(fixture, [{ type: "text", text: "scripted model override response" }], "stop", { usage: usage(1_000) }),
|
|
1352
|
+
});
|
|
1353
|
+
try {
|
|
1354
|
+
await fixture.session.prompt("MODEL_OVERRIDE_A");
|
|
1355
|
+
await fixture.session.waitForIdle();
|
|
1356
|
+
assert.deepEqual(contextRemainingResults(fixture), [0], "model-a's high reserve reaches zero in the real tool result");
|
|
1357
|
+
const changedModel = { ...fixture.model, id: modelBId };
|
|
1358
|
+
fixture.model = changedModel;
|
|
1359
|
+
await fixture.session.setModel(changedModel, { persist: false });
|
|
1360
|
+
await fixture.session.prompt("MODEL_OVERRIDE_B");
|
|
1361
|
+
await fixture.session.waitForIdle();
|
|
1362
|
+
const results = contextRemainingResults(fixture);
|
|
1363
|
+
assert.equal(results.length, 2);
|
|
1364
|
+
assert.ok((results[1] ?? 0) > 0, "model-b's lower reserve is selected for the next real tool result");
|
|
1365
|
+
}
|
|
1366
|
+
finally {
|
|
1367
|
+
fixture.close();
|
|
1368
|
+
if (previousNotesRoot === undefined)
|
|
1369
|
+
delete process.env.PI_NOTES_HOME;
|
|
1370
|
+
else
|
|
1371
|
+
process.env.PI_NOTES_HOME = previousNotesRoot;
|
|
1372
|
+
rmSync(notesRoot, { recursive: true, force: true });
|
|
1373
|
+
}
|
|
1374
|
+
});
|
|
1375
|
+
test("real AgentSession: persisted budget warning re-arms after a later abort/error", { timeout: 30000 }, async () => {
|
|
1376
|
+
for (const mode of ["ctx-abort", "generic-error"]) {
|
|
1377
|
+
let fixture;
|
|
1378
|
+
let warningTurnStarted;
|
|
1379
|
+
let releaseWarningTurn;
|
|
1380
|
+
let didAbort = false;
|
|
1381
|
+
const warningStarted = new Promise((resolve) => { warningTurnStarted = resolve; });
|
|
1382
|
+
const warningGate = new Promise((resolve) => { releaseWarningTurn = resolve; });
|
|
1383
|
+
fixture = await openFixture({
|
|
1384
|
+
compactionEnabled: true,
|
|
1385
|
+
hook: mode === "ctx-abort" ? (pi, _getSession, requests) => pi.on("context", (_event, ctx) => {
|
|
1386
|
+
if (!didAbort && requests.length === 3) {
|
|
1387
|
+
didAbort = true;
|
|
1388
|
+
ctx.abort();
|
|
1389
|
+
}
|
|
1390
|
+
}) : undefined,
|
|
1391
|
+
script: async (request, context) => {
|
|
1392
|
+
if (request === 1)
|
|
1393
|
+
return assistant(fixture, [{ type: "toolCall", id: "rearm-probe-1", name: "get_context_remaining", arguments: {} }], "toolUse", { usage: usage(50_000) });
|
|
1394
|
+
if (request === 2)
|
|
1395
|
+
return assistant(fixture, [{ type: "toolCall", id: "rearm-probe-2", name: "get_context_remaining", arguments: {} }], "toolUse", { usage: usage(60_000) });
|
|
1396
|
+
if (request === 3) {
|
|
1397
|
+
assert.ok(text(context).includes(WARNING_PROMPT), "the low-budget request carries the close-out warning");
|
|
1398
|
+
warningTurnStarted();
|
|
1399
|
+
await warningGate;
|
|
1400
|
+
return assistant(fixture, [{ type: "toolCall", id: "rearm-note", name: "notes_write", arguments: { address: "warning-rearm.md", content: "DURABLE_WARNING_CHECKPOINT" } }], "toolUse", { usage: usage(60_000) });
|
|
1401
|
+
}
|
|
1402
|
+
if (request === 4 && mode === "generic-error") {
|
|
1403
|
+
assert.equal(text(context).split(WARNING_PROMPT).length - 1, 1, "the durable warning is not injected a second time");
|
|
1404
|
+
assert.ok(text(context).includes("REARM_QUEUED_FOLLOWUP"));
|
|
1405
|
+
return assistant(fixture, [{ type: "text", text: "ordinary provider failure" }], "error", { errorMessage: "synthetic non-overflow failure", usage: usage(60_000) });
|
|
1406
|
+
}
|
|
1407
|
+
return assistant(fixture, [{ type: "text", text: `normal response ${request}` }], "stop", { usage: usage(60_000) });
|
|
1408
|
+
},
|
|
1409
|
+
});
|
|
1410
|
+
try {
|
|
1411
|
+
const initialTurn = fixture.session.prompt(`REARM_${mode}_INITIAL`);
|
|
1412
|
+
await warningStarted;
|
|
1413
|
+
fixture.session.steer("REARM_QUEUED_FOLLOWUP");
|
|
1414
|
+
releaseWarningTurn();
|
|
1415
|
+
await initialTurn;
|
|
1416
|
+
await fixture.session.waitForIdle();
|
|
1417
|
+
const afterFailure = fixture.sessionManager.getBranch();
|
|
1418
|
+
assert.equal(afterFailure.filter((entry) => entry.type === "custom_message" && entry.customType === WARNING_TYPE).length, 1, "the warning was persisted exactly once before the failed follow-up");
|
|
1419
|
+
assert.ok(existsSync(join(fixture.notesRoot, "pi", "session", fixture.sessionManager.getSessionId(), "warning-rearm.md")), "the preceding note/tool turn completed");
|
|
1420
|
+
assert.equal(resetMarkers(fixture).length, 0, `${mode} itself must not reset`);
|
|
1421
|
+
assert.equal(afterFailure.filter((entry) => entry.type === "compaction").length, 0);
|
|
1422
|
+
const failedContext = fixture.streamContexts[3];
|
|
1423
|
+
assert.ok(failedContext);
|
|
1424
|
+
assert.equal(text(failedContext).split(WARNING_PROMPT).length - 1, 1, "the persisted warning appears once, without duplicate injection");
|
|
1425
|
+
assert.equal(text(failedContext).split("REARM_QUEUED_FOLLOWUP").length - 1, 1, "queued follow-up reaches the failed request once");
|
|
1426
|
+
assert.equal(fixture.streamSignals.at(-1), mode === "ctx-abort", "the abort case cancels Pi's real signal; the error case does not");
|
|
1427
|
+
await fixture.session.prompt("REARM_AFTER_FAILED_TURN");
|
|
1428
|
+
await fixture.session.waitForIdle();
|
|
1429
|
+
assert.equal(resetMarkers(fixture).length, 0, "a later normal stop still does not authorize a budget reset");
|
|
1430
|
+
assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === WARNING_TYPE).length, 1, "re-arming does not duplicate the durable warning");
|
|
1431
|
+
assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "compaction").length, 0);
|
|
1432
|
+
assert.ok(text(fixture.requests.at(-1)).includes(`REARM_${mode}_INITIAL`), "the original task survives settlement");
|
|
1433
|
+
}
|
|
1434
|
+
finally {
|
|
1435
|
+
releaseWarningTurn();
|
|
1436
|
+
fixture.close();
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
});
|
|
1440
|
+
test("real AgentSession: warning precedes a durable checkpoint, including failed writes and an ignored warning", { timeout: 20000 }, async () => {
|
|
1441
|
+
for (const scenario of ["checkpoint", "write-error", "ignored-warning"]) {
|
|
1442
|
+
let fixture;
|
|
1443
|
+
fixture = await openFixture({
|
|
1444
|
+
compactionEnabled: true,
|
|
1445
|
+
script: (request, context) => {
|
|
1446
|
+
if (request === 3) {
|
|
1447
|
+
assert.ok(text(context).includes(GUIDANCE_OPEN_TAG), "the warning remains in its hidden guidance wrapper");
|
|
1448
|
+
assert.ok(text(context).includes(WARNING_PROMPT), "the shared close-out warning reaches the provider before checkpoint choice");
|
|
1449
|
+
}
|
|
1450
|
+
if (request === 1)
|
|
1451
|
+
return assistant(fixture, [{ type: "toolCall", id: "budget-probe-1", name: "get_context_remaining", arguments: {} }], "toolUse", { usage: usage(50_000) });
|
|
1452
|
+
if (request === 2)
|
|
1453
|
+
return assistant(fixture, [{ type: "toolCall", id: "budget-probe-2", name: "get_context_remaining", arguments: {} }], "toolUse", { usage: usage(60_000) });
|
|
1454
|
+
if (request === 3 && scenario !== "ignored-warning")
|
|
1455
|
+
return assistant(fixture, [{ type: "toolCall", id: "checkpoint", name: "notes_write", arguments: {
|
|
1456
|
+
address: scenario === "write-error" ? "../invalid.md" : "checkpoint.md",
|
|
1457
|
+
content: "CHECKPOINT_SENTINEL",
|
|
1458
|
+
} }], "toolUse", { usage: usage(60_000) });
|
|
1459
|
+
if (request === 4 && scenario !== "ignored-warning")
|
|
1460
|
+
return assistant(fixture, [{ type: "toolCall", id: "wipe-after-checkpoint", name: "clear_memory", arguments: {} }], "toolUse", { usage: usage(60_000) });
|
|
1461
|
+
return assistant(fixture, [{ type: "text", text: scenario === "ignored-warning" ? "warning intentionally ignored" : "checkpoint and wipe complete" }], "stop", { usage: usage(60_000) });
|
|
1462
|
+
},
|
|
1463
|
+
});
|
|
1464
|
+
try {
|
|
1465
|
+
await fixture.session.prompt(`WARNING_${scenario.toUpperCase()}_SENTINEL`);
|
|
1466
|
+
await fixture.session.waitForIdle();
|
|
1467
|
+
const branch = fixture.sessionManager.getBranch();
|
|
1468
|
+
assert.equal(branch.filter((entry) => entry.type === "custom_message" && entry.customType === GUIDANCE_TYPE).length, 1, "one early reminder is durable");
|
|
1469
|
+
assert.equal(branch.filter((entry) => entry.type === "custom_message" && entry.customType === WARNING_TYPE).length, 1, "one critical warning is durable");
|
|
1470
|
+
const noteFile = join(fixture.notesRoot, "pi", "session", fixture.sessionManager.getSessionId(), "checkpoint.md");
|
|
1471
|
+
if (scenario === "checkpoint") {
|
|
1472
|
+
assert.equal(resetMarkers(fixture).length, 1);
|
|
1473
|
+
assert.equal(existsSync(noteFile), true, "a successful checkpoint reaches the notes store before reset");
|
|
1474
|
+
assert.ok(text(fixture.requests.at(-1)).includes("checkpoint.md"), "the fresh boot indexes the successful checkpoint");
|
|
1475
|
+
}
|
|
1476
|
+
else if (scenario === "write-error") {
|
|
1477
|
+
assert.equal(resetMarkers(fixture).length, 1);
|
|
1478
|
+
assert.equal(existsSync(noteFile), false, "a failed checkpoint does not create a note");
|
|
1479
|
+
assert.ok(branch.some((entry) => entry.type === "message" && entry.message.role === "toolResult" && entry.message.toolName === "notes_write" && entry.message.isError && entry.message.content.some((part) => part.type === "text" && part.text.startsWith("error: invalid_address: "))), "the failed write persists its coded refusal as an error result");
|
|
1480
|
+
}
|
|
1481
|
+
else {
|
|
1482
|
+
assert.equal(resetMarkers(fixture).length, 0, "an ignored warning must not erase the task at normal stop");
|
|
1483
|
+
assert.equal(fixture.requests.length, 3, "settlement must not manufacture a fresh-window request");
|
|
1484
|
+
assert.equal(branch.filter((entry) => entry.type === "compaction").length, 0);
|
|
1485
|
+
assert.equal(existsSync(noteFile), false);
|
|
1486
|
+
await fixture.session.prompt("Continue the same task.");
|
|
1487
|
+
await fixture.session.waitForIdle();
|
|
1488
|
+
assert.equal(resetMarkers(fixture).length, 0);
|
|
1489
|
+
assert.ok(text(fixture.requests.at(-1)).includes(`WARNING_${scenario.toUpperCase()}_SENTINEL`));
|
|
1490
|
+
assert.equal(text(fixture.requests.at(-1)).split(WARNING_PROMPT).length - 1, 1, "the persisted warning remains visible without duplicate injection");
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
finally {
|
|
1494
|
+
fixture.close();
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
});
|