notesoup 0.58.2 → 0.59.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.
Files changed (62) hide show
  1. package/README.md +2 -1
  2. package/dist/plugins/claude/src/helper.js +13 -0
  3. package/dist/plugins/claude/src/thresholds.js +17 -12
  4. package/dist/plugins/pi/budget.d.ts +3 -0
  5. package/dist/plugins/pi/budget.js +22 -11
  6. package/dist/plugins/pi/runtime.js +22 -6
  7. package/dist/src/boot/text.d.ts +1 -1
  8. package/dist/src/boot/text.js +5 -4
  9. package/dist/src/budget/cap.d.ts +2 -0
  10. package/dist/src/budget/cap.js +11 -0
  11. package/dist/src/notes/policy.d.ts +1 -1
  12. package/dist/src/notes/policy.js +4 -3
  13. package/dist/src/tools/notes.js +1 -1
  14. package/dist/test/agent-loop.test.js +13 -39
  15. package/dist/test/boot.integration.test.js +20 -18
  16. package/dist/test/budget-settings.integration.test.js +63 -14
  17. package/dist/test/claude-history.test.js +1 -2
  18. package/dist/test/claude-mod.test.js +96 -29
  19. package/dist/test/codex-history.test.js +9 -6
  20. package/dist/test/codex-plugin.test.js +4 -8
  21. package/dist/test/dream-skill.test.js +6 -10
  22. package/dist/test/dsh-cli.test.js +2 -3
  23. package/dist/test/dsh.test.js +1 -7
  24. package/dist/test/helpers/extension.js +3 -1
  25. package/dist/test/history-corpus.test.js +2 -3
  26. package/dist/test/history-prefilter.test.js +33 -40
  27. package/dist/test/history-summary-cache.test.js +1 -1
  28. package/dist/test/history.integration.test.js +11 -37
  29. package/dist/test/host-neutral.test.js +2 -2
  30. package/dist/test/marker.test.js +1 -2
  31. package/dist/test/model-facing-text.test.js +20 -187
  32. package/dist/test/note-policy.test.js +40 -22
  33. package/dist/test/notes-library.test.js +2 -2
  34. package/dist/test/notes.integration.test.js +36 -149
  35. package/dist/test/notes.test.js +13 -61
  36. package/dist/test/pi-render.test.js +23 -62
  37. package/dist/test/reset-lifecycle.test.js +4 -9
  38. package/docs/architecture.md +1 -1
  39. package/docs/claude-code-mod.md +5 -3
  40. package/docs/dsh.md +1 -1
  41. package/docs/notes-library.md +1 -1
  42. package/docs/reset-lifecycle.md +3 -1
  43. package/docs/tool-results.md +1 -1
  44. package/package.json +1 -1
  45. package/playbook.md +1 -1
  46. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  47. package/plugins/claude/dist/claude/helper.js +47 -17
  48. package/plugins/claude/hooks/register.ts +51 -5
  49. package/plugins/claude/playbook.md +1 -1
  50. package/plugins/claude/skills/dream/SKILL.md +1 -1
  51. package/plugins/claude/skills/memory/SKILL.md +1 -1
  52. package/plugins/claude/src/helper.ts +11 -0
  53. package/plugins/claude/src/thresholds.ts +18 -11
  54. package/plugins/codex/dist/codex/notesoup.js +10 -8
  55. package/plugins/pi/budget.ts +21 -11
  56. package/plugins/pi/runtime.ts +18 -6
  57. package/skills/dream/SKILL.md +1 -1
  58. package/skills/memory/SKILL.md +1 -1
  59. package/src/boot/text.ts +5 -4
  60. package/src/budget/cap.ts +9 -0
  61. package/src/notes/policy.ts +4 -3
  62. package/src/tools/notes.ts +1 -1
package/README.md CHANGED
@@ -50,6 +50,7 @@ pi -e npm:notesoup
50
50
  - **Migration (0.40.0)**: parameters renamed: `order` → `from`, `before`/`after` → `before_seq`/`after_seq`, `limit_chars` → `max_chars`, `wastebasket` → `crumpled`, `pattern` → `glob` (the standalone library's options included), and `notes_update`'s `change_kind` value `file` → `moved`. Old names are refused.
51
51
 
52
52
  - **Runtime toggle** — `/notesoup off` stops new automatic resets; `/notesoup on` re-enables them; bare `/notesoup` reports the state.
53
+ - **Context cap (Pi and Claude)** — `/notesoup cap 100k` limits the capacity used by notesoup's budget to `min(model window, 100000)`. Existing reserves and warning margins are deducted from that capacity; 100k is not the used-token reset point. `/notesoup cap` shows the configured cap and `/notesoup cap off` removes it. Whole tokens and decimal `k`/`m` suffixes are accepted; caps too small for the host's reserves are refused. The cap applies only to the running session, survives notesoup resets and model changes, and is lost on reload/restart/session switch. It never writes host settings or environment variables, changes the provider's advertised model window, or enables disabled automatic resets.
53
54
 
54
55
  ## Per-note policy
55
56
 
@@ -60,7 +61,7 @@ Notes have optional `pinned`, `budget`, and `readonly` frontmatter fields, also
60
61
  ```
61
62
 
62
63
  - **Pinned** notes are injected **in full** at boot. Root `CHEATSHEET.md` and `MAP.md` default to pinned; every other page defaults to unpinned. Explicit `pinned: false` overrides even a default page. Each notebook allows **five live pins**, including its existing default pages; crumpled notes do not count. A sixth pin, restore or move that exceeds the cap refuses without changing either note. Manually over-cap notebooks get a boot warning naming the omitted pins, with default pages shown first.
63
- - **Budget** defaults to **2048 Unicode code points for every page**, including CHEATSHEET and MAP. Any positive safe integer is allowed. Over-budget writes and updates succeed with a visible warning; pinned bodies are never truncated to their budget. This advisory budget is separate from the existing hard serialized-file byte limit. Tool results/read metadata/list/search expose effective policy and budget warnings.
64
+ - **Budget** defaults to **4096 Unicode code points for ordinary pages**, and **2048 for root CHEATSHEET.md and MAP.md**. Any positive safe integer is allowed. Over-budget writes and updates succeed with a visible warning; pinned bodies are never truncated to their budget. This advisory budget is separate from the existing hard serialized-file byte limit. Tool results/read metadata/list/search expose effective policy and budget warnings.
64
65
  - **Readonly** defaults to false. `readonly: true` is a **soft lock**, not security: mutations refuse until explicitly unlocked with `readonly: false`, either by itself or in the same call as the requested changes. A write can create and lock a note together. Reads still record access metadata; direct filesystem edits can bypass the lock.
65
66
 
66
67
  Absent fields stay absent on disk. On move/rename, implicit pin defaults follow the new root path; explicit true/false values travel with the note. The original origin, other metadata, and unknown frontmatter are preserved. See the [library API](docs/notes-library.md#per-note-policy) for details.
@@ -11,6 +11,7 @@ import { renderBootBlock } from "../../../src/boot/render.js";
11
11
  import { selectContinuation } from "../../../src/budget/text.js";
12
12
  import { claudeHistoryGapNotice, claudeHistoryUnconfirmedSeq, CLAUDE_HISTORY_UNKNOWN_WINDOW, CLAUDE_HISTORY_UNAVAILABLE_SENTENCE, CLAUDE_WARNING_PROMPT } from "./text.js";
13
13
  import { resolveClaudeLimits } from "./thresholds.js";
14
+ import { parseContextCap } from "../../../src/budget/cap.js";
14
15
  import { projectKey, snapshotNotesIdentity } from "../../../src/notes/index.js";
15
16
  import { notesToolContext } from "../../../src/tools/notes-context.js";
16
17
  const MAX_REQUEST_BYTES = 512 * 1024;
@@ -55,6 +56,18 @@ export async function dispatch(request, historyOptions = {}) {
55
56
  if (!request || typeof request !== "object" || Array.isArray(request))
56
57
  throw new Error("malformed request");
57
58
  const value = request;
59
+ if (value.op === "cap") {
60
+ const cap = typeof value.value === "string" ? parseContextCap(value.value) : undefined;
61
+ if (cap === undefined)
62
+ throw new Error("Usage: /notesoup cap [100k|1m|tokens|off]");
63
+ if (cap !== null) {
64
+ const facts = value.facts && typeof value.facts === "object" ? value.facts : {};
65
+ const limits = resolveClaudeLimits({ ...facts, capTokens: undefined, usage: { window: cap }, breakdown: {} });
66
+ if (limits.reset <= 1)
67
+ throw new Error("Cap is too small for Claude's output, compaction and reset reserves");
68
+ }
69
+ return { cap };
70
+ }
58
71
  if (value.op === "schemas")
59
72
  return [...Object.entries(OPERATIONS), ...Object.entries(HISTORY_OPERATIONS)].map(([name, operation]) => ({ name, description: operation.description, inputSchema: JSON.parse(JSON.stringify(operation.parameters)) }));
60
73
  // The shared reset prose lives here, not in the sandboxed hooks module, so Pi and Claude
@@ -58,6 +58,11 @@ function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
58
58
  native: tokens, reset, warn: Math.max(MIN_POINT_TOKENS, reset - warningRunway), resetMargin, warningRunway,
59
59
  };
60
60
  }
61
+ function windowPoint(window, autoCompact, pct) {
62
+ const available = window - CLAUDE_OUTPUT_RESERVE_TOKENS;
63
+ const threshold = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
64
+ return autoCompact ? pct === undefined ? threshold : Math.min(Math.floor(available * (pct / 100)), threshold) : available;
65
+ }
61
66
  /**
62
67
  * Resolve the points from whatever the host could read. Every field is undocumented-adjacent,
63
68
  * so a missing or malformed one degrades to the next source and finally to the percent
@@ -78,6 +83,13 @@ export function resolveClaudeLimits(facts) {
78
83
  && !presenceFlag(env.disableAutoCompact)
79
84
  && breakdown.isAutoCompactEnabled !== false;
80
85
  const pct = percent(env.pctOverride);
86
+ const window = positiveNumber(usage.window);
87
+ const capacity = window ?? ASSUMED_WINDOW_TOKENS;
88
+ const configured = configuredWindow(settings, env, breakdown.model);
89
+ const effective = Math.min(configured ?? capacity, capacity);
90
+ const cap = positiveInteger(root.capTokens);
91
+ const capped = cap !== undefined && cap < effective;
92
+ const nativeFromWindow = windowPoint(Math.min(effective, cap ?? Infinity), autoCompact, pct);
81
93
  // (a) Claude's own point. It already includes the window, model settings and CLI flag; only
82
94
  // the percent override is applied separately, on the window-after-output-reserve it is
83
95
  // minted from (threshold + summary buffer). A malformed override that floors the point to
@@ -85,20 +97,13 @@ export function resolveClaudeLimits(facts) {
85
97
  const threshold = positiveNumber(breakdown.autoCompactThreshold);
86
98
  if (autoCompact && threshold !== undefined) {
87
99
  const native = pct === undefined ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
88
- if (native > 0)
89
- return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
100
+ if (native > 0) {
101
+ const point = capped ? Math.min(native, nativeFromWindow) : native;
102
+ return tokenLimits(point < native ? "window" : "auto-compact", true, point, resetMargin, warningRunway);
103
+ }
90
104
  }
91
105
  // (b/c) Compute once, using the classic 200K capacity only when the host reports none.
92
- const window = positiveNumber(usage.window);
93
- const capacity = window ?? ASSUMED_WINDOW_TOKENS;
94
- const configured = configuredWindow(settings, env, breakdown.model);
95
- const effective = Math.min(configured ?? capacity, capacity);
96
- const available = effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
97
- const thresholdFromWindow = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
98
- const native = autoCompact
99
- ? pct === undefined ? thresholdFromWindow : Math.min(Math.floor(available * (pct / 100)), thresholdFromWindow)
100
- : available;
101
- const limits = tokenLimits(window === undefined ? "percent" : "window", autoCompact, native, resetMargin, warningRunway);
106
+ const limits = tokenLimits(window === undefined ? "percent" : "window", autoCompact, nativeFromWindow, resetMargin, warningRunway);
102
107
  if (window !== undefined)
103
108
  return limits;
104
109
  return {
@@ -11,6 +11,9 @@ export declare function registerBudget(pi: ExtensionAPI, isEnabled: () => boolea
11
11
  /** The same room before the hard-reserve wipe the model sees; null when usage is unknown. */
12
12
  statusFor: (ctx: ExtensionContext) => {
13
13
  remaining: number | null;
14
+ cap: number | undefined;
14
15
  };
16
+ /** Runtime-only cap; reserve and all warning margins keep their existing meanings. */
17
+ setCap: (value: number | undefined, ctx: ExtensionContext) => string | undefined;
15
18
  clear: () => void;
16
19
  };
@@ -14,11 +14,12 @@ export const ContextRemainingOutputSchema = Type.Object({
14
14
  remaining_tokens: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
15
15
  }, { additionalProperties: false });
16
16
  /** Remaining tokens in the provider's active window, or null without a usable estimate. */
17
- function remainingTokens(ctx) {
17
+ function remainingTokens(ctx, cap) {
18
18
  const usage = windowUsage(ctx);
19
- return !usage || usage.tokens === null ? null : Math.max(0, usage.contextWindow - usage.tokens);
19
+ return !usage || usage.tokens === null ? null : Math.max(0, Math.min(usage.contextWindow, cap ?? Infinity) - usage.tokens);
20
20
  }
21
21
  export function registerBudget(pi, isEnabled, settingsManager) {
22
+ let cap;
22
23
  let cachedPolicy;
23
24
  const notifiedWarnings = new Set();
24
25
  const resolvePolicy = (ctx) => {
@@ -41,17 +42,18 @@ export function registerBudget(pi, isEnabled, settingsManager) {
41
42
  if (!automaticResetEnabled(ctx))
42
43
  return false;
43
44
  if (preSendMessages) {
44
- const contextWindow = ctx.model?.contextWindow ?? ctx.getContextUsage()?.contextWindow;
45
- if (!contextWindow || contextWindow <= 0)
45
+ const nativeWindow = ctx.model?.contextWindow ?? ctx.getContextUsage()?.contextWindow;
46
+ if (!nativeWindow || nativeWindow <= 0)
46
47
  return false;
48
+ const contextWindow = Math.min(nativeWindow, cap ?? Infinity);
47
49
  const { reserve } = thresholdsFor(ctx);
48
50
  const estimate = estimateContextTokens(convertToLlm(preSendMessages));
49
51
  if (estimate.lastUsageIndex !== null && contextWindow - estimate.usageTokens <= reserve)
50
52
  return false;
51
53
  return contextWindow - estimate.tokens <= reserve;
52
54
  }
53
- const usage = windowUsage(ctx);
54
- return usage !== undefined && usage.tokens !== null && usage.contextWindow - usage.tokens <= thresholdsFor(ctx).reserve;
55
+ const remaining = remainingTokens(ctx, cap);
56
+ return remaining !== null && remaining <= thresholdsFor(ctx).reserve;
55
57
  };
56
58
  let pendingGuidance;
57
59
  let pendingWarning;
@@ -82,10 +84,10 @@ export function registerBudget(pi, isEnabled, settingsManager) {
82
84
  details: { anchorEntryId },
83
85
  }));
84
86
  };
85
- pi.on("session_start", (_event, ctx) => { resetForTransition(); thresholdsFor(ctx); });
87
+ pi.on("session_start", (_event, ctx) => { cap = undefined; resetForTransition(); thresholdsFor(ctx); });
86
88
  pi.on("session_tree", resetForTransition);
87
89
  pi.on("model_select", resetForTransition);
88
- pi.on("session_shutdown", resetForTransition);
90
+ pi.on("session_shutdown", () => { cap = undefined; resetForTransition(); });
89
91
  pi.on("agent_settled", clearStaged);
90
92
  pi.on("context", (event, ctx) => {
91
93
  if (!isEnabled())
@@ -102,7 +104,7 @@ export function registerBudget(pi, isEnabled, settingsManager) {
102
104
  // Without automatic reset nothing gets cleared, so there is nothing to remind about.
103
105
  if (!automaticResetEnabled(ctx))
104
106
  return result();
105
- const remaining = remainingTokens(ctx);
107
+ const remaining = remainingTokens(ctx, cap);
106
108
  if (remaining === null)
107
109
  return result();
108
110
  const windowId = currentWindowId(ctx);
@@ -142,7 +144,7 @@ export function registerBudget(pi, isEnabled, settingsManager) {
142
144
  outputSchema: ContextRemainingOutputSchema,
143
145
  async execute(_id, _params, _signal, _update, ctx) {
144
146
  // Report room to the hard-reserve wipe, including the warning runway.
145
- const remaining = remainingTokens(ctx);
147
+ const remaining = remainingTokens(ctx, cap);
146
148
  const value = { remaining_tokens: remainingBudget(remaining, thresholdsFor(ctx).reserve) };
147
149
  return { ...output(value), structuredContent: value };
148
150
  },
@@ -152,7 +154,16 @@ export function registerBudget(pi, isEnabled, settingsManager) {
152
154
  hardReserveDue,
153
155
  consumeTurnEnd,
154
156
  /** The same room before the hard-reserve wipe the model sees; null when usage is unknown. */
155
- statusFor: (ctx) => ({ remaining: remainingBudget(remainingTokens(ctx), thresholdsFor(ctx).reserve) }),
157
+ statusFor: (ctx) => ({ remaining: remainingBudget(remainingTokens(ctx, cap), thresholdsFor(ctx).reserve), cap }),
158
+ /** Runtime-only cap; reserve and all warning margins keep their existing meanings. */
159
+ setCap: (value, ctx) => {
160
+ const reserve = thresholdsFor(ctx).reserve;
161
+ if (value !== undefined && value <= reserve)
162
+ return `Cap must exceed the ${reserve.toLocaleString("en-US")}-token reset reserve`;
163
+ cap = value;
164
+ clearStaged();
165
+ return undefined;
166
+ },
156
167
  clear: () => { clearStaged(); notifiedWindows.clear(); },
157
168
  };
158
169
  }
@@ -17,6 +17,7 @@ import { buildBootMessage, sendBoot } from "./boot.js";
17
17
  import { maybeSendMarker } from "./marker.js";
18
18
  import { nextHistorySeq } from "./history.js";
19
19
  import { errorMessage } from "../../src/error-message.js";
20
+ import { parseContextCap } from "../../src/budget/cap.js";
20
21
  function readPackageVersion() {
21
22
  for (const up of ["../../package.json", "../../../package.json"]) {
22
23
  try {
@@ -157,11 +158,26 @@ export function registerContext(pi, settingsManager) {
157
158
  }
158
159
  });
159
160
  pi.registerCommand("notesoup", {
160
- description: "Show loaded version/build and toggle notesoup context windows",
161
- getArgumentCompletions: (prefix) => ["on", "off"].filter((a) => a.startsWith(prefix)).map((a) => ({ value: a, label: a })),
161
+ description: "Show notesoup status, toggle context windows, or cap their capacity",
162
+ getArgumentCompletions: (prefix) => ["on", "off", "cap", "cap off"].filter((a) => a.startsWith(prefix)).map((a) => ({ value: a, label: a })),
162
163
  handler: async (args, cmdCtx) => {
163
164
  const arg = args.trim().toLowerCase();
164
- if (arg === "on") {
165
+ const parts = arg.split(/\s+/);
166
+ if (parts[0] === "cap") {
167
+ if (parts.length > 1) {
168
+ const value = parts.length === 2 ? parseContextCap(parts[1]) : undefined;
169
+ if (value === undefined) {
170
+ cmdCtx.ui.notify("Usage: /notesoup cap [100k|1m|tokens|off]", "error");
171
+ return;
172
+ }
173
+ const error = budget.setCap(value ?? undefined, cmdCtx);
174
+ if (error) {
175
+ cmdCtx.ui.notify(`🥣 ${error}`, "error");
176
+ return;
177
+ }
178
+ }
179
+ }
180
+ else if (arg === "on") {
165
181
  enabled = true;
166
182
  const generation = ++lifecycleGeneration;
167
183
  await ensureBoot(pi, cmdCtx, notifyIncompleteNotes, () => generation === lifecycleGeneration && enabled);
@@ -176,11 +192,11 @@ export function registerContext(pi, settingsManager) {
176
192
  resets.clear();
177
193
  }
178
194
  else if (arg !== "") {
179
- cmdCtx.ui.notify("Usage: /notesoup [on|off]", "error");
195
+ cmdCtx.ui.notify("Usage: /notesoup [on|off|cap [100k|1m|tokens|off]]", "error");
180
196
  return;
181
197
  }
182
- const remaining = budget.statusFor(cmdCtx).remaining;
183
- cmdCtx.ui.notify(`🥣 notesoup ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION}${remaining === null ? "" : ` · ${remaining.toLocaleString("en-US")} tokens left`}`, "info");
198
+ const { remaining, cap } = budget.statusFor(cmdCtx);
199
+ cmdCtx.ui.notify(`🥣 notesoup ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION} · cap ${cap === undefined ? "off" : cap.toLocaleString("en-US")}${remaining === null ? "" : ` · ${remaining.toLocaleString("en-US")} tokens left`}`, "info");
184
200
  },
185
201
  });
186
202
  const emptyBrainCommand = (name) => ({
@@ -15,7 +15,7 @@ export declare const PROTOCOL_HISTORY_SENTENCE = "History can still be dug up, p
15
15
  /**
16
16
  * Default pinned pages and per-note policy are taught between the protocol and the notes index.
17
17
  */
18
- export declare const MAPS_BLOCK = "<notesoup:maps>\nEvery notebook's root has two default pins: `CHEATSHEET.md` and `MAP.md`.\nPinned pages get jammed straight into your brain the moment you wake up. Whoever wakes up next\nreads them, and next is you. So keep them short, and keep them true.\n\nSet `pinned`, `budget`, and `readonly` with the note tools or frontmatter. Each notebook allows five\nlive pins, including the defaults; `pinned:false` unpins even a default page. Every page's budget\nstarts at 2048 Unicode code points; set a positive integer to change it. Going over warns but saves,\nand pinned bodies arrive whole, not cut short. `readonly:true` is a soft lock, not security;\nexplicitly set `readonly:false` to unlock, on its own or with your changes.\n\n- **`CHEATSHEET.md`** holds what you'll want next time \u2014 a rule, a warning, a grudge, a name,\n a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat\n and everybody pays for it.\n- **`MAP.md`** is only the note index. One line per durable note: the address, then a gist short\n enough to tell whether the thing is worth opening. Rules belong in `CHEATSHEET.md`, and note\n contents belong in their own notes \u2014 *taps the sign* not inline here.\n\nEach notebook keeps its own: `@project`, `@human`, `@self`, `@model`. Missing pages are skipped;\nno need to create empty ones. New note, new MAP line. New rule worth remembering, new Cheatsheet\nline. And when a line stops being true, kill it \u2014 every window after you reads that page as fact.\n</notesoup:maps>";
18
+ export declare const MAPS_BLOCK = "<notesoup:maps>\nEvery notebook's root has two default pins: `CHEATSHEET.md` and `MAP.md`.\nPinned pages get jammed straight into your brain the moment you wake up. Whoever wakes up next\nreads them, and next is you. So keep them short, and keep them true.\n\nSet `pinned`, `budget`, and `readonly` with the note tools or frontmatter. Each notebook allows five\nlive pins, including the defaults; `pinned:false` unpins even a default page. Budgets start at 4096\nUnicode code points, or 2048 for root `CHEATSHEET.md` and `MAP.md`; set a positive integer to\nchange one. Going over warns but saves, and pinned bodies arrive whole, not cut short.\n`readonly:true` is a soft lock, not security; explicitly set `readonly:false` to unlock,\non its own or with your changes.\n\n- **`CHEATSHEET.md`** holds what you'll want next time \u2014 a rule, a warning, a grudge, a name,\n a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat\n and everybody pays for it.\n- **`MAP.md`** is only the note index. One line per durable note: the address, then a gist short\n enough to tell whether the thing is worth opening. Rules belong in `CHEATSHEET.md`, and note\n contents belong in their own notes \u2014 *taps the sign* not inline here.\n\nEach notebook keeps its own: `@project`, `@human`, `@self`, `@model`. Missing pages are skipped;\nno need to create empty ones. New note, new MAP line. New rule worth remembering, new Cheatsheet\nline. And when a line stops being true, kill it \u2014 every window after you reads that page as fact.\n</notesoup:maps>";
19
19
  /** Logical tool names are supplied by the composing host, not discovered here. */
20
20
  export type BootToolNames = Readonly<{
21
21
  notes: string;
@@ -62,10 +62,11 @@ Pinned pages get jammed straight into your brain the moment you wake up. Whoever
62
62
  reads them, and next is you. So keep them short, and keep them true.
63
63
 
64
64
  Set \`pinned\`, \`budget\`, and \`readonly\` with the note tools or frontmatter. Each notebook allows five
65
- live pins, including the defaults; \`pinned:false\` unpins even a default page. Every page's budget
66
- starts at 2048 Unicode code points; set a positive integer to change it. Going over warns but saves,
67
- and pinned bodies arrive whole, not cut short. \`readonly:true\` is a soft lock, not security;
68
- explicitly set \`readonly:false\` to unlock, on its own or with your changes.
65
+ live pins, including the defaults; \`pinned:false\` unpins even a default page. Budgets start at 4096
66
+ Unicode code points, or 2048 for root \`CHEATSHEET.md\` and \`MAP.md\`; set a positive integer to
67
+ change one. Going over warns but saves, and pinned bodies arrive whole, not cut short.
68
+ \`readonly:true\` is a soft lock, not security; explicitly set \`readonly:false\` to unlock,
69
+ on its own or with your changes.
69
70
 
70
71
  - **\`CHEATSHEET.md\`** holds what you'll want next time — a rule, a warning, a grudge, a name,
71
72
  a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
@@ -0,0 +1,2 @@
1
+ /** Parse a slash-command cap: decimal k/m suffixes, whole tokens, or off. */
2
+ export declare function parseContextCap(value: string): number | null | undefined;
@@ -0,0 +1,11 @@
1
+ /** Parse a slash-command cap: decimal k/m suffixes, whole tokens, or off. */
2
+ export function parseContextCap(value) {
3
+ const text = value.trim().toLowerCase();
4
+ if (text === "off")
5
+ return null;
6
+ const match = /^(\d+(?:\.\d+)?)([km]?)$/.exec(text);
7
+ if (!match)
8
+ return undefined;
9
+ const tokens = Number(match[1]) * (match[2] === "m" ? 1_000_000 : match[2] === "k" ? 1_000 : 1);
10
+ return Number.isSafeInteger(tokens) && tokens > 0 ? tokens : undefined;
11
+ }
@@ -4,7 +4,7 @@ export type NotePolicyFields = {
4
4
  readonly?: boolean;
5
5
  };
6
6
  export type NotePolicy = Required<NotePolicyFields>;
7
- export declare const DEFAULT_NOTE_BUDGET = 2048;
7
+ export declare const DEFAULT_NOTE_BUDGET = 4096;
8
8
  export declare const MAX_PINNED_NOTES = 5;
9
9
  export declare function validateNotePolicy(fields: NotePolicyFields): void;
10
10
  /** Only root default pages are pinned implicitly; an explicit false always wins. */
@@ -1,5 +1,5 @@
1
1
  import { NoteError } from "./errors.js";
2
- export const DEFAULT_NOTE_BUDGET = 2048;
2
+ export const DEFAULT_NOTE_BUDGET = 4096;
3
3
  export const MAX_PINNED_NOTES = 5;
4
4
  /** Defaults and ordering live here; no other layer assigns behavior by page name. */
5
5
  const DEFAULT_PINNED_PAGES = ["CHEATSHEET.md", "MAP.md"];
@@ -15,9 +15,10 @@ export function validateNotePolicy(fields) {
15
15
  /** Only root default pages are pinned implicitly; an explicit false always wins. */
16
16
  export function effectiveNotePolicy(fields, path) {
17
17
  validateNotePolicy(fields);
18
+ const defaultPage = DEFAULT_PINNED_PAGES.some(page => page === path);
18
19
  return {
19
- pinned: fields.pinned ?? DEFAULT_PINNED_PAGES.some(page => page === path),
20
- budget: fields.budget ?? DEFAULT_NOTE_BUDGET,
20
+ pinned: fields.pinned ?? defaultPage,
21
+ budget: fields.budget ?? (defaultPage ? 2048 : DEFAULT_NOTE_BUDGET),
21
22
  readonly: fields.readonly ?? false,
22
23
  };
23
24
  }
@@ -17,7 +17,7 @@ const ORIGIN = Type.Optional(Type.Union([...ORIGIN_VALUES], {
17
17
  }));
18
18
  const POLICY_PARAMETERS = {
19
19
  pinned: Type.Optional(Type.Boolean({ description: "Inject the full body at boot. At most 5 live pins per notebook; root CHEATSHEET.md/MAP.md default true, all others false. Explicit false overrides the default." })),
20
- budget: Type.Optional(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "Body budget in Unicode code points (default 2048 for every note). Over budget warns but saves; boot does not truncate." })),
20
+ budget: Type.Optional(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "Body budget in Unicode code points (default 4096; root CHEATSHEET.md and MAP.md default 2048). Over budget warns but saves; boot does not truncate." })),
21
21
  readonly: Type.Optional(Type.Boolean({ description: "Soft lock, not a security boundary. true locks changes; explicitly pass false to unlock, including in the same call as edits or overwrite." })),
22
22
  };
23
23
  const PolicySchema = {
@@ -10,7 +10,7 @@ import { BOOT_TYPE, CARRIED_INPUT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, MANUAL
10
10
  import { historyFromSession } from "../plugins/pi/history.js";
11
11
  import { MARKER_INTERVAL } from "../plugins/pi/marker.js";
12
12
  import { assertBootHistory } from "./helpers/extension.js";
13
- import { DEFAULT_BOOT_TOOL_NAMES, MAPS_BLOCK, NOTES_PROTOCOL_OPEN_TAG, WINDOW_IDENTITY_OPEN_TAG, renderProtocolBlock } from "../src/boot/text.js";
13
+ import { DEFAULT_BOOT_TOOL_NAMES, MAPS_BLOCK, NAMELESS_AGENT, NOTES_PROTOCOL_OPEN_TAG, WINDOW_IDENTITY_OPEN_TAG, renderProtocolBlock } from "../src/boot/text.js";
14
14
  import { createNotesStore } from "../src/notes/index.js";
15
15
  import { agentSlug } from "../plugins/pi/notes/adapter.js";
16
16
  import { registerBudget } from "../plugins/pi/budget.js";
@@ -70,7 +70,6 @@ async function openFixture(options) {
70
70
  const streamSignals = [];
71
71
  const events = [];
72
72
  const notices = [];
73
- let budgetNotices = 0;
74
73
  let session;
75
74
  const loader = new DefaultResourceLoader({
76
75
  cwd: dir,
@@ -132,15 +131,7 @@ async function openFixture(options) {
132
131
  };
133
132
  await session.bindExtensions({
134
133
  uiContext: {
135
- notify(message, type) {
136
- if (message === "🥣 Brain forcibly emptied: overflow") {
137
- const marker = sessionManager.getBranch().filter((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE).at(-1);
138
- const windowId = marker?.data?.windowId;
139
- assert.ok(sessionManager.getBranch().some((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE && entry.data?.windowId === windowId), "notification follows the reset marker commit");
140
- assert.ok(sessionManager.getBranch().some((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE && entry.details?.windowId === windowId), "notification follows the reset boot commit");
141
- }
142
- if (type === "warning" && /^🥣 Brain almost full/.test(message))
143
- budgetNotices++;
134
+ notify(message) {
144
135
  notices.push(message);
145
136
  },
146
137
  },
@@ -156,7 +147,6 @@ async function openFixture(options) {
156
147
  streamSignals,
157
148
  events,
158
149
  notices,
159
- budgetNotices: () => budgetNotices,
160
150
  close: () => {
161
151
  session.dispose();
162
152
  if (managesEnvironment) {
@@ -213,8 +203,6 @@ const COMMAND_WARNING_JSON = JSON.stringify(commandWarningContent()).slice(1, -1
213
203
  function assertUserContent(context, content) {
214
204
  assert.ok(context?.messages.some((message) => message.role === "user" && JSON.stringify(message.content) === JSON.stringify(content)), "carried input reaches the provider verbatim as user content");
215
205
  }
216
- /** Recognize reset completion notices, including the removed normal-reset wording. */
217
- const isResetSuccessNotice = (notice) => notice.includes("🥣 Fresh brain") || notice.includes("🥣 Brain forcibly emptied");
218
206
  function resetMarkers(fixture) {
219
207
  return fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE);
220
208
  }
@@ -304,7 +292,7 @@ test("real AgentSession: protocol and tool directory stay in system while window
304
292
  const boots = context.messages.filter((message) => message.role === "user" && JSON.stringify(message.content).includes(WINDOW_IDENTITY_OPEN_TAG));
305
293
  assert.equal(boots.length, 1, "one user boot reaches the provider");
306
294
  const boot = JSON.stringify(boots[0]);
307
- assert.ok(boot.includes("YOUR NOTES") && boot.includes(request === 3 ? "HUMAN_PIN_AFTER_RESET" : "HUMAN_PIN_BEFORE_RESET"), "the notes snapshot changes only at reset");
295
+ assert.ok(boot.includes(request === 3 ? "HUMAN_PIN_AFTER_RESET" : "HUMAN_PIN_BEFORE_RESET"), "the notes snapshot changes only at reset");
308
296
  assert.equal(boot.includes(NOTES_PROTOCOL_OPEN_TAG), false);
309
297
  assert.equal(boot.includes("<notesoup:maps>"), false);
310
298
  assert.equal(context.messages.filter((message) => message.role === "system" && message.sections?.notesoup_protocol !== undefined).length, 1, "unchanged teaching adds no duplicate delta");
@@ -358,7 +346,7 @@ test("real AgentSession: identity changes update system teaching and the next bo
358
346
  compactionEnabled: false,
359
347
  script: (request, context) => {
360
348
  const protocol = getCurrentSystemMessage(context.messages)?.sections?.notesoup_protocol;
361
- assert.equal(protocol?.includes("public square shared by every nameless nobody"), request === 1, "the protocol follows the live named/nameless identity");
349
+ assert.ok(protocol?.includes(renderProtocolBlock({ ...DEFAULT_BOOT_TOOL_NAMES, preResetHints: PI_PRE_RESET_HINTS }, request === 1 ? NAMELESS_AGENT : "boot-tester")), "the protocol follows the live named/nameless identity");
362
350
  if (request >= 3) {
363
351
  const boot = context.messages.find((message) => message.role === "user" && JSON.stringify(message.content).includes(WINDOW_IDENTITY_OPEN_TAG));
364
352
  assert.ok(JSON.stringify(boot).includes("Agent name: boot-tester (brain: boot-split-model)"));
@@ -445,22 +433,21 @@ test("real AgentSession: aborted early guidance retries silently", async () => {
445
433
  });
446
434
  try {
447
435
  const guidance = () => fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === GUIDANCE_TYPE);
448
- const notices = () => fixture.budgetNotices();
449
436
  await fixture.session.prompt("Establish usage below the reminder line.");
450
437
  await fixture.session.waitForIdle();
451
438
  assert.equal(guidance().length, 0);
452
439
  await fixture.session.prompt("Abort this low-budget request.");
453
440
  await fixture.session.waitForIdle();
454
441
  assert.equal(guidance().length, 0, "an aborted turn does not commit early guidance");
455
- assert.equal(notices(), 0, "early guidance never notifies");
442
+ assert.equal(fixture.notices.length, 0, "early guidance never notifies");
456
443
  await fixture.session.prompt("Retry successfully.");
457
444
  await fixture.session.waitForIdle();
458
445
  assert.equal(guidance().length, 1, "the successful retry commits the model guidance");
459
- assert.equal(notices(), 0, "committed early guidance stays UI-silent");
446
+ assert.equal(fixture.notices.length, 0, "committed early guidance stays UI-silent");
460
447
  await fixture.session.prompt("Continue in the same window.");
461
448
  await fixture.session.waitForIdle();
462
449
  assert.equal(guidance().length, 1);
463
- assert.equal(notices(), 0, "later turns cannot toast the early reminder");
450
+ assert.equal(fixture.notices.length, 0, "later turns cannot toast the early reminder");
464
451
  }
465
452
  finally {
466
453
  fixture.close();
@@ -523,25 +510,23 @@ test("real AgentSession: a final warning notifies before the response, even if a
523
510
  if (request === 2)
524
511
  return assistant(fixture, [{ type: "toolCall", id: "abort-budget-probe-2", name: "get_context_remaining", arguments: {} }], "toolUse", { usage: usage(60_000) });
525
512
  assert.ok(text(context).includes(WARNING_JSON), "the final warning reaches the model on both attempts");
526
- assert.equal(fixture.budgetNotices(), 1, "the UI is notified before the model responds, once across retries");
513
+ assert.equal(fixture.notices.length, 1, "the UI is notified before the model responds, once across retries");
527
514
  return assistant(fixture, [{ type: "text", text: `response ${request}` }], request === 3 ? "aborted" : "stop", { usage: usage(60_000) });
528
515
  },
529
516
  });
530
517
  try {
531
518
  const warnings = () => fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === WARNING_TYPE);
532
- const notices = () => fixture.budgetNotices();
533
519
  await fixture.session.prompt("Establish usage and reach the final runway.");
534
520
  await fixture.session.waitForIdle();
535
521
  assert.equal(fixture.requests.length, 3, "budget probes reach one final-warning attempt");
536
522
  assert.equal(warnings().length, 0, "the aborted attempt leaves no durable warning");
537
- assert.equal(notices(), 1, "the aborted request already notified at injection");
523
+ assert.equal(fixture.notices.length, 1, "the aborted request already notified at injection");
538
524
  await fixture.session.prompt("Retry successfully.");
539
525
  await fixture.session.waitForIdle();
540
526
  assert.equal(warnings().length, 1, "the successful retry commits one hidden warning");
541
527
  assert.equal(resetMarkers(fixture).length, 0, "committing the warning does not authorize a reset at normal stop");
542
528
  assert.equal(fixture.requests.length, 4, "the retry settles without a fresh-window continuation");
543
- assert.equal(notices(), 1, "committing the retry does not repeat the notification");
544
- assert.equal(fixture.notices.some((notice) => notice.includes("Context running low")), false, "early guidance remains UI-silent");
529
+ assert.equal(fixture.notices.length, 1, "committing the retry does not repeat the notification");
545
530
  }
546
531
  finally {
547
532
  fixture.close();
@@ -558,7 +543,7 @@ test("real AgentSession: final warning survives its reset boundary and notifies
558
543
  return assistant(fixture, [{ type: "toolCall", id: "final-budget-probe-2", name: "get_context_remaining", arguments: {} }], "toolUse", { usage: usage(60_000) });
559
544
  if (request === 3) {
560
545
  assert.ok(text(context).includes(WARNING_JSON), "the final warning reaches the model");
561
- assert.equal(fixture.budgetNotices(), 1, "warning notifies before the wipe tool runs");
546
+ assert.equal(fixture.notices.length, 1, "warning notifies before the wipe tool runs");
562
547
  return assistant(fixture, [{ type: "toolCall", id: "final-budget-wipe", name: "empty_brain", arguments: {} }], "toolUse", { usage: usage(60_000) });
563
548
  }
564
549
  return assistant(fixture, [{ type: "text", text: "fresh window ready" }]);
@@ -572,13 +557,10 @@ test("real AgentSession: final warning survives its reset boundary and notifies
572
557
  assertFreshRequest(fixture, 3, "FINAL_WARNING_RESET_SENTINEL");
573
558
  assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === WARNING_TYPE).length, 1);
574
559
  assert.equal(resetMarkers(fixture).length, 1, "the reset commits in the same boundary as the final warning");
575
- assert.equal(fixture.budgetNotices(), 1, "the old-window committed warning reaches the UI after reset");
576
- assert.equal(fixture.notices.filter(isResetSuccessNotice).length, 0, "normal reset completion stays silent");
577
- assert.equal(fixture.notices.some((notice) => notice.includes("Context running low")), false, "early guidance stays silent");
560
+ assert.equal(fixture.notices.length, 1, "the old-window committed warning reaches the UI after reset");
578
561
  await fixture.session.prompt("Continue after reset.");
579
562
  await fixture.session.waitForIdle();
580
- assert.equal(fixture.budgetNotices(), 1, "later turns cannot repeat the consumed final warning");
581
- assert.equal(fixture.notices.filter(isResetSuccessNotice).length, 0, "later turns do not announce normal reset completion");
563
+ assert.equal(fixture.notices.length, 1, "later turns cannot repeat the consumed final warning");
582
564
  }
583
565
  finally {
584
566
  fixture.close();
@@ -598,7 +580,6 @@ test("real AgentSession: explicit tiny-session wipe ignores keepRecentTokens and
598
580
  assert.equal(fixture.notices.length, 0, "startup boot is silent");
599
581
  await fixture.session.prompt("OLD_CONTEXT_SENTINEL: retain this only in durable history.");
600
582
  await fixture.session.waitForIdle();
601
- assert.deepEqual(fixture.notices.filter(isResetSuccessNotice), [], "normal reset completion stays silent");
602
583
  assert.equal(fixture.requests.length, 2, "the tool starts exactly one continuation");
603
584
  assert.ok(text(fixture.requests[0]).includes("OLD_CONTEXT_SENTINEL"));
604
585
  assertFreshRequest(fixture, 1, "OLD_CONTEXT_SENTINEL");
@@ -747,7 +728,6 @@ test("real AgentSession: /empty text is close-out context and stops after reset"
747
728
  const branch = fixture.sessionManager.getBranch();
748
729
  assert.equal(branch.some((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE), false);
749
730
  assert.equal(JSON.stringify(fixture.sessionManager.buildSessionProjection().messages).includes("AFTER_CLEAR_PROMPT_SENTINEL"), false);
750
- assert.equal(fixture.notices.some(isResetSuccessNotice), false);
751
731
  }
752
732
  finally {
753
733
  fixture.close();
@@ -808,7 +788,6 @@ test("real AgentSession: streaming clear prompt keeps the first request", async
808
788
  assert.equal(fixture.requests.length, 2);
809
789
  assert.equal(fixture.sessionManager.getBranch().some((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE), false);
810
790
  assert.equal(resetMarkers(fixture).length, 1);
811
- assert.ok(fixture.notices.some((notice) => notice.includes("Brain already being emptied")));
812
791
  }
813
792
  finally {
814
793
  release();
@@ -880,7 +859,6 @@ test("real AgentSession: manual hard-reserve reset stops clean and mixed-tool tu
880
859
  assert.equal(fixture.requests.length, 2);
881
860
  assert.equal(resetMarkers(fixture).length, 1, "the safety wipe is not repeated at settlement");
882
861
  assert.equal(JSON.stringify(fixture.sessionManager.buildSessionProjection().messages).includes("HARD_RESERVE_OLD_SENTINEL"), false);
883
- assert.equal(fixture.notices.some(isResetSuccessNotice), !mixed, "only forced reset completion notifies");
884
862
  if (mixed) {
885
863
  assert.ok(existsSync(join(fixture.notesRoot, "pi", "session", fixture.sessionManager.getSessionId(), "pressure.md")), "the whole tool batch completes before the cut");
886
864
  assert.equal(fixture.streamSignals.at(-1), true, "Pi's unavoidable tool follow-up is cancelled before provider work");
@@ -917,7 +895,6 @@ test("real AgentSession: overflowing /empty close-out forces a reset and stops",
917
895
  assert.equal(resetMarkers(fixture).length, 1);
918
896
  assert.equal(fixture.sessionManager.getBranch().some((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE), false);
919
897
  assert.equal(resetMarkers(fixture)[0].data.origin, "forced");
920
- assert.ok(fixture.notices.some(isResetSuccessNotice));
921
898
  }
922
899
  finally {
923
900
  fixture.close();
@@ -947,7 +924,6 @@ test("real AgentSession: streaming /empty steers a close-out and stops at settle
947
924
  await started;
948
925
  await fixture.session.prompt("/empty", { streamingBehavior: "steer" });
949
926
  await fixture.session.prompt("/empty", { streamingBehavior: "followUp" });
950
- assert.equal(fixture.notices.filter((notice) => notice.includes("Dumping Brain")).length, 1, "the user is notified once while output is ongoing");
951
927
  assert.equal(resetMarkers(fixture).length, 0, "the ongoing turn is not interrupted");
952
928
  releaseResponse();
953
929
  await running;
@@ -956,7 +932,6 @@ test("real AgentSession: streaming /empty steers a close-out and stops at settle
956
932
  assert.equal(fixture.requests.length, 2, "the warning closes out and the run stops — no continuation in the fresh window");
957
933
  assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === MANUAL_WIPE_TYPE).length, 1, "the busy warning is persisted once");
958
934
  assert.equal(JSON.stringify(fixture.sessionManager.buildSessionProjection().messages).includes("STREAMING_WIPE_OLD_SENTINEL"), false);
959
- assert.ok(fixture.notices.some(isResetSuccessNotice), "the committed boundary has a separate success notice");
960
935
  }
961
936
  finally {
962
937
  releaseResponse();
@@ -1021,7 +996,6 @@ test("real AgentSession: user abort, synthetic aborted response, and generic err
1021
996
  await fixture.session.waitForIdle();
1022
997
  assert.equal(resetMarkers(fixture).length, 0, `${mode} does not force a reset`);
1023
998
  assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "compaction").length, 0);
1024
- assert.equal(fixture.notices.some(isResetSuccessNotice), false);
1025
999
  if (mode === "ctx-abort")
1026
1000
  assert.equal(fixture.streamSignals.at(-1), true, "this case aborts the real Pi operation signal");
1027
1001
  else