notesoup 0.58.3 → 0.59.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/plugins/claude/src/helper.js +13 -0
- package/dist/plugins/claude/src/thresholds.js +17 -12
- package/dist/plugins/dsh/tools.js +0 -3
- package/dist/plugins/pi/budget.d.ts +3 -0
- package/dist/plugins/pi/budget.js +22 -11
- package/dist/plugins/pi/runtime.js +22 -6
- package/dist/src/boot/text.d.ts +1 -1
- package/dist/src/boot/text.js +6 -10
- package/dist/src/budget/cap.d.ts +2 -0
- package/dist/src/budget/cap.js +11 -0
- package/dist/src/notes/address.d.ts +1 -1
- package/dist/src/notes/address.js +1 -1
- package/dist/src/notes/policy.js +1 -1
- package/dist/src/tools/dream.d.ts +3 -3
- package/dist/src/tools/dream.js +5 -5
- package/dist/src/tools/history.js +12 -13
- package/dist/src/tools/notes.d.ts +7 -5
- package/dist/src/tools/notes.js +35 -34
- package/dist/src/tools/result.js +2 -2
- package/dist/src/tools/schema.js +2 -2
- package/dist/test/budget-settings.integration.test.js +45 -1
- package/dist/test/claude-mod.test.js +80 -21
- package/dist/test/dsh.test.js +13 -1
- package/dist/test/note-policy.test.js +6 -1
- package/dist/test/notes.integration.test.js +28 -0
- package/docs/claude-code-mod.md +5 -3
- package/docs/reset-lifecycle.md +3 -1
- package/package.json +1 -1
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +96 -70
- package/plugins/claude/hooks/register.ts +57 -9
- package/plugins/claude/src/helper.ts +11 -0
- package/plugins/claude/src/thresholds.ts +18 -11
- package/plugins/codex/dist/codex/notesoup.js +59 -61
- package/plugins/dsh/tools.ts +0 -2
- package/plugins/pi/budget.ts +21 -11
- package/plugins/pi/runtime.ts +18 -6
- package/src/boot/text.ts +6 -10
- package/src/budget/cap.ts +9 -0
- package/src/notes/address.ts +1 -1
- package/src/notes/policy.ts +1 -1
- package/src/tools/dream.ts +5 -5
- package/src/tools/history.ts +12 -14
- package/src/tools/notes.ts +35 -33
- package/src/tools/result.ts +2 -2
- package/src/tools/schema.ts +2 -2
package/dist/src/tools/notes.js
CHANGED
|
@@ -13,12 +13,12 @@ import { nullableString, searchQuery } from "./schema.js";
|
|
|
13
13
|
import { notesIdentityForCall } from "./notes-context.js";
|
|
14
14
|
const ORIGIN_VALUES = [Type.Literal("user"), Type.Literal("self"), Type.Literal("external")];
|
|
15
15
|
const ORIGIN = Type.Optional(Type.Union([...ORIGIN_VALUES], {
|
|
16
|
-
description: "
|
|
16
|
+
description: "Whose handwriting: user, self, or external. Leave it out to keep what's there.",
|
|
17
17
|
}));
|
|
18
18
|
const POLICY_PARAMETERS = {
|
|
19
|
-
pinned: Type.Optional(Type.Boolean({ description: "
|
|
20
|
-
budget: Type.Optional(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "
|
|
21
|
-
readonly: Type.Optional(Type.Boolean({ description: "
|
|
19
|
+
pinned: Type.Optional(Type.Boolean({ description: "Tape the page inside the cover: read whole at every wake-up. Five per notebook, CHEATSHEET and MAP included." })),
|
|
20
|
+
budget: Type.Optional(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "How much paper the page gets. Writing past it still saves, with a warning. A page over budget gets boiled down: stale lines out, repeats merged, the rest said shorter. More paper is for a page already boiled down that still needs the room." })),
|
|
21
|
+
readonly: Type.Optional(Type.Boolean({ description: "A paperclip that keeps your own hands off. `false` takes it off — same call is fine." })),
|
|
22
22
|
};
|
|
23
23
|
const PolicySchema = {
|
|
24
24
|
pinned: Type.Boolean(), budget: Type.Integer(), readonly: Type.Boolean(),
|
|
@@ -33,13 +33,12 @@ function renderPolicy(policy) {
|
|
|
33
33
|
function withWarnings(text, data) {
|
|
34
34
|
return [text, ...data.warnings].join("\n");
|
|
35
35
|
}
|
|
36
|
-
const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "
|
|
37
|
-
const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "
|
|
38
|
-
const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "
|
|
39
|
-
const GLOB_PARAMETER = nullableString("
|
|
40
|
-
const CWD_PARAMETER = Type.Optional(Type.String({ minLength: 1, description: "
|
|
41
|
-
const
|
|
42
|
-
const ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable notebooks; `@projects/<name>/<path>` and `@sessions/<id>/<path>` read named project and session notes (read-only). Not file paths: never pass them to file tools.";
|
|
36
|
+
const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "`true` balls the page up: gone from list and search, still readable. `false` smooths it flat again." }));
|
|
37
|
+
const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "Only the crumpled balls." }));
|
|
38
|
+
const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "How many pages at most." }));
|
|
39
|
+
const GLOB_PARAMETER = nullableString("Which drawers to open. Leave it out for this session and your current notebooks. `@project/**` one shelf · `MAP.md` that page in every notebook · `**` everything · `@sessions/*/**` every session.");
|
|
40
|
+
const CWD_PARAMETER = Type.Optional(Type.String({ minLength: 1, description: "Treat this directory's project as `@project/`." }));
|
|
41
|
+
const ADDRESS_PARAMETER = Type.String({ description: "Which drawer the page sits in. `plan.md` — this session's desk, cleared when it ends. `@project/` this project's shelf · `@human/` your human's file · `@self/` your own notebook · `@model/` your brain's. `@projects/<name>/`, `@sessions/<id>/`, `@agents/<name>/`, `@models/<name>/` — someone else's shelf: read only. Paper, not files: hand one to read/write/edit/bash and a real `@project` folder is born." });
|
|
43
42
|
/**
|
|
44
43
|
* Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
|
|
45
44
|
* Convert expected refusals; unexpected errors propagate unchanged.
|
|
@@ -151,7 +150,7 @@ const MatchSchema = Type.Object({
|
|
|
151
150
|
}, { additionalProperties: false });
|
|
152
151
|
const SearchedFileSchema = Type.Object({
|
|
153
152
|
...ListedFileSchema.properties,
|
|
154
|
-
matches: Type.Array(MatchSchema),
|
|
153
|
+
matches: Type.Array(MatchSchema), more_matches: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
155
154
|
}, { additionalProperties: false });
|
|
156
155
|
export const SnapshotSchema = {
|
|
157
156
|
more: Type.Integer({ description: "How many more were left out." }),
|
|
@@ -211,13 +210,13 @@ export function listedFile(row, identity) {
|
|
|
211
210
|
const policy = policyAt(row.meta, row.address);
|
|
212
211
|
return { ...noteIdentity(identity, row.address), ...policy, warnings: row.warnings ?? (row.body === undefined ? [] : noteBudgetWarnings(row.body, policy)), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
|
|
213
212
|
}
|
|
214
|
-
export const notesWriteParameters = Type.Object({ address:
|
|
213
|
+
export const notesWriteParameters = Type.Object({ address: ADDRESS_PARAMETER, content: Type.String({ description: "The whole page." }), origin: ORIGIN, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
|
|
215
214
|
function renderWriteData(data) {
|
|
216
215
|
return withWarnings(`${data.outcome} ${renderIdentity(data)} | ${renderPolicy(data)}`, data);
|
|
217
216
|
}
|
|
218
217
|
export const notesWrite = {
|
|
219
218
|
name: "notes_write", label: "Notes write",
|
|
220
|
-
description:
|
|
219
|
+
description: "Take a fresh page and write it — or rip out the old one and write it again. Title it for what's inside and when you'll reach for it.",
|
|
221
220
|
parameters: notesWriteParameters, outputSchema: resultSchema(NotesWriteDataSchema), executionMode: "sequential",
|
|
222
221
|
async execute(params, context) {
|
|
223
222
|
try {
|
|
@@ -232,13 +231,13 @@ export const notesWrite = {
|
|
|
232
231
|
render: (result) => renderOutcome(result, renderWriteData),
|
|
233
232
|
};
|
|
234
233
|
export const notesUpdateParameters = Type.Object({
|
|
235
|
-
address:
|
|
236
|
-
edits: Type.Optional(Type.Array(Type.Object({ oldText: Type.String(), newText: Type.String() }, { additionalProperties: false }))),
|
|
234
|
+
address: ADDRESS_PARAMETER,
|
|
235
|
+
edits: Type.Optional(Type.Array(Type.Object({ oldText: Type.String({ description: "The passage as it stands on the page." }), newText: Type.String({ description: "What goes in its place." }) }, { additionalProperties: false }), { description: "Pen strokes, in order. Each `oldText` is the exact passage — same case, found once — and `newText` is what goes in its place." })),
|
|
237
236
|
origin: ORIGIN,
|
|
238
237
|
...POLICY_PARAMETERS,
|
|
239
238
|
crumpled: CRUMPLED_PARAMETER,
|
|
240
|
-
replace_all: Type.Optional(Type.Boolean({ description: "
|
|
241
|
-
rename_to: Type.Optional(Type.String({ description: "
|
|
239
|
+
replace_all: Type.Optional(Type.Boolean({ description: "Strike every copy of `oldText`, not just one." })),
|
|
240
|
+
rename_to: Type.Optional(Type.String({ description: "Move the page to another address. Never lands on top of a live page; nothing pointing at it follows." })),
|
|
242
241
|
cwd: CWD_PARAMETER,
|
|
243
242
|
}, { additionalProperties: false });
|
|
244
243
|
function renderUpdateData(data) {
|
|
@@ -249,7 +248,7 @@ function renderUpdateData(data) {
|
|
|
249
248
|
}
|
|
250
249
|
export const notesUpdate = {
|
|
251
250
|
name: "notes_update", label: "Notes update",
|
|
252
|
-
description:
|
|
251
|
+
description: "Work on a page you already have: cross out and rewrite lines, move it, pin it, lock it, give it more paper, crumple it. Keep every page true to now: wrong, stale, or no-longer-mattering lines get rewritten or struck where they stand. The page stays one page.",
|
|
253
252
|
parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
|
|
254
253
|
async execute(params, context, onChange) {
|
|
255
254
|
try {
|
|
@@ -269,13 +268,13 @@ export const notesUpdate = {
|
|
|
269
268
|
},
|
|
270
269
|
render: (result) => renderOutcome(result, renderUpdateData),
|
|
271
270
|
};
|
|
272
|
-
export const notesReadParameters = Type.Object({ address:
|
|
271
|
+
export const notesReadParameters = Type.Object({ address: ADDRESS_PARAMETER, ...TextWindowRequestSchema, cwd: CWD_PARAMETER }, { additionalProperties: false });
|
|
273
272
|
function renderReadData(data) {
|
|
274
273
|
return withWarnings(`${renderIdentity(data)}\n${renderMetadata(data.metadata)}`, data) + `\n\n${renderTextWindow(data)}`;
|
|
275
274
|
}
|
|
276
275
|
export const notesRead = {
|
|
277
276
|
name: "notes_read", label: "Notes read",
|
|
278
|
-
description:
|
|
277
|
+
description: "Read a page. Long ones come a stretch at a time; follow `next_offset_chars`.",
|
|
279
278
|
parameters: notesReadParameters, outputSchema: resultSchema(NotesReadDataSchema),
|
|
280
279
|
async execute(params, context) {
|
|
281
280
|
try {
|
|
@@ -312,7 +311,7 @@ export function renderListData(data) {
|
|
|
312
311
|
}
|
|
313
312
|
export const notesList = {
|
|
314
313
|
name: "notes_list", label: "Notes list",
|
|
315
|
-
description:
|
|
314
|
+
description: "Leaf through the drawers, newest pages on top. One pass; `more` counts pages left on the pile — narrow `glob`.",
|
|
316
315
|
parameters: notesListParameters, outputSchema: resultSchema(NotesListDataSchema),
|
|
317
316
|
async execute(params, context) {
|
|
318
317
|
try {
|
|
@@ -326,11 +325,11 @@ export const notesList = {
|
|
|
326
325
|
},
|
|
327
326
|
render: (result) => renderOutcome(result, renderListData),
|
|
328
327
|
};
|
|
329
|
-
export const notesSearchParameters = Type.Object({ query: Type.Optional(searchQuery()), glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, max_matches_per_file: Type.Optional(Type.Integer({ minimum: 1, description: "
|
|
328
|
+
export const notesSearchParameters = Type.Object({ query: Type.Optional(searchQuery()), glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, max_matches_per_file: Type.Optional(Type.Integer({ minimum: 1, description: "How many hit lines per page at most." })), crumpled: CRUMPLED_LIST_PARAMETER, cwd: CWD_PARAMETER }, { additionalProperties: false });
|
|
330
329
|
function renderSearchData(data) {
|
|
331
330
|
const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
|
|
332
331
|
for (const file of data.files) {
|
|
333
|
-
lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
|
|
332
|
+
lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}${file.more_matches ? `, ${file.more_matches} more lines` : ""}`);
|
|
334
333
|
lines.push(...file.warnings.map(warning => ` ${warning}`));
|
|
335
334
|
for (const match of file.matches)
|
|
336
335
|
lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
|
|
@@ -341,6 +340,10 @@ function renderSearchData(data) {
|
|
|
341
340
|
lines.push(`${namespace} could not be read`);
|
|
342
341
|
return lines.join("\n");
|
|
343
342
|
}
|
|
343
|
+
function keepMatches(file, count = file.matches.length) {
|
|
344
|
+
const more = (file.more_matches ?? 0) + Math.max(0, file.matches.length - count);
|
|
345
|
+
return { ...file, matches: file.matches.slice(0, count), ...(more ? { more_matches: more } : {}) };
|
|
346
|
+
}
|
|
344
347
|
/** A shortened match line still ends with a marker, so its own text says it was cut. */
|
|
345
348
|
export const MATCH_SHORTENED_MARKER = " [truncated]";
|
|
346
349
|
/** Prefer whole match lines; shorten the first line only if no whole line fits, and mark it. */
|
|
@@ -349,31 +352,29 @@ function fitSearchFile(file, fits) {
|
|
|
349
352
|
let high = file.matches.length;
|
|
350
353
|
while (low < high) {
|
|
351
354
|
const mid = Math.ceil((low + high) / 2);
|
|
352
|
-
if (fits(
|
|
355
|
+
if (fits(keepMatches(file, mid)))
|
|
353
356
|
low = mid;
|
|
354
357
|
else
|
|
355
358
|
high = mid - 1;
|
|
356
359
|
}
|
|
357
|
-
if (low > 0)
|
|
358
|
-
return
|
|
360
|
+
if (low > 0 || file.matches.length === 0)
|
|
361
|
+
return keepMatches(file, low);
|
|
359
362
|
const first = file.matches[0];
|
|
360
|
-
|
|
361
|
-
return file;
|
|
362
|
-
const withText = (text) => ({ ...file, matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
|
|
363
|
+
const withText = (text) => ({ ...keepMatches(file, 1), matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
|
|
363
364
|
return withText(prefixFit(first.text, text => fits(withText(text))));
|
|
364
365
|
}
|
|
365
366
|
export const notesSearch = {
|
|
366
367
|
name: "notes_search", label: "Notes search",
|
|
367
|
-
description:
|
|
368
|
+
description: "Run a finger down every page for some text, case doesn't matter. Returns the lines it hits and where they sit; no query just lists the pages. One pass; `more` counts pages left on the pile — narrow `glob`.",
|
|
368
369
|
parameters: notesSearchParameters, outputSchema: resultSchema(NotesSearchDataSchema),
|
|
369
370
|
async execute(params, context) {
|
|
370
371
|
try {
|
|
371
372
|
const identity = notesIdentityForCall(context, params.cwd);
|
|
372
373
|
const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? undefined, crumpled: params.crumpled });
|
|
373
|
-
const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map(row => ({
|
|
374
|
+
const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map(row => keepMatches({
|
|
374
375
|
...listedFile(row, identity),
|
|
375
|
-
matches: row.matches.
|
|
376
|
-
}));
|
|
376
|
+
matches: row.matches.map(match => ({ line: match.line, text: match.text, offset_chars: match.offsetChars })),
|
|
377
|
+
}, params.max_matches_per_file));
|
|
377
378
|
return snapshot(files, params.limit, status, renderSearchData, fitSearchFile);
|
|
378
379
|
}
|
|
379
380
|
catch (error) {
|
package/dist/src/tools/result.js
CHANGED
|
@@ -40,8 +40,8 @@ export const TextWindowSchema = Type.Object({
|
|
|
40
40
|
* because `readTextWindow` already owns the defaults.
|
|
41
41
|
*/
|
|
42
42
|
export const TextWindowRequestSchema = {
|
|
43
|
-
offset_chars: Type.Optional(Type.Integer({ description: "
|
|
44
|
-
max_chars: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description:
|
|
43
|
+
offset_chars: Type.Optional(Type.Integer({ description: "Where on the page to start reading; negative counts from the end." })),
|
|
44
|
+
max_chars: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much to read at once." })),
|
|
45
45
|
};
|
|
46
46
|
/**
|
|
47
47
|
* Read one code-point window of `text` and build the operation's data around it. `offset` and
|
package/dist/src/tools/schema.js
CHANGED
|
@@ -2,7 +2,7 @@ import { Type } from "typebox";
|
|
|
2
2
|
import { Errors } from "typebox/value";
|
|
3
3
|
import { HistoryRoleSchema } from "../history/history.js";
|
|
4
4
|
export const nullableString = (description) => Type.Optional(Type.Union([Type.String(), Type.Null()], description === undefined ? {} : { description }));
|
|
5
|
-
export const historyRoles = () => Type.Optional(Type.Array(HistoryRoleSchema, { minItems: 1, description: "
|
|
5
|
+
export const historyRoles = () => Type.Optional(Type.Array(HistoryRoleSchema, { minItems: 1, description: "Only these voices: user, assistant, tool, context. Without roles or query, tool and context runs fold into one line." }));
|
|
6
6
|
/** First parameter violation; skip false subschemas so additionalProperties can name the field. */
|
|
7
7
|
export function paramProblem(schema, params) {
|
|
8
8
|
const first = Errors(schema, params).find((error) => error.keyword !== "boolean");
|
|
@@ -13,4 +13,4 @@ export function paramProblem(schema, params) {
|
|
|
13
13
|
return `${field ? `${field} ` : ""}${first.message}${extra}`;
|
|
14
14
|
}
|
|
15
15
|
/** Search query parameter: one literal, or several literals combined with OR. */
|
|
16
|
-
export const searchQuery = (description = "
|
|
16
|
+
export const searchQuery = (description = "Text to look for, or a list (any match). Leave it out to just list the pages.") => Type.Union([Type.String(), Type.Array(Type.String())], { description });
|
|
@@ -7,9 +7,10 @@ import { DEFAULT_REMINDER_MARGIN_TOKENS, DEFAULT_RESERVE_TOKENS } from "../src/b
|
|
|
7
7
|
import { tokenBudgetGuidance } from "../src/budget/text.js";
|
|
8
8
|
import { GUIDANCE_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../plugins/pi/entries.js";
|
|
9
9
|
import { deriveThresholds } from "../src/budget/policy.js";
|
|
10
|
+
import { parseContextCap } from "../src/budget/cap.js";
|
|
10
11
|
import { readThresholdSettings } from "../plugins/pi/thresholds.js";
|
|
11
12
|
import { NOTESOUP_SETTINGS_KEY } from "../src/settings.js";
|
|
12
|
-
import { appendText, call, commitTurnEndBoundary, context, makeExtension, manager, noticesOf, resultJson, runContextHook, runHandlers, sentOf, settingsFixture, writeJson, } from "./helpers/extension.js";
|
|
13
|
+
import { appendText, call, commitTurnEndBoundary, context, makeExtension, manager, noticesOf, resultJson, runContextHook, runHandlers, runCommand, sentOf, settingsFixture, writeJson, } from "./helpers/extension.js";
|
|
13
14
|
import { installExtensionTestHooks } from "./helpers/extension-test-environment.js";
|
|
14
15
|
const testEnvironment = installExtensionTestHooks("notesoup-integration");
|
|
15
16
|
const explicitBudgetSettings = {
|
|
@@ -31,6 +32,49 @@ test("budget derivation preserves defaults and validates overrides independently
|
|
|
31
32
|
}
|
|
32
33
|
assert.deepEqual(deriveThresholds(32_768, { reserveTokens: 8192, warningRunwayTokens: null }).thresholds, { reserve: 8192, reminder: 32_768, warning: 24_576 }, "an invalid runway does not discard a valid reserve");
|
|
33
34
|
});
|
|
35
|
+
test("context caps accept whole tokens and decimal k/m suffixes without lossy rounding", () => {
|
|
36
|
+
for (const [text, tokens] of [["100k", 100_000], ["100000", 100_000], [" 1M ", 1_000_000], ["1.5k", 1500], ["off", null]]) {
|
|
37
|
+
assert.equal(parseContextCap(text), tokens);
|
|
38
|
+
}
|
|
39
|
+
for (const text of ["", "0", "-1k", "1.5", "NaN", "Infinity", "100k extra", "1e5", "9007199254740992"])
|
|
40
|
+
assert.equal(parseContextCap(text), undefined, text);
|
|
41
|
+
});
|
|
42
|
+
test("Pi cap controls warning, reported room and hard wipe, without changing the model or settings", async () => {
|
|
43
|
+
const sm = manager();
|
|
44
|
+
appendText(sm, "user", "ongoing work");
|
|
45
|
+
const settings = SettingsManager.inMemory(explicitBudgetSettings);
|
|
46
|
+
const captured = makeExtension(sm, settings);
|
|
47
|
+
const at = (tokens, window = 200_000) => {
|
|
48
|
+
const ctx = context(sm, undefined, { tokens, percent: tokens / window * 100, contextWindow: window });
|
|
49
|
+
ctx.model = { provider: "test", id: "cap-model", contextWindow: window };
|
|
50
|
+
return ctx;
|
|
51
|
+
};
|
|
52
|
+
const native = at(0), beforeSettings = settings.getSettings();
|
|
53
|
+
const room = async (ctx = at(0)) => resultJson(await call(captured, "get_context_remaining", {}, ctx)).remaining_tokens;
|
|
54
|
+
await runCommand(captured, "notesoup", "cap 100k", native);
|
|
55
|
+
assert.equal(await room(), 83_616);
|
|
56
|
+
assert.equal(native.model?.contextWindow, 200_000);
|
|
57
|
+
assert.deepEqual(settings.getSettings(), beforeSettings);
|
|
58
|
+
for (const invalid of ["cap 0", "cap nonsense", "cap 100k extra", "cap 16k"]) {
|
|
59
|
+
assert.equal((await runCommand(captured, "notesoup", invalid, at(0)))[0]?.type, "error");
|
|
60
|
+
assert.equal(await room(), 83_616, "invalid caps leave the previous cap intact");
|
|
61
|
+
}
|
|
62
|
+
const warning = await runContextHook(captured, at(67_232));
|
|
63
|
+
assert.equal(warning?.messages[0]?.customType, WARNING_TYPE);
|
|
64
|
+
assert.equal(await room(at(83_615)), 1);
|
|
65
|
+
assert.equal((await commitTurnEndBoundary(captured, sm, at(83_615))).entries.some((e) => e.type === "custom" && e.customType === RESET_MARKER_TYPE), false);
|
|
66
|
+
const hard = await commitTurnEndBoundary(captured, sm, at(83_616));
|
|
67
|
+
assert.equal(hard.entries.filter((e) => e.type === "custom" && e.customType === RESET_MARKER_TYPE).length, 1);
|
|
68
|
+
assert.equal(await room(at(1000)), 82_616, "the cap survives a notesoup reset");
|
|
69
|
+
assert.equal(await room(at(1000, 64_000)), 46_616, "a cap cannot enlarge a smaller model window");
|
|
70
|
+
await runCommand(captured, "notesoup", "cap off", at(0));
|
|
71
|
+
assert.equal(await room(), 183_616);
|
|
72
|
+
await runCommand(captured, "notesoup", "cap 100k", at(0));
|
|
73
|
+
await runHandlers(captured, "model_select", {}, at(0, 64_000));
|
|
74
|
+
assert.equal(await room(at(0, 64_000)), 47_616, "switching models preserves the cap but uses the smaller window");
|
|
75
|
+
await runHandlers(captured, "session_start", {}, at(0));
|
|
76
|
+
assert.equal(await room(), 183_616, "a new/reloaded session does not inherit the runtime cap");
|
|
77
|
+
});
|
|
34
78
|
test("Pi budget settings merge per key without changing native compaction settings or enablement", async () => {
|
|
35
79
|
const fixture = settingsFixture({
|
|
36
80
|
reserveTokens: 32_768,
|
|
@@ -278,6 +278,14 @@ test("Claude limits derive from Claude's own auto-compact point, never a fixed p
|
|
|
278
278
|
assert.equal(absurdMargin.source, "percent");
|
|
279
279
|
assert.ok(absurdMargin.reset > 0 && absurdMargin.warn > 0, "an absurd margin cannot zero the percent fallback either");
|
|
280
280
|
});
|
|
281
|
+
test("Claude caps the capacity before deriving the same warning and hard points", () => {
|
|
282
|
+
const facts = { usage: { window: 200_000 }, breakdown: { autoCompactThreshold: 167_000 }, capTokens: 100_000 };
|
|
283
|
+
assert.deepEqual(limitPoints(facts), { source: "window", unit: "tokens", autoCompact: true, native: 67_000, reset: 58_808, warn: 42_424 });
|
|
284
|
+
assert.equal(resolveClaudeLimits({ ...facts, capTokens: 1_000_000 }).reset, 158_808, "a cap never enlarges the model window");
|
|
285
|
+
assert.equal(resolveClaudeLimits({ usage: { window: 64_000 }, capTokens: 100_000 }).reset, 22_808, "a smaller model keeps its own limit");
|
|
286
|
+
assert.equal(resolveClaudeLimits({ ...facts, breakdown: { autoCompactThreshold: 50_000 } }).reset, 41_808, "an earlier native hard point still wins");
|
|
287
|
+
assert.equal(resolveClaudeLimits({ ...facts, settings: { autoCompactWindow: 80_000 }, breakdown: {} }).reset, 38_808, "a smaller configured window still wins");
|
|
288
|
+
});
|
|
281
289
|
test("Claude limits read margins from the notesoup settings shape and ignore garbage", () => {
|
|
282
290
|
const base = { usage: { window: 200_000 }, breakdown: { autoCompactThreshold: 167_000, isAutoCompactEnabled: true } };
|
|
283
291
|
assert.deepEqual(limitPoints({ ...base, settings: { notesoup: { resetMarginTokens: 10_000, warningRunwayTokens: 5_000 } } }), { source: "auto-compact", unit: "tokens", autoCompact: true, native: 167_000, reset: 157_000, warn: 152_000 });
|
|
@@ -556,7 +564,7 @@ test("Claude Mod hook delivers the helper's shared text, and marks only a refusa
|
|
|
556
564
|
assert.equal(crashed.isError, true);
|
|
557
565
|
assert.match(String(crashed.result), /^notesoup: helper execution failed: Error: spawn timed out after 10000ms$/, "the host's own reason survives the catch");
|
|
558
566
|
});
|
|
559
|
-
test("Claude Mod
|
|
567
|
+
test("Claude Mod clears at the shared hard point after successful settlement and retains one fresh boot", async (t) => {
|
|
560
568
|
const home = mkdtempSync(join(tmpdir(), "claude-reset-home-"));
|
|
561
569
|
t.after(() => rmSync(home, { recursive: true, force: true }));
|
|
562
570
|
const { host, registered, notifications } = fakeEngine(home);
|
|
@@ -564,7 +572,7 @@ test("Claude Mod crosses old reset thresholds without clearing and retains one f
|
|
|
564
572
|
(await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
|
|
565
573
|
const invoke = (name, event = {}) => handlers.get(name)(host, event, async () => ({ sentinel: name }));
|
|
566
574
|
assert.equal(handlers.has("session.measure"), false, "measure has no reset hook");
|
|
567
|
-
//
|
|
575
|
+
// Warning and automatic reset share the same native-derived points.
|
|
568
576
|
let tokens = 140_000;
|
|
569
577
|
let compactions = 0;
|
|
570
578
|
let kept = [];
|
|
@@ -597,16 +605,8 @@ test("Claude Mod crosses old reset thresholds without clearing and retains one f
|
|
|
597
605
|
assert.equal(compactions, 0, "one token below the resolved reset point");
|
|
598
606
|
await invoke("turn.start");
|
|
599
607
|
tokens = 158_808;
|
|
600
|
-
assert.equal(compactions, 0, "
|
|
608
|
+
assert.equal(compactions, 0, "measurement alone cannot compact under a running turn");
|
|
601
609
|
assert.deepEqual(await invoke("turn.complete", turnComplete()), { sentinel: "turn.complete" });
|
|
602
|
-
assert.equal(compactions, 0, "the old reset point no longer clears at turn completion");
|
|
603
|
-
tokens = 190_000;
|
|
604
|
-
await invoke("turn.start");
|
|
605
|
-
await invoke("turn.complete", turnComplete());
|
|
606
|
-
assert.equal(compactions, 0, "even beyond the native threshold, only a native auto event or explicit request resets");
|
|
607
|
-
await invoke("turn.start");
|
|
608
|
-
await invoke("command.run", { command: "empty" });
|
|
609
|
-
await invoke("turn.complete", turnComplete());
|
|
610
610
|
await settleHooks();
|
|
611
611
|
assert.equal(compactions, 1);
|
|
612
612
|
assert.equal(kept.length, 2, "the reset is the notes boot followed by the one reset message");
|
|
@@ -700,7 +700,7 @@ test("Claude headless resets through its own manual command, retries failure and
|
|
|
700
700
|
assert.match(kept[0].text, /claude:hook-session:2/);
|
|
701
701
|
assert.equal(kept.length, 2, "sticky is consumed once");
|
|
702
702
|
});
|
|
703
|
-
test("Claude headless warns
|
|
703
|
+
test("Claude headless warns, automatically resets at the hard point, and supports both manual aliases", async (t) => {
|
|
704
704
|
const home = mkdtempSync(join(tmpdir(), "claude-headless-auto-"));
|
|
705
705
|
t.after(() => rmSync(home, { recursive: true, force: true }));
|
|
706
706
|
const { host } = fakeEngine(home);
|
|
@@ -725,11 +725,8 @@ test("Claude headless warns without proactive resets and supports both manual al
|
|
|
725
725
|
await invoke("turn.start");
|
|
726
726
|
assert.equal(attempts, 0);
|
|
727
727
|
await invoke("turn.complete", turnComplete());
|
|
728
|
-
assert.equal(attempts, 0, "the old reset threshold and turn completion do not clear");
|
|
729
|
-
await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
|
|
730
|
-
await invoke("turn.complete", turnComplete());
|
|
731
728
|
await settleHooks();
|
|
732
|
-
assert.equal(attempts, 1);
|
|
729
|
+
assert.equal(attempts, 1, "the hard point clears after successful settlement without a tool request");
|
|
733
730
|
for (const command of ["empty", "fresh-window"]) {
|
|
734
731
|
assert.deepEqual(await invoke("command.run", { command }), { text: "🥣 Dumping Brain" });
|
|
735
732
|
await settleHooks();
|
|
@@ -817,7 +814,7 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
|
|
|
817
814
|
};
|
|
818
815
|
(await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
|
|
819
816
|
await invoke("session.start", { cwd: home, isInteractive: true });
|
|
820
|
-
assert.deepEqual(commands.sort(), ["empty", "fresh-window"], "
|
|
817
|
+
assert.deepEqual(commands.sort(), ["empty", "fresh-window", "notesoup"], "the cap command and both reset aliases are registered");
|
|
821
818
|
assert.deepEqual(await invoke("command.run", { command: "empty-brain" }), {}, "the retired spelling passes through instead of resetting");
|
|
822
819
|
assert.equal(compactions, 0);
|
|
823
820
|
const command = await invoke("command.run", { command: "empty" });
|
|
@@ -1148,13 +1145,9 @@ test("Claude Mod retries an unresolvable warning threshold inside the same windo
|
|
|
1148
1145
|
host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
|
|
1149
1146
|
host.command.run = async ({ args }) => { compactions++; await nativeCompaction(host, handlers, args); return {}; };
|
|
1150
1147
|
await invoke("session.start", { cwd: home, isInteractive: true });
|
|
1151
|
-
await invoke("turn.start");
|
|
1152
|
-
await invoke("turn.complete", turnComplete());
|
|
1153
1148
|
await handlers.get("prompt.submit")(host, { text: "continue" }, async (e) => e);
|
|
1154
1149
|
assert.equal(limitsCalls, 1, "the first limits round trip failed");
|
|
1155
1150
|
assert.equal(compactions, 0, "one failed resolution does not disable the window");
|
|
1156
|
-
await invoke("turn.start");
|
|
1157
|
-
await invoke("turn.complete", turnComplete());
|
|
1158
1151
|
const retried = await handlers.get("prompt.submit")(host, { text: "continue" }, async (e) => e);
|
|
1159
1152
|
assert.deepEqual(retried.context, [CLAUDE_WARNING_PROMPT]);
|
|
1160
1153
|
assert.equal(limitsCalls, 2, "the retry runs in the same window");
|
|
@@ -1178,6 +1171,72 @@ async function retainedFixture(t) {
|
|
|
1178
1171
|
assert.deepEqual((await context()).blocks, [], "the existing boot is retained, not injected twice");
|
|
1179
1172
|
return { home, host, invoke, context, boot, handlers, notifications };
|
|
1180
1173
|
}
|
|
1174
|
+
test("Claude runtime cap warns and clears at a safe main batch boundary, then survives the reset", async (t) => {
|
|
1175
|
+
const { host, invoke, handlers } = await retainedFixture(t);
|
|
1176
|
+
let tokens = 42_423, window = 200_000, resets = 0;
|
|
1177
|
+
const prompts = [];
|
|
1178
|
+
const settings = { autoCompactWindow: 200_000 };
|
|
1179
|
+
host.settings.read = async () => settings;
|
|
1180
|
+
host.session.usage = async () => ({ context: { tokens, window, breakdown: { autoCompactThreshold: window - 33_000, isAutoCompactEnabled: true, model: "claude" } } });
|
|
1181
|
+
host.prompt.submit = async ({ text }) => { prompts.push(text); return { text }; };
|
|
1182
|
+
host.command.run = async ({ command, args }) => {
|
|
1183
|
+
assert.equal(command, "compact", "the existing notes-only reset runs; /autocompact is never called");
|
|
1184
|
+
resets++;
|
|
1185
|
+
await nativeCompaction(host, handlers, args);
|
|
1186
|
+
tokens = undefined;
|
|
1187
|
+
return {};
|
|
1188
|
+
};
|
|
1189
|
+
const cap = async (args) => await invoke("command.run", { command: "notesoup", args });
|
|
1190
|
+
assert.match((await cap("cap 100k")).text, /100,000/);
|
|
1191
|
+
for (const value of ["cap 0", "cap garbage", "cap 100k extra", "cap 1k"]) {
|
|
1192
|
+
assert.match((await cap(value)).text, /Usage:|too small/);
|
|
1193
|
+
assert.match((await cap("cap")).text, /100,000/, "a refused cap keeps the previous one");
|
|
1194
|
+
}
|
|
1195
|
+
assert.equal((await invoke("tool.call", { tool: "Read" })).context, undefined);
|
|
1196
|
+
tokens = 42_424;
|
|
1197
|
+
assert.deepEqual((await invoke("tool.call", { tool: "Read" })).context, [CLAUDE_WARNING_PROMPT]);
|
|
1198
|
+
tokens = 58_807;
|
|
1199
|
+
await invoke("turn.start", { turnId: "main" });
|
|
1200
|
+
const step = handlers.get("turn.step");
|
|
1201
|
+
const chunks = async (agentId) => {
|
|
1202
|
+
const result = [];
|
|
1203
|
+
for await (const chunk of step(host, { turnId: "main", index: 1, ...(agentId ? { agentId } : {}) }, async function* () { yield { kind: "text", text: "model" }; return {}; }))
|
|
1204
|
+
result.push(chunk);
|
|
1205
|
+
return result;
|
|
1206
|
+
};
|
|
1207
|
+
assert.deepEqual(await chunks(), [{ kind: "text", text: "model" }]);
|
|
1208
|
+
tokens = 58_808;
|
|
1209
|
+
await Promise.all([invoke("tool.call", { tool: "Read" }), invoke("tool.call", { tool: "Bash" })]);
|
|
1210
|
+
assert.equal(resets, 0, "all sibling tool results finish before the hard point can act");
|
|
1211
|
+
assert.deepEqual(await chunks("child"), [{ kind: "text", text: "model" }], "child steps never reset the main brain");
|
|
1212
|
+
assert.deepEqual(await chunks(), [{ kind: "stop", stopReason: "end_turn", usage: null }]);
|
|
1213
|
+
await invoke("turn.complete", turnComplete({ turnId: "main", reason: "error" }));
|
|
1214
|
+
await settleHooks();
|
|
1215
|
+
assert.equal(resets, 0, "a failed turn cannot commit a budget reset");
|
|
1216
|
+
await invoke("turn.start", { turnId: "main" });
|
|
1217
|
+
await chunks();
|
|
1218
|
+
await invoke("turn.complete", turnComplete({ turnId: "main" }));
|
|
1219
|
+
await settleHooks();
|
|
1220
|
+
assert.equal(resets, 1);
|
|
1221
|
+
assert.equal(prompts.length, 1, "a confirmed automatic reset continues exactly once");
|
|
1222
|
+
assert.ok(FORCED_CONTINUATIONS.includes((await host.session.messages())[1].text), "only a real tool request uses the normal handoff pool");
|
|
1223
|
+
assert.match((await cap("cap")).text, /100,000/, "cap survives notesoup rollover");
|
|
1224
|
+
assert.deepEqual(settings, { autoCompactWindow: 200_000 }, "the user's settings stay untouched");
|
|
1225
|
+
await cap("cap off");
|
|
1226
|
+
tokens = 80_000;
|
|
1227
|
+
await invoke("turn.start", { turnId: "main" });
|
|
1228
|
+
assert.deepEqual(await chunks(), [{ kind: "text", text: "model" }], "off immediately restores the native budget");
|
|
1229
|
+
window = 64_000;
|
|
1230
|
+
tokens = 22_807;
|
|
1231
|
+
await cap("cap 100k");
|
|
1232
|
+
assert.deepEqual(await chunks(), [{ kind: "text", text: "model" }]);
|
|
1233
|
+
tokens++;
|
|
1234
|
+
await invoke("turn.complete", turnComplete({ turnId: "main" }));
|
|
1235
|
+
await settleHooks();
|
|
1236
|
+
assert.equal(resets, 2, "a smaller model clears at its own point, not at the cap's point");
|
|
1237
|
+
await invoke("session.end");
|
|
1238
|
+
assert.match((await cap("cap")).text, /cap off/, "a different session does not inherit the runtime cap");
|
|
1239
|
+
});
|
|
1181
1240
|
test("Claude empty_brain stops at the batch boundary, carries last_word, and resumes once after commit", async (t) => {
|
|
1182
1241
|
const { host, invoke, handlers } = await retainedFixture(t);
|
|
1183
1242
|
host.session.usage = async () => ({ context: { tokens: 100, window: 200_000 } });
|
package/dist/test/dsh.test.js
CHANGED
|
@@ -8,7 +8,8 @@ import { tmpdir } from "node:os";
|
|
|
8
8
|
import { join } from "node:path";
|
|
9
9
|
import { resolveProjectNamespace } from "../src/notes/project-namespace.js";
|
|
10
10
|
import { WINDOW_IDENTITY_CLOSE_TAG, WINDOW_IDENTITY_OPEN_TAG } from "../src/boot/text.js";
|
|
11
|
-
import { notesRead } from "../src/tools/notes.js";
|
|
11
|
+
import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../src/tools/notes.js";
|
|
12
|
+
import { historyList, historyRead } from "../src/tools/history.js";
|
|
12
13
|
import { notesToolContext } from "../src/tools/notes-context.js";
|
|
13
14
|
import { success } from "../src/result.js";
|
|
14
15
|
import { createNotesStore } from "../src/notes/index.js";
|
|
@@ -24,6 +25,17 @@ function prompt(text) { return createUserMessage({ content: [{ type: "text", tex
|
|
|
24
25
|
async function run(agent, text) { agent.followup(prompt(text)); await agent.whenIdle(); }
|
|
25
26
|
function system(request) { return typeof request.system === "string" ? request.system : request.system?.map((block) => block.text).join("\n") ?? ""; }
|
|
26
27
|
function code(expected) { return (error) => error?.code === expected; }
|
|
28
|
+
test("dsh preserves shared tool and parameter descriptions verbatim", async (t) => {
|
|
29
|
+
const { ctx } = await dshFixture(t);
|
|
30
|
+
for (const operation of [notesWrite, notesUpdate, notesRead, notesList, notesSearch, historyList, historyRead]) {
|
|
31
|
+
const registered = ctx.tools.get(operation.name);
|
|
32
|
+
assert.equal(registered.description, operation.description);
|
|
33
|
+
const properties = registered.parameters.properties;
|
|
34
|
+
for (const [name, parameter] of Object.entries(operation.parameters.properties)) {
|
|
35
|
+
assert.equal(properties[name].description, parameter.description, `${operation.name}.${name}`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
});
|
|
27
39
|
// Critical lifecycle tests exercise the actual loop, DeepSeek HTTP adapter, tool registry,
|
|
28
40
|
// token meter and SQLite query service. Only the provider is a scripted Messages server.
|
|
29
41
|
test("dsh registered tools query other DSH sessions and foreign Pi files through the same session surface", async (t) => {
|
|
@@ -85,7 +85,7 @@ test("tools set policy, validate values, and visibly report effective policy and
|
|
|
85
85
|
const updated = await notesUpdate.execute({ address: "custom", readonly: false, edits: [{ oldText: "😀".repeat(2), newText: "😀".repeat(3) }] }, context);
|
|
86
86
|
assert.equal(Check(notesUpdate.outputSchema, wireResult(updated)), true);
|
|
87
87
|
assert.equal(data(updated).warnings.length, 1);
|
|
88
|
-
assert.match(notesUpdate.render(updated), /3 Unicode code points, over budget 2
|
|
88
|
+
assert.match(notesUpdate.render(updated), /3 Unicode code points, over budget 2 — boil it down\./);
|
|
89
89
|
assert.equal((await notes.read("custom")).body, "😀".repeat(3), "over budget saves the entire body");
|
|
90
90
|
const read = await notesRead.execute({ address: "custom", max_chars: 10 }, context);
|
|
91
91
|
assert.equal(Check(notesRead.outputSchema, wireResult(read)), true);
|
|
@@ -102,6 +102,11 @@ test("tools set policy, validate values, and visibly report effective policy and
|
|
|
102
102
|
assert.equal(data(search).files[0].budget, 2);
|
|
103
103
|
assert.match(notesSearch.render(search), /pinned true \| budget 2 \| readonly false/);
|
|
104
104
|
assert.match(notesSearch.render(search), /Warning: note body is 3/);
|
|
105
|
+
const overflow = await notesWrite.execute({ address: "overflow", content: "😀".repeat(3), budget: 2 }, context);
|
|
106
|
+
for (const warnings of [data(overflow).warnings, data(read).warnings]) {
|
|
107
|
+
assert.ok(warnings.length > 0);
|
|
108
|
+
assert.ok(warnings.every(warning => warning.endsWith("— boil it down.")));
|
|
109
|
+
}
|
|
105
110
|
const larger = await notesUpdate.execute({ address: "custom", budget: 4, pinned: false }, context);
|
|
106
111
|
assert.deepEqual(data(larger).warnings, []);
|
|
107
112
|
assert.equal(data(larger).change_kind, "metadata");
|
|
@@ -334,6 +334,33 @@ test("an over-budget note search match is a marked prefix with an honest line ad
|
|
|
334
334
|
}
|
|
335
335
|
assert.ok(parts.join("").endsWith(hugeLine), "resuming across pages reconstructs the matched body line");
|
|
336
336
|
});
|
|
337
|
+
for (const [label, padding, cap] of [
|
|
338
|
+
["match cap", 0, 2],
|
|
339
|
+
["output budget", Math.floor(TOOL_OUTPUT_MAX_BYTES / 3), undefined],
|
|
340
|
+
["both limits", Math.floor(TOOL_OUTPUT_MAX_BYTES / 3), 6],
|
|
341
|
+
["shortened first line", TOOL_OUTPUT_MAX_BYTES * 2, undefined],
|
|
342
|
+
]) {
|
|
343
|
+
test(`notes_search reports dropped lines after ${label}`, async () => {
|
|
344
|
+
const session = manager();
|
|
345
|
+
const captured = makeExtension(session);
|
|
346
|
+
const ctx = context(session);
|
|
347
|
+
const lines = Array.from({ length: padding > TOOL_OUTPUT_MAX_BYTES ? 3 : 8 }, (_, index) => `needle ${index}${"y".repeat(padding)}`);
|
|
348
|
+
resultData(await call(captured, "notes_write", { address: "matches.md", content: lines.join("\n") }, ctx));
|
|
349
|
+
const raw = await call(captured, "notes_search", { query: "needle", max_matches_per_file: cap }, ctx);
|
|
350
|
+
assertWithinBudget(raw, label);
|
|
351
|
+
const found = resultData(raw);
|
|
352
|
+
assert.equal(found.more, 0, "line omissions are separate from omitted pages");
|
|
353
|
+
const [file] = found.files;
|
|
354
|
+
assert.ok(file);
|
|
355
|
+
assert.ok(file.matches.length > 0 && file.matches.length < lines.length);
|
|
356
|
+
if (cap !== undefined)
|
|
357
|
+
assert.ok(file.matches.length <= cap);
|
|
358
|
+
if (padding > 0)
|
|
359
|
+
assert.ok(file.matches.length < (cap ?? lines.length), "the output budget also drops lines");
|
|
360
|
+
assert.equal(file.more_matches, lines.length - file.matches.length);
|
|
361
|
+
assert.ok(textOf(raw).includes(`${file.more_matches} more lines`));
|
|
362
|
+
});
|
|
363
|
+
}
|
|
337
364
|
test("notes_search ignores case, treats queries literally, and preserves original Unicode offsets", async () => {
|
|
338
365
|
const session = manager();
|
|
339
366
|
const captured = makeExtension(session);
|
|
@@ -342,6 +369,7 @@ test("notes_search ignores case, treats queries literally, and preserves origina
|
|
|
342
369
|
const found = resultData(await call(captured, "notes_search", { query: ["missing", "needle.*"], glob: "case-match.md" }, ctx));
|
|
343
370
|
assert.equal(found.files.length, 1);
|
|
344
371
|
assert.equal(found.files[0].matches.length, 1);
|
|
372
|
+
assert.equal(found.files[0].more_matches, undefined);
|
|
345
373
|
const hit = found.files[0];
|
|
346
374
|
const read = resultRead(await call(captured, "notes_read", { address: hit.address, offset_chars: hit.matches[0].offset_chars }, ctx));
|
|
347
375
|
assert.equal(read.content, "NeEdLe.* tail");
|
package/docs/claude-code-mod.md
CHANGED
|
@@ -2,19 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
The package also ships `plugins/claude/`, an early-access Claude Code Mod that registers five notes tools as `mcp__notesoup__notes_*`, two history tools as `mcp__notesoup__history_*`, and `mcp__notesoup__empty_brain` and attaches one host-scoped notes boot block through Claude's conversation-scoped `prompt.context` event; Claude persists it across resume and reload. The sandboxed hooks module delegates filesystem and shared-domain work to the plugin-local `plugins/claude/dist/claude/helper.js` through Claude's bounded `$.process.run` capability.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Warning and automatic clear use one budget policy. The existing warning and reset points are derived from Claude's own auto-compact threshold instead of a fixed percent, in `plugins/claude/src/thresholds.ts`, and reach the sandboxed hooks module through the helper's `limits` operation. At the hard point, the next main `turn.step` ends the old turn after its whole tool batch; a successful main `turn.complete` also checks the point when no request is already pending. Both enter the existing non-held reset worker, without a separate cap-specific trigger. Measurement alone never clears context, child events cannot reset the main brain, and aborted/error/refusal turns do not commit a budget reset. The policy resolves its native point as follows:
|
|
6
6
|
|
|
7
7
|
1. `$.session.usage({breakdown:"summary"}).context.breakdown.autoCompactThreshold` when it is a positive number, with `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` applied the way Claude applies it (it can only lower the point);
|
|
8
8
|
2. otherwise computed from `$.session.usage().context.window` plus `CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `modelSettings.<model>.autoCompactWindow` and `autoCompactWindow` (the smallest configured window wins, capped at the model window), with Claude's 20000-token output reserve and 13000-token summary buffer; `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` lowers this fallback point by the same formula. With auto-compaction off, the percent override is ignored;
|
|
9
9
|
3. otherwise the percent fallback, which assumes a classic 200K capacity, applies the same configured-window caps and token derivation, then converts the points to percentages.
|
|
10
10
|
|
|
11
|
-
The
|
|
11
|
+
The hard clear point is `resetMarginTokens` (default 8192) below the native point; the warning is another `warningRunwayTokens` (default `WARNING_RUNWAY_TOKENS`, 16384) below that. Resolved points are reused only while the current model, cap, threshold inputs and settings match; changing context fill alone does not invalidate them. With automatic compaction off (`autoCompactEnabled: false` in the merged settings, or `DISABLE_AUTO_COMPACT=1`) the point becomes the effective window minus the output reserve, so the same warning margins still apply, but automatic notesoup clears are disabled too. Explicit resets remain available. Every undocumented field is type-guarded and degrades to the next source; an unresolvable point, or missing usage, logs once and skips the budget warning. `DISABLE_COMPACT=1` is detected at `session.start`, logs once, suppresses budget warnings and explicit resets, and makes `/fresh-window` report that it cannot run. The margins are read from the `notesoup` object of Claude's merged `$.settings.read()` (`resetMarginTokens`, `warningRunwayTokens`); any other value is ignored. Setting `NOTESOUP_DISABLED` (presence-style, the same convention as `DISABLE_COMPACT`) turns the whole mod off: `session.start` registers no tools or commands and logs once, every event passes through untouched, and native compaction behaves as if the mod were absent.
|
|
12
|
+
|
|
13
|
+
`/notesoup cap 100k` supplies a runtime-only capacity ceiling, clamped to the smaller model/configured window before the same reserves and margins are deducted. A reported native threshold can only be lowered, never raised. `/notesoup cap` (or bare `/notesoup`) shows the cap; `/notesoup cap off` restores the uncapped policy. Whole tokens and decimal `k`/`m` suffixes are accepted, with caps too small for reserves refused. The cap survives notesoup rollover and model changes but is cleared on plugin reload, session end or session identity change. It does not call `/autocompact`, alter the model, or write settings/environment variables. An already pending reset keeps its continuation/STOP policy when the cap changes.
|
|
12
14
|
|
|
13
15
|
Once per window, when the measured context crosses the warning point, main-agent tool results or prompt submission carry exactly the same budget warning as Pi, ending with `empty_brain` and the countdown. Delivery is consumed only when the downstream chain accepts the warning. The warned flag resets with the window ordinal. Its own `session.compact` hook answers native compaction in the main conversation instead of letting it summarize: an automatic compaction (threshold or prompt-too-long) becomes the freshly built notes boot followed by one randomly selected handoff paragraph (normal only when the model called `empty_brain`, otherwise forced), selected once for the new window and reused on retry — the same boot-then-handoff order as Pi — while user `/compact` and precompute are vetoed with a one-line notice. `prompt.context` still recomputes but does not duplicate that retained boot. The boot's protocol block binds the shared reset sentence to `mcp__notesoup__empty_brain`; Pi's boot text is unchanged. Boot window IDs end in the ordinal `:0`, `:1`, etc.; retained boots restore the ordinal on resume/reload. Original transcript rows remain on disk. `session.end` forgets the old window, and identity is refreshed lazily from `$.session.id()`, `$.session.cwd()` and the documented `$.session.model()` (slugified, with `claude` only as a fallback). `/clear`, `/resume` and `/branch` therefore acquire a boot again without needing another `session.start`. A failed boot build falls back to Claude's own summary, which invalidates a removed retained boot; vetoes, subagent compaction and precompute leave it alone.
|
|
14
16
|
|
|
15
17
|
The reset flow has three separate lifetimes. `ResetFlow.request` lasts until successful reset or cancellation; it owns the first valid tool call's sticky note and continuation policy. `ResetState.commit` lasts for one native command attempt and tracks proof that Claude kept the boot. The per-turn cutoff can outlive the request when native auto compaction consumes it before the next step. Successful explicit reset and automatic reset share the same window/boot bookkeeping. A failed compaction retains the request for retry; an aborted, failed, or refused main turn cancels it. Session changes discard the flow and invalidate asynchronous work by generation.
|
|
16
18
|
|
|
17
|
-
`empty_brain` accepts optional `last_word` and boolean `terminate` (default `false`). Non-boolean `terminate` is refused before recording a request. The first valid tool call owns both arguments for that pending reset; duplicates can re-arm the cutoff but cannot replace them. Every tool in the response's batch finishes, including parallel siblings. At the requesting main turn's next `turn.step`, the cutoff yields a synthetic `end_turn` without another model request or aborting tools. Subagent steps pass through, and subagents cannot reset the main brain. After successful main `turn.complete`, the non-held reset worker compacts; a confirmed commit permits one plugin-origin continuation unless `terminate: true`, manual STOP, or natural input has taken over. The handoff and sticky are already retained alongside the boot and are not repeated by that prompt.
|
|
19
|
+
`empty_brain` accepts optional `last_word` and boolean `terminate` (default `false`). Non-boolean `terminate` is refused before recording a request. The first valid tool call owns both arguments for that pending reset; duplicates can re-arm the cutoff but cannot replace them. Every tool in the response's batch finishes, including parallel siblings. At the requesting main turn's next `turn.step`, the cutoff yields a synthetic `end_turn` without another model request or aborting tools. The automatic hard point uses the same cutoff and commit path; a budget reset uses the forced handoff pool and continues once only after a confirmed commit, unless manual STOP or natural input takes over. Subagent steps pass through, and subagents cannot reset the main brain. After successful main `turn.complete`, the non-held reset worker compacts; a confirmed commit permits one plugin-origin continuation unless `terminate: true`, manual STOP, or natural input has taken over. The handoff and sticky are already retained alongside the boot and are not repeated by that prompt.
|
|
18
20
|
|
|
19
21
|
Accepted natural input owns its continuation. Input received within the running turn, including input accepted before the first tool latch, releases the cutoff at the next step for the whole subsequent tool workflow. Input not yet delivered to a model request prevents reset work from starting. A separately queued natural turn also runs normally. No input is replayed. Native auto compaction consumes a pending request without resetting twice, while preserving its armed cutoff until turn completion or natural-input delivery; further auto compaction does not disarm it. Once that reset has completed and natural input releases its cutoff, a new `empty_brain` owns its own sticky and `terminate` policy. A consumed request's STOP does not carry into the new request.
|
|
20
22
|
|