notesoup 0.47.0 → 0.48.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 (78) hide show
  1. package/README.md +1 -1
  2. package/dist/src/boot/render.d.ts +14 -7
  3. package/dist/src/boot/render.js +29 -16
  4. package/dist/src/boot/text.d.ts +25 -4
  5. package/dist/src/boot/text.js +59 -11
  6. package/dist/src/budget/text.d.ts +29 -9
  7. package/dist/src/budget/text.js +51 -10
  8. package/dist/src/claude/helper.d.ts +2 -3
  9. package/dist/src/claude/helper.js +45 -11
  10. package/dist/src/claude/history.d.ts +9 -0
  11. package/dist/src/claude/history.js +271 -0
  12. package/dist/src/dsh/engine.d.ts +2 -1
  13. package/dist/src/dsh/engine.js +18 -9
  14. package/dist/src/dsh/index.js +9 -4
  15. package/dist/src/dsh/window.d.ts +2 -1
  16. package/dist/src/dsh/window.js +14 -8
  17. package/dist/src/history/query.js +59 -81
  18. package/dist/src/notes/address.d.ts +5 -0
  19. package/dist/src/notes/address.js +20 -21
  20. package/dist/src/notes/store.js +12 -19
  21. package/dist/src/pi/boot.d.ts +1 -1
  22. package/dist/src/pi/boot.js +28 -5
  23. package/dist/src/pi/budget.d.ts +0 -2
  24. package/dist/src/pi/budget.js +13 -53
  25. package/dist/src/pi/entries.d.ts +0 -1
  26. package/dist/src/pi/entries.js +0 -1
  27. package/dist/src/pi/history.d.ts +3 -0
  28. package/dist/src/pi/history.js +4 -0
  29. package/dist/src/pi/reset/artifacts.d.ts +7 -2
  30. package/dist/src/pi/reset/artifacts.js +16 -14
  31. package/dist/src/pi/reset/lifecycle.d.ts +21 -25
  32. package/dist/src/pi/reset/lifecycle.js +49 -73
  33. package/dist/src/pi/runtime.js +19 -18
  34. package/dist/src/pi/window.d.ts +12 -6
  35. package/dist/src/pi/window.js +7 -0
  36. package/dist/test/agent-loop.test.js +65 -42
  37. package/dist/test/boot.integration.test.js +119 -16
  38. package/dist/test/budget-settings.integration.test.js +4 -2
  39. package/dist/test/claude-history.test.d.ts +1 -0
  40. package/dist/test/claude-history.test.js +184 -0
  41. package/dist/test/claude-mod.test.js +243 -49
  42. package/dist/test/dsh.test.js +79 -2
  43. package/dist/test/helpers/extension.d.ts +3 -0
  44. package/dist/test/helpers/extension.js +33 -5
  45. package/dist/test/history.integration.test.js +66 -0
  46. package/dist/test/host-neutral.test.js +1 -1
  47. package/dist/test/model-facing-text.test.d.ts +1 -0
  48. package/dist/test/model-facing-text.test.js +181 -0
  49. package/dist/test/notes.integration.test.js +16 -18
  50. package/dist/test/reset-lifecycle.test.js +202 -47
  51. package/docs/architecture.md +3 -3
  52. package/docs/claude-code-mod.md +15 -3
  53. package/docs/dsh.md +1 -1
  54. package/docs/reset-lifecycle.md +32 -20
  55. package/docs/skills.md +1 -1
  56. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  57. package/mods/notesoup/dist/claude/helper.js +836 -92
  58. package/mods/notesoup/hooks/register.ts +154 -52
  59. package/package.json +1 -1
  60. package/src/boot/render.ts +41 -23
  61. package/src/boot/text.ts +68 -11
  62. package/src/budget/text.ts +61 -10
  63. package/src/claude/helper.ts +53 -22
  64. package/src/claude/history.ts +228 -0
  65. package/src/dsh/engine.ts +16 -9
  66. package/src/dsh/index.ts +8 -3
  67. package/src/dsh/window.ts +15 -9
  68. package/src/history/query.ts +57 -82
  69. package/src/notes/address.ts +19 -16
  70. package/src/notes/store.ts +9 -14
  71. package/src/pi/boot.ts +27 -5
  72. package/src/pi/budget.ts +13 -50
  73. package/src/pi/entries.ts +0 -1
  74. package/src/pi/history.ts +7 -2
  75. package/src/pi/reset/artifacts.ts +17 -14
  76. package/src/pi/reset/lifecycle.ts +57 -80
  77. package/src/pi/runtime.ts +19 -18
  78. package/src/pi/window.ts +11 -1
@@ -4,7 +4,7 @@ import { failure, success } from "../tools/result.js";
4
4
  import { prefixFit, TOOL_OUTPUT_LIMIT } from "../tools/output.js";
5
5
  import { earliestMatchOffsetChars } from "../text-match.js";
6
6
  import { InvalidQueryError, searchQueries } from "../tools/schema.js";
7
- import { allItems, eventDocument, filteredItems, inSelection, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS } from "./history.js";
7
+ import { eventDocument, filteredItems, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS } from "./history.js";
8
8
  /** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
9
9
  const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
10
10
  /** Epoch ms for one optional time param, or a refusal naming it. */
@@ -59,20 +59,12 @@ function truncateHistoryItem(item, fits) {
59
59
  const { tool: _dropped, ...withoutName } = item;
60
60
  return fits(withoutName) ? withoutName : shrinkContent(withoutName);
61
61
  }
62
- function isFoldableEvent(event) {
63
- return event.role === "tool" || event.role === "context";
64
- }
65
- /** Only a call without roles or query folds tool/context runs. */
66
- function foldsRuns(params) {
67
- return !params.roles && params.query === undefined;
68
- }
69
- /** Folded counts stay exact even when some distinct tool names must be omitted. */
70
- function foldedRuns(events) {
62
+ /** Summarize one already ordered gap; omitted tool names never change its exact count. */
63
+ function foldedRun(events) {
71
64
  if (events.length === 0)
72
- return [];
73
- const sorted = [...events].sort((a, b) => a.seq - b.seq);
65
+ return undefined;
74
66
  const counts = new Map();
75
- for (const event of sorted) {
67
+ for (const event of events) {
76
68
  if (event.role !== "tool")
77
69
  continue;
78
70
  const name = event.execution?.name ?? "unknown";
@@ -81,64 +73,45 @@ function foldedRuns(events) {
81
73
  const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
82
74
  // fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
83
75
  const tools = Object.fromEntries(entries);
84
- return [{ folded: true, first_seq: sorted[0].seq, last_seq: sorted.at(-1).seq, count: sorted.length, tools }];
76
+ return { folded: true, first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
85
77
  }
86
- /** A cursor exists only when the same selection still has a visible event past that end. */
87
- function pageCursors(vis, selected, beforeSeq, afterSeq) {
88
- if (selected.length === 0)
89
- return { page_older: null, page_newer: null };
90
- const lower = afterSeq ?? 0;
91
- const upper = beforeSeq ?? Number.POSITIVE_INFINITY;
92
- // Selected events are in seq order.
93
- const first = selected[0].seq;
94
- const last = selected.at(-1).seq;
95
- return {
96
- page_older: vis.some((event) => event.seq > lower && event.seq < first) ? { before_seq: first } : null,
97
- page_newer: vis.some((event) => event.seq > last && event.seq < upper) ? { after_seq: last, from: "oldest" } : null,
98
- };
99
- }
100
- function foldRows(projection, params, selected, cursors) {
101
- if (selected.length === 0) {
102
- // Even a range with no conversation can contain tool/context events.
103
- return foldedRuns(allItems(projection).filter((event) => inSelection(event, params) && isFoldableEvent(event)));
104
- }
105
- const windowEvents = allItems(projection).filter((event) => inSelection(event, params)).sort((a, b) => a.seq - b.seq);
106
- const folded = [];
107
- const firstSeq = selected[0].seq;
108
- const lastSeq = selected.at(-1).seq;
109
- if (cursors.page_older === null)
110
- folded.push(...foldedRuns(windowEvents.filter((event) => event.seq < firstSeq && isFoldableEvent(event))));
111
- // pageData already ordered selected by seq.
112
- for (let i = 0; i + 1 < selected.length; i++) {
113
- const left = selected[i].seq;
114
- const right = selected[i + 1].seq;
115
- folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > left && event.seq < right && isFoldableEvent(event))));
78
+ /** Filter and order once. Conversation candidates own the folded gap immediately before them. */
79
+ function prepareSelection(projection, params) {
80
+ const folds = !params.roles && params.query === undefined;
81
+ const candidates = [];
82
+ let run = [];
83
+ for (const event of filteredItems(projection, params, false)) {
84
+ if (folds && (event.role === "tool" || event.role === "context")) {
85
+ run.push(event);
86
+ continue;
87
+ }
88
+ if (folds && eventDocument(event) === "")
89
+ continue;
90
+ const matchOffset = params.query === undefined ? undefined : earliestMatchOffsetChars(eventDocument(event), params.query);
91
+ if (matchOffset !== undefined && matchOffset < 0)
92
+ continue;
93
+ candidates.push({ event, matchOffset, before: foldedRun(run) });
94
+ run = [];
116
95
  }
117
- if (cursors.page_newer === null)
118
- folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > lastSeq && isFoldableEvent(event))));
119
- return folded;
96
+ return { candidates, tail: foldedRun(run) };
120
97
  }
121
- function pageData(projection, params, vis, selected, maxChars, folds) {
122
- const orderedSelected = [...selected].sort((a, b) => a.event.seq - b.event.seq);
123
- const selectedEvents = orderedSelected.map((candidate) => candidate.event);
124
- const cursors = pageCursors(vis, selectedEvents, params.before_seq, params.after_seq);
125
- const visible = orderedSelected.map((candidate) => candidate.preview ?? visibleItem(candidate.event, maxChars, candidate.matchOffset));
126
- let rows = visible;
127
- if (folds) {
128
- const folded = foldRows(projection, params, selectedEvents, cursors);
129
- rows = [...visible, ...folded].sort((a, b) => ("folded" in a ? a.first_seq : a.seq) - ("folded" in b ? b.first_seq : b.seq));
98
+ /** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
99
+ function pageData(prepared, start, end, maxChars, preview) {
100
+ const { candidates, tail } = prepared;
101
+ const items = [];
102
+ for (let index = start; index < end; index++) {
103
+ const candidate = candidates[index];
104
+ if (candidate.before && (index > start || start === 0))
105
+ items.push(candidate.before);
106
+ items.push(preview ?? (candidate.preview ??= visibleItem(candidate.event, maxChars, candidate.matchOffset)));
130
107
  }
131
- return { items: rows, ...cursors };
132
- }
133
- /** Filter, then keep only literal matches when a normalized query is present. */
134
- function selectionCandidates(projection, params) {
135
- const events = filteredItems(projection, params, params.query === undefined);
136
- if (params.query === undefined)
137
- return events.map((event) => ({ event }));
138
- const needles = params.query;
139
- return events
140
- .map((event) => ({ event, matchOffset: earliestMatchOffsetChars(eventDocument(event), needles) }))
141
- .filter((candidate) => candidate.matchOffset >= 0);
108
+ if (end === candidates.length && tail)
109
+ items.push(tail);
110
+ return {
111
+ items,
112
+ page_older: start > 0 && start < end ? { before_seq: candidates[start].event.seq } : null,
113
+ page_newer: end < candidates.length && start < end ? { after_seq: candidates[end - 1].event.seq, from: "oldest" } : null,
114
+ };
142
115
  }
143
116
  /**
144
117
  * Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
@@ -158,25 +131,30 @@ export function selectPage(projection, params, fits, maxChars) {
158
131
  throw error;
159
132
  }
160
133
  const scoped = { ...params, ...bounds.data, query: queries.length ? queries : undefined };
161
- const vis = selectionCandidates(projection, scoped);
162
- // Take the limit from the end `from` names, so a budget for one row keeps the most important one.
163
- // At least one: `slice(-0)` would otherwise return the whole selection.
134
+ const prepared = prepareSelection(projection, scoped);
135
+ const { candidates } = prepared;
136
+ // Grow a contiguous interval from the requested end; even a byte-limited newest page stays ascending.
137
+ const newest = scoped.from !== "oldest";
138
+ let start = newest ? candidates.length : 0;
139
+ let end = start;
164
140
  const limit = Math.max(1, scoped.limit ?? 20);
165
- const folds = foldsRuns(scoped);
166
- const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
167
- const ordered = scoped.from === "oldest" ? ascending.slice(0, limit) : ascending.slice(-limit).reverse();
168
- const allVisible = vis.map((candidate) => candidate.event).sort((a, b) => a.seq - b.seq);
169
- const kept = [];
170
- for (const candidate of ordered) {
171
- if (fits(pageData(projection, scoped, allVisible, [...kept, candidate], maxChars, folds))) {
172
- kept.push(candidate);
141
+ for (let count = 0; count < limit && (newest ? start > 0 : end < candidates.length); count++) {
142
+ const nextStart = newest ? start - 1 : start;
143
+ const nextEnd = newest ? end : end + 1;
144
+ if (fits(pageData(prepared, nextStart, nextEnd, maxChars))) {
145
+ start = nextStart;
146
+ end = nextEnd;
173
147
  continue;
174
148
  }
175
- if (kept.length === 0)
176
- kept.push({ ...candidate, preview: truncateHistoryItem(visibleItem(candidate.event, maxChars, candidate.matchOffset), (preview) => fits(pageData(projection, scoped, allVisible, [{ ...candidate, preview }], maxChars, folds))) });
149
+ if (start === end) {
150
+ start = nextStart;
151
+ end = nextEnd;
152
+ const candidate = candidates[start];
153
+ candidate.preview = truncateHistoryItem(candidate.preview, (preview) => fits(pageData(prepared, start, end, maxChars, preview)));
154
+ }
177
155
  break;
178
156
  }
179
- const page = pageData(projection, scoped, allVisible, kept, maxChars, folds);
157
+ const page = pageData(prepared, start, end, maxChars);
180
158
  if (!fits(page)) {
181
159
  return failure("page_too_large", `Even trimmed to their shortest, these ${page.items.length} rows and their folded runs fill the ${TOOL_OUTPUT_LIMIT} a call can carry; narrow with \`before_seq\`/\`after_seq\` or \`since\`/\`until\`, pass \`roles\` to skip folding, or \`history_read\` one seq.`);
182
160
  }
@@ -6,6 +6,11 @@ export type NoteAddress = {
6
6
  who?: string;
7
7
  };
8
8
  export declare const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path> reads a named project home.";
9
+ /** The one home-head vocabulary: the scope each public `@head` names, and the home directory family a head with `home` lists. */
10
+ export declare const HOME_HEADS: ReadonlyMap<string, {
11
+ readonly scope: Scope;
12
+ readonly home?: "project" | "agents" | "models";
13
+ }>;
9
14
  /**
10
15
  * Minimal glob over virtual note paths: `*` matches any run within a segment (never
11
16
  * `/`), `**` matches any run across segments (a leading double-star followed by a
@@ -1,6 +1,16 @@
1
1
  import { NoteError, shown } from "./errors.js";
2
2
  import { assertVirtualPath, SLUG_PATTERN } from "./paths.js";
3
3
  export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path> reads a named project home.";
4
+ /** The one home-head vocabulary: the scope each public `@head` names, and the home directory family a head with `home` lists. */
5
+ export const HOME_HEADS = new Map([
6
+ ["project", { scope: "project" }],
7
+ ["human", { scope: "human" }],
8
+ ["self", { scope: "agent" }],
9
+ ["model", { scope: "model" }],
10
+ ["projects", { scope: "project", home: "project" }],
11
+ ["agents", { scope: "agent", home: "agents" }],
12
+ ["models", { scope: "model", home: "models" }],
13
+ ]);
4
14
  /**
5
15
  * Minimal glob over virtual note paths: `*` matches any run within a segment (never
6
16
  * `/`), `**` matches any run across segments (a leading double-star followed by a
@@ -52,29 +62,18 @@ export function assertAddress(value) {
52
62
  let path = value;
53
63
  let who;
54
64
  if (value.startsWith("@")) {
55
- const rest = value.slice(1);
56
- const headEnd = rest.indexOf("/");
57
- const head = headEnd === -1 ? rest : rest.slice(0, headEnd);
58
- const tail = headEnd === -1 ? "" : rest.slice(headEnd + 1);
59
- path = tail;
60
- if (head === "project")
61
- scope = "project";
62
- else if (head === "human")
63
- scope = "human";
64
- else if (head === "self")
65
- scope = "agent";
66
- else if (head === "model")
67
- scope = "model";
68
- else if (head === "projects" || head === "agents" || head === "models") {
69
- const nameEnd = tail.indexOf("/");
70
- who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
65
+ const [rawHead, ...tail] = value.slice(1).split("/");
66
+ const head = HOME_HEADS.get(rawHead);
67
+ if (head === undefined)
68
+ throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
69
+ scope = head.scope;
70
+ if (head.home === undefined)
71
+ path = tail.join("/");
72
+ else {
73
+ who = tail[0] ?? "";
71
74
  if (!SLUG_PATTERN.test(who))
72
75
  throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
73
- scope = head === "projects" ? "project" : head === "agents" ? "agent" : "model";
74
- path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
75
- }
76
- else {
77
- throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
76
+ path = tail.slice(1).join("/");
78
77
  }
79
78
  if (path === "" && scope !== "agent" && scope !== "model")
80
79
  throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { earliestMatchOffsetChars } from "../text-match.js";
5
- import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp } from "./address.js";
5
+ import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp, HOME_HEADS } from "./address.js";
6
6
  import { isFilesystemError } from "./fs-error.js";
7
7
  import { snapshotNotesIdentity } from "./identity.js";
8
8
  import { NoteError } from "./errors.js";
@@ -79,24 +79,17 @@ async function walkMarkdown(dir, base = dir) {
79
79
  async function homesForPattern(pattern, identity) {
80
80
  if (!pattern || !pattern.startsWith("@"))
81
81
  return undefined;
82
- const head = /^@([^/]+)\//.exec(pattern)?.[1];
83
- if (head === "project")
84
- return [{ scope: "project" }];
85
- if (head === "human")
86
- return [{ scope: "human" }];
87
- if (head === "self")
88
- return [{ scope: "agent" }];
89
- if (head === "model")
90
- return [{ scope: "model" }];
91
- if (head === "projects" || head === "agents" || head === "models") {
92
- const scope = head === "projects" ? "project" : head === "agents" ? "agent" : "model";
93
- const name = pattern.slice(head.length + 2).split("/")[0] ?? "";
94
- if (name.length > 0 && !/[*?]/.test(name))
95
- return [{ scope, who: assertWho(name) }];
96
- const names = head === "projects" ? projectHomes(identity.home).map(home => home.name) : await namespaceSlugs(head, identity.home);
97
- return names.map((who) => ({ scope, who }));
98
- }
99
- return [];
82
+ const [rawHead, ...tail] = pattern.split("/");
83
+ const head = tail.length === 0 ? undefined : HOME_HEADS.get(rawHead.slice(1)); // a bare "@projects" names no homes
84
+ if (head === undefined)
85
+ return [];
86
+ if (head.home === undefined)
87
+ return [{ scope: head.scope }];
88
+ const name = tail[0];
89
+ if (name !== undefined && name.length > 0 && !/[*?]/.test(name))
90
+ return [{ scope: head.scope, who: assertWho(name) }];
91
+ const names = head.home === "project" ? projectHomes(identity.home).map(home => home.name) : await namespaceSlugs(head.home, identity.home);
92
+ return names.map((who) => ({ scope: head.scope, who }));
100
93
  }
101
94
  /** Relative pattern heads resolve to canonical names, so they match canonical addresses. */
102
95
  function normalizePattern(pattern, identity) {
@@ -14,6 +14,6 @@ export type BootMessage = {
14
14
  * Acquire one notes snapshot and build the boot custom message for a window. All identity
15
15
  * fields are captured synchronously before the first filesystem await.
16
16
  */
17
- export declare function buildBootMessage(ctx: ExtensionContext, windowId: string, previousId: string | undefined, notifyIncompleteNotes?: IncompleteNotesNotifier, isCurrent?: () => boolean): Promise<BootMessage>;
17
+ export declare function buildBootMessage(ctx: ExtensionContext, windowId: string, firstSeq: number | undefined, notifyIncompleteNotes?: IncompleteNotesNotifier, isCurrent?: () => boolean): Promise<BootMessage>;
18
18
  /** Persist one hidden boot message without triggering a model turn. */
19
19
  export declare function sendBoot(pi: ExtensionAPI, boot: BootMessage): void;
@@ -1,18 +1,41 @@
1
- import { DEFAULT_BOOT_TOOL_NAMES } from "../boot/text.js";
1
+ import { DEFAULT_BOOT_TOOL_NAMES, PI_PRE_RESET_HINTS } from "../boot/text.js";
2
2
  import { agentSlug, modelSlug, notesIdentityFromPi } from "./notes/adapter.js";
3
3
  import { loadNotesSnapshot, unavailableNotesSnapshot } from "../boot/snapshot.js";
4
4
  import { isFilesystemError } from "../notes/index.js";
5
5
  import { BOOT_TYPE } from "./entries.js";
6
6
  import { renderBootBlock } from "../boot/render.js";
7
- import { rootWindowId } from "./window.js";
7
+ import { historyFromSession, nextHistorySeq } from "./history.js";
8
8
  /**
9
9
  * Acquire one notes snapshot and build the boot custom message for a window. All identity
10
10
  * fields are captured synchronously before the first filesystem await.
11
11
  */
12
- export async function buildBootMessage(ctx, windowId, previousId, notifyIncompleteNotes, isCurrent = () => true) {
12
+ export async function buildBootMessage(ctx, windowId, firstSeq, notifyIncompleteNotes, isCurrent = () => true) {
13
13
  const agentName = agentSlug();
14
14
  const modelName = modelSlug(ctx);
15
- const sessionId = ctx.sessionManager.getSessionId();
15
+ const windows = historyFromSession(ctx).windows.map((window) => {
16
+ const seqs = window.items.map((item) => item.seq);
17
+ return {
18
+ shortName: window.windowId.slice(window.windowId.lastIndexOf(":") + 1),
19
+ firstSeq: firstSeq === undefined || seqs.length === 0 ? undefined : Math.min(...seqs),
20
+ lastSeq: firstSeq === undefined || seqs.length === 0 ? undefined : Math.max(...seqs),
21
+ isCurrent: window.windowId === windowId,
22
+ };
23
+ });
24
+ if (firstSeq !== undefined) {
25
+ // An empty old window will consume the pending boundary before its marker is written.
26
+ const last = windows.at(-1);
27
+ last.firstSeq ??= last.isCurrent ? firstSeq : nextHistorySeq(ctx);
28
+ }
29
+ if (!windows.some((window) => window.isCurrent)) {
30
+ windows.push({ shortName: windowId.slice(windowId.lastIndexOf(":") + 1), firstSeq, lastSeq: undefined, isCurrent: true });
31
+ }
32
+ // A closing boundary includes folded result slots, pending warnings and the old checkpoint.
33
+ for (let index = 0; index < windows.length - 1; index++) {
34
+ const nextFirst = windows[index + 1].firstSeq;
35
+ if (nextFirst !== undefined)
36
+ windows[index].lastSeq = nextFirst - 1;
37
+ }
38
+ const tree = { trunk: windowId.slice(0, windowId.lastIndexOf(":")), windows };
16
39
  const openedAt = Date.now();
17
40
  let notes;
18
41
  try {
@@ -27,7 +50,7 @@ export async function buildBootMessage(ctx, windowId, previousId, notifyIncomple
27
50
  notifyIncompleteNotes?.(ctx, windowId, notes);
28
51
  return {
29
52
  customType: BOOT_TYPE,
30
- content: renderBootBlock({ agentName, modelName, firstWindowId: rootWindowId(sessionId), currentWindowId: windowId, previousWindowId: previousId, notes, tools: DEFAULT_BOOT_TOOL_NAMES }),
53
+ content: renderBootBlock({ agentName, modelName, tree, notes, tools: { ...DEFAULT_BOOT_TOOL_NAMES, preResetHints: PI_PRE_RESET_HINTS } }),
31
54
  display: false,
32
55
  details: { windowId },
33
56
  };
@@ -3,8 +3,6 @@ export declare function registerBudget(pi: ExtensionAPI, isEnabled: () => boolea
3
3
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
4
4
  hardReserveDue: (ctx: ExtensionContext) => boolean;
5
5
  consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
6
- /** The reset owner wires its close-out here once the lifecycle reducer exists. */
7
- setCloseOut: (handler: (windowId: string) => void) => void;
8
6
  /** The same close-out countdown the model sees, for user-facing status; null when usage is unknown. */
9
7
  statusFor: (ctx: ExtensionContext) => {
10
8
  remaining: number | null;
@@ -3,9 +3,9 @@ import { remainingBudget } from "../budget/policy.js";
3
3
  import { Type } from "@earendil-works/pi-ai";
4
4
  import { defineTool } from "@earendil-works/pi-coding-agent";
5
5
  import { GUIDANCE_TYPE, WARNING_TYPE } from "./entries.js";
6
- import { WARNING_CONTENT } from "../budget/text.js";
6
+ import { warningContent } from "../budget/text.js";
7
7
  import { readThresholdSettings } from "./thresholds.js";
8
- import { currentWindowId, hasWindowMessage, isWindowMarker, rootWindowId, windowUsage } from "./window.js";
8
+ import { currentWindowId, hasWindowMessage, windowUsage } from "./window.js";
9
9
  import { tokenBudgetGuidance } from "../budget/text.js";
10
10
  import { arrangeAnchoredReminders } from "./anchored.js";
11
11
  import { output } from "./tool-result.js";
@@ -17,9 +17,6 @@ function remainingTokens(ctx) {
17
17
  export function registerBudget(pi, isEnabled, settingsManager) {
18
18
  let cachedPolicy;
19
19
  const notifiedWarnings = new Set();
20
- // The reset owner is wired after both sides exist, so no handler can observe a
21
- // half-constructed pair (a close-out request cannot arrive before registration ends).
22
- let onCloseOut = () => { };
23
20
  const resolvePolicy = (ctx) => {
24
21
  if (!settingsManager && cachedPolicy)
25
22
  return { ...cachedPolicy, warnings: [] };
@@ -44,41 +41,14 @@ export function registerBudget(pi, isEnabled, settingsManager) {
44
41
  };
45
42
  let pendingGuidance;
46
43
  let pendingWarning;
47
- let pendingNotices = new Map();
48
- const noticeKey = (sessionId, windowId) => `${sessionId}:${windowId}`;
49
- const warningCommittedInWindow = (ctx, notice) => {
50
- if (ctx.sessionManager.getSessionId() !== notice.sessionId)
51
- return false;
52
- let windowId = rootWindowId(notice.sessionId);
53
- for (const entry of ctx.sessionManager.getBranch()) {
54
- if (isWindowMarker(entry)) {
55
- windowId = entry.data.windowId;
56
- continue;
57
- }
58
- if (windowId === notice.windowId && entry.type === "custom_message" && entry.customType === WARNING_TYPE)
59
- return true;
60
- }
61
- return false;
62
- };
63
- const notifyCommittedWarnings = (ctx, settled = false) => {
64
- for (const [key, notice] of pendingNotices) {
65
- if (warningCommittedInWindow(ctx, notice)) {
66
- pendingNotices.delete(key);
67
- ctx.ui.notify("🥣 Context almost full · saving notes before memory clears", "warning");
68
- }
69
- else if (settled) {
70
- // An uncommitted draft must not be matched to a later manual warning.
71
- pendingNotices.delete(key);
72
- }
73
- }
74
- };
44
+ const notifiedWindows = new Set();
75
45
  const clearStaged = () => {
76
46
  pendingGuidance = undefined;
77
47
  pendingWarning = undefined;
78
48
  };
79
49
  const resetForTransition = () => {
80
50
  clearStaged();
81
- pendingNotices.clear();
51
+ notifiedWindows.clear();
82
52
  cachedPolicy = undefined;
83
53
  notifiedWarnings.clear();
84
54
  };
@@ -90,10 +60,6 @@ export function registerBudget(pi, isEnabled, settingsManager) {
90
60
  clearStaged();
91
61
  const windowId = currentWindowId(ctx);
92
62
  const drafts = staged.filter((draft) => draft !== undefined && draft.windowId === windowId);
93
- if (drafts.some((draft) => draft.customType === WARNING_TYPE)) {
94
- const sessionId = ctx.sessionManager.getSessionId();
95
- pendingNotices.set(noticeKey(sessionId, windowId), { sessionId, windowId });
96
- }
97
63
  return drafts.map((draft) => ({
98
64
  type: "custom_message",
99
65
  customType: draft.customType,
@@ -106,14 +72,7 @@ export function registerBudget(pi, isEnabled, settingsManager) {
106
72
  pi.on("session_tree", resetForTransition);
107
73
  pi.on("model_select", resetForTransition);
108
74
  pi.on("session_shutdown", resetForTransition);
109
- // A warning can be committed at turn_end, before a tool turn or a reset changes the
110
- // active window. Observe the active branch at public lifecycle boundaries and match
111
- // the candidate against its originating window segment, not only the current window.
112
- pi.on("turn_start", (_event, ctx) => notifyCommittedWarnings(ctx));
113
- pi.on("agent_settled", (_event, ctx) => {
114
- notifyCommittedWarnings(ctx, true);
115
- clearStaged();
116
- });
75
+ pi.on("agent_settled", clearStaged);
117
76
  pi.on("context", (event, ctx) => {
118
77
  if (!isEnabled())
119
78
  return undefined;
@@ -135,16 +94,19 @@ export function registerBudget(pi, isEnabled, settingsManager) {
135
94
  const windowId = currentWindowId(ctx);
136
95
  const { reminder, warning } = thresholdsFor(ctx);
137
96
  if (remaining <= warning) {
138
- // Re-arm close-out on each eligible request. A prior request may have aborted
139
- // after persisting the warning, so warning deduplication must not own this state.
140
- onCloseOut(windowId);
141
97
  if (hasWindowMessage(ctx, WARNING_TYPE))
142
98
  return result();
143
99
  // The critical close-out starts at reserve + runway, not at the hard reserve.
144
100
  // Another request in the same turn re-sends the staged text instead of re-measuring.
145
101
  pendingGuidance = undefined;
146
102
  if (pendingWarning?.windowId !== windowId)
147
- pendingWarning = { windowId, content: WARNING_CONTENT };
103
+ pendingWarning = { windowId, content: warningContent() };
104
+ // Notify when injected, not after tools finish or a reset has already committed.
105
+ // An aborted request does not undo the low-budget condition or repeat the toast.
106
+ if (!notifiedWindows.has(windowId)) {
107
+ notifiedWindows.add(windowId);
108
+ ctx.ui.notify("🥣 Brain almost full · taking notes", "warning");
109
+ }
148
110
  return result({ customType: WARNING_TYPE, content: pendingWarning.content });
149
111
  }
150
112
  if (hasWindowMessage(ctx, WARNING_TYPE) || pendingWarning?.windowId === windowId)
@@ -174,10 +136,8 @@ export function registerBudget(pi, isEnabled, settingsManager) {
174
136
  automaticResetEnabled,
175
137
  hardReserveDue,
176
138
  consumeTurnEnd,
177
- /** The reset owner wires its close-out here once the lifecycle reducer exists. */
178
- setCloseOut: (handler) => { onCloseOut = handler; },
179
139
  /** The same close-out countdown the model sees, for user-facing status; null when usage is unknown. */
180
140
  statusFor: (ctx) => ({ remaining: remainingBudget(remainingTokens(ctx), thresholdsFor(ctx).warning) }),
181
- clear: () => { clearStaged(); pendingNotices.clear(); },
141
+ clear: () => { clearStaged(); notifiedWindows.clear(); },
182
142
  };
183
143
  }
@@ -4,5 +4,4 @@ export declare const WARNING_TYPE = "notesoup/warning";
4
4
  export declare const MANUAL_WIPE_TYPE = "notesoup/manual-wipe";
5
5
  export declare const RESET_MARKER_TYPE = "notesoup/reset-marker";
6
6
  export declare const CONTINUATION_TYPE = "notesoup/continuation";
7
- export declare const RESET_PROMPT_TYPE = "notesoup/reset-prompt";
8
7
  export declare const RESET_LAST_WORD_TYPE = "notesoup/reset-last-word";
@@ -4,5 +4,4 @@ export const WARNING_TYPE = "notesoup/warning";
4
4
  export const MANUAL_WIPE_TYPE = "notesoup/manual-wipe";
5
5
  export const RESET_MARKER_TYPE = "notesoup/reset-marker";
6
6
  export const CONTINUATION_TYPE = "notesoup/continuation";
7
- export const RESET_PROMPT_TYPE = "notesoup/reset-prompt";
8
7
  export const RESET_LAST_WORD_TYPE = "notesoup/reset-last-word";
@@ -1,4 +1,7 @@
1
+ import type { SessionBoundaryDraft } from "@earendil-works/pi-coding-agent";
1
2
  import type { SessionReader } from "./session-reader.js";
2
3
  import { type HistoryProjection } from "../history/history.js";
4
+ /** Pending boundary drafts use the same slots as persisted entries. */
5
+ export declare function nextHistorySeq(ctx: SessionReader, pending?: readonly SessionBoundaryDraft[]): number;
3
6
  /** Build stable internal addresses, then project the active branch into public events. */
4
7
  export declare function historyFromSession(ctx: SessionReader): HistoryProjection;
@@ -24,6 +24,10 @@ function sequenceCount(entry) {
24
24
  return 1;
25
25
  return 1 + entry.message.content.filter(isToolCall).length;
26
26
  }
27
+ /** Pending boundary drafts use the same slots as persisted entries. */
28
+ export function nextHistorySeq(ctx, pending = []) {
29
+ return 1 + [...ctx.sessionManager.getEntries(), ...pending].reduce((sum, entry) => sum + sequenceCount(entry), 0);
30
+ }
27
31
  function messageContent(message) {
28
32
  switch (message.role) {
29
33
  case "bashExecution":
@@ -1,4 +1,5 @@
1
1
  import type { ExtensionAPI, ExtensionContext, SessionBoundaryDraft, SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ import { type ResetOrigin } from "../../budget/text.js";
2
3
  import { type WindowMarker } from "../window.js";
3
4
  import { type IncompleteNotesNotifier } from "../boot.js";
4
5
  export type ResetTailState = {
@@ -15,9 +16,13 @@ export declare function sanitizeLastWord(raw: string | undefined): string | unde
15
16
  export declare function isWindowContinuationEntry(entry: SessionEntry): boolean;
16
17
  /**
17
18
  * The closed, ordered reset shape: retain-none native checkpoint, marker, matching boot,
18
- * continuation, then an optional parting line and command prompt. The boot snapshot is acquired asynchronously after capturing this identity.
19
+ * continuation, then an optional parting line. The prompt is not persisted here — it reached the
20
+ * closing window inside the warning. The boot snapshot is acquired asynchronously after capturing
21
+ * this identity. The continuation is drawn from the pool its origin names, here, once: the caller
22
+ * persists the returned text and no read, render, or repair draws it again. The origin defaults to
23
+ * `normal`, the same reading a legacy marker with no origin gets.
19
24
  */
20
- export declare function buildResetDrafts(ctx: ExtensionContext, notifyIncompleteNotes?: IncompleteNotesNotifier, isCurrent?: () => boolean, prompt?: string, lastWord?: string): Promise<SessionBoundaryDraft[]>;
25
+ export declare function buildResetDrafts(ctx: ExtensionContext, notifyIncompleteNotes?: IncompleteNotesNotifier, isCurrent?: () => boolean, lastWord?: string, firstSeq?: number, origin?: ResetOrigin): Promise<SessionBoundaryDraft[]>;
21
26
  /**
22
27
  * Inspect the persisted tail of a reset marker. It reports which reset messages are present
23
28
  * only while the tail stays repairable: metadata may follow the marker, but real conversation,