notesoup 0.47.1 → 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 +48 -72
  33. package/dist/src/pi/runtime.js +6 -6
  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 +52 -29
  37. package/dist/test/boot.integration.test.js +114 -11
  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 +236 -42
  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 +201 -46
  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 +140 -38
  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 +56 -79
  77. package/src/pi/runtime.ts +6 -6
  78. package/src/pi/window.ts +11 -1
package/src/dsh/window.ts CHANGED
@@ -7,7 +7,6 @@ import { createHash } from "node:crypto";
7
7
  import { loadNotesSnapshot } from "../boot/snapshot.js";
8
8
  import { renderBootBlock } from "../boot/render.js";
9
9
  import { DEFAULT_BOOT_TOOL_NAMES } from "../boot/text.js";
10
- import { CONTINUATION } from "../budget/text.js";
11
10
  import { contentText } from "../history/history.js";
12
11
  import { projectKey, slugify, snapshotNotesIdentity, type NotesIdentity } from "../notes/index.js";
13
12
 
@@ -17,7 +16,7 @@ const BOOT_OPEN = "<notesoup-boot>\n";
17
16
  const BOOT_CLOSE = "\n</notesoup-boot>";
18
17
  const CHECKPOINT_END = "\n\n<notesoup-continuation>\n";
19
18
  export type WindowSnapshot = Readonly<{ version: 1; window: number; windowId: string; openedAt: number; boot: string; notesDigest: string }>;
20
- export type WindowState = { snapshot: WindowSnapshot; pendingReset: boolean; warned: boolean; reminded: boolean };
19
+ export type WindowState = { snapshot: WindowSnapshot; pendingReset: boolean; warned: boolean; reminded: boolean; continuation?: string };
21
20
  export type NotesConfig = { notesHome?: string; agentName?: string };
22
21
 
23
22
  export function restoreWarnings(state: WindowState, events: readonly SessionEvent[]): void {
@@ -37,7 +36,7 @@ declare module "@deepseek-ai/dsh-session/types" {
37
36
 
38
37
  export function windowId(sessionId: string, window: number): string { return `dsh:${sessionId}:${window}`; }
39
38
  function digest(boot: string): string { return createHash("sha256").update(boot).digest("hex"); }
40
- export function checkpointText(snapshot: WindowSnapshot): string { return snapshot.boot + CHECKPOINT_END + CONTINUATION + "\n</notesoup-continuation>"; }
39
+ export function checkpointText(snapshot: WindowSnapshot, continuation: string): string { return snapshot.boot + CHECKPOINT_END + continuation + "\n</notesoup-continuation>"; }
41
40
 
42
41
  export function recordSnapshot(event: SessionEvent): WindowSnapshot | undefined {
43
42
  const record = pluginRecordOf(event);
@@ -65,10 +64,17 @@ function systemSnapshot(event: SessionEvent): WindowSnapshot | undefined {
65
64
  return snapshotFromBoot(text.slice(start, end + BOOT_CLOSE.length), event.time);
66
65
  }
67
66
 
67
+ /**
68
+ * Read the window identity out of a persisted boot. The `context_window` spelling is what boots
69
+ * written before the rename carry, so both spellings still yield their ordinal and window id.
70
+ */
68
71
  function snapshotFromBoot(boot: string, openedAt: number): WindowSnapshot | undefined {
69
- const id = /^Current context window id: (dsh:.*:(\d+))$/m.exec(boot);
70
- if (!id || !Number.isSafeInteger(Number(id[2]))) return undefined;
71
- return Object.freeze({ version: 1, window: Number(id[2]), windowId: id[1]!, openedAt, boot, notesDigest: digest(boot) });
72
+ const identity = /<(?:context_window|notesoup:window_identity)>\n[\s\S]*?\n(dsh:[^\n]+)\n[\s\S]*?└─ (\d+)(?: +[^\n]*)?\n<\/(?:context_window|notesoup:window_identity)>/.exec(boot);
73
+ const legacy = /^Current context window id: (dsh:.*:(\d+))$/m.exec(boot);
74
+ const shortName = identity?.[2] ?? legacy?.[2];
75
+ const id = identity ? `${identity[1]}:${shortName}` : legacy?.[1];
76
+ if (!id || shortName === undefined || !Number.isSafeInteger(Number(shortName))) return undefined;
77
+ return Object.freeze({ version: 1, window: Number(shortName), windowId: id, openedAt, boot, notesDigest: digest(boot) });
72
78
  }
73
79
 
74
80
  export function recoverSnapshot(events: readonly SessionEvent[]): WindowSnapshot | undefined {
@@ -116,9 +122,9 @@ export class Windows {
116
122
  async mint(agent: Pick<Agent, "session" | "options">, window: number, openedAt: number): Promise<WindowSnapshot> {
117
123
  const identity = notesIdentity(agent, this.config);
118
124
  const notes = await loadNotesSnapshot(identity, openedAt);
119
- const previous = this.states.get(agent.session)?.snapshot;
120
- const firstWindowId = previous?.boot.match(/^First context window id: (.+)$/m)?.[1] ?? windowId(agent.session.id, 0);
121
- const boot = BOOT_OPEN + renderBootBlock({ agentName: identity.agent, modelName: identity.model, firstWindowId, currentWindowId: windowId(agent.session.id, window), ...(window ? { previousWindowId: previous?.windowId ?? windowId(agent.session.id, window - 1) } : {}), notes, tools: DEFAULT_BOOT_TOOL_NAMES }) + BOOT_CLOSE;
125
+ const trunk = `dsh:${agent.session.id}`;
126
+ const tree = { trunk, windows: Array.from({ length: window + 1 }, (_, index) => ({ shortName: String(index), isCurrent: index === window })) };
127
+ const boot = BOOT_OPEN + renderBootBlock({ agentName: identity.agent, modelName: identity.model, tree, notes, tools: DEFAULT_BOOT_TOOL_NAMES }) + BOOT_CLOSE;
122
128
  return Object.freeze({ version: 1, window, windowId: windowId(agent.session.id, window), openedAt, boot, notesDigest: digest(boot) });
123
129
  }
124
130
  }
@@ -4,10 +4,10 @@ import { failure, success, type Outcome } 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, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
7
+ import { eventDocument, filteredItems, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
8
8
 
9
- type PageRow = HistoryPageItem | HistoryFoldedRow;
10
- type Candidate = { event: HistoryEvent; matchOffset?: number; preview?: HistoryPageItem };
9
+ type Candidate = { event: HistoryEvent; matchOffset?: number; preview?: HistoryPageItem; before?: HistoryFoldedRow };
10
+ type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow };
11
11
 
12
12
  /** Which end of one selection `limit` is taken from; page items always come back ascending. */
13
13
  export type HistoryOrder = "newest" | "oldest";
@@ -83,21 +83,11 @@ function truncateHistoryItem(item: HistoryPageItem, fits: (candidate: HistoryPag
83
83
  return fits(withoutName) ? withoutName : shrinkContent(withoutName);
84
84
  }
85
85
 
86
- function isFoldableEvent(event: HistoryEvent): boolean {
87
- return event.role === "tool" || event.role === "context";
88
- }
89
-
90
- /** Only a call without roles or query folds tool/context runs. */
91
- function foldsRuns(params: HistorySelection): boolean {
92
- return !params.roles && params.query === undefined;
93
- }
94
-
95
- /** Folded counts stay exact even when some distinct tool names must be omitted. */
96
- function foldedRuns(events: HistoryEvent[]): HistoryFoldedRow[] {
97
- if (events.length === 0) return [];
98
- const sorted = [...events].sort((a, b) => a.seq - b.seq);
86
+ /** Summarize one already ordered gap; omitted tool names never change its exact count. */
87
+ function foldedRun(events: HistoryEvent[]): HistoryFoldedRow | undefined {
88
+ if (events.length === 0) return undefined;
99
89
  const counts = new Map<string, number>();
100
- for (const event of sorted) {
90
+ for (const event of events) {
101
91
  if (event.role !== "tool") continue;
102
92
  const name = event.execution?.name ?? "unknown";
103
93
  counts.set(name, (counts.get(name) ?? 0) + 1);
@@ -105,64 +95,43 @@ function foldedRuns(events: HistoryEvent[]): HistoryFoldedRow[] {
105
95
  const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
106
96
  // fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
107
97
  const tools = Object.fromEntries(entries);
108
- return [{ folded: true, first_seq: sorted[0]!.seq, last_seq: sorted.at(-1)!.seq, count: sorted.length, tools }];
109
- }
110
-
111
- /** A cursor exists only when the same selection still has a visible event past that end. */
112
- function pageCursors(vis: HistoryEvent[], selected: HistoryEvent[], beforeSeq: number | undefined, afterSeq: number | undefined): Pick<HistoryPage, "page_older" | "page_newer"> {
113
- if (selected.length === 0) return { page_older: null, page_newer: null };
114
- const lower = afterSeq ?? 0;
115
- const upper = beforeSeq ?? Number.POSITIVE_INFINITY;
116
- // Selected events are in seq order.
117
- const first = selected[0]!.seq;
118
- const last = selected.at(-1)!.seq;
119
- return {
120
- page_older: vis.some((event) => event.seq > lower && event.seq < first) ? { before_seq: first } : null,
121
- page_newer: vis.some((event) => event.seq > last && event.seq < upper) ? { after_seq: last, from: "oldest" } : null,
122
- };
98
+ return { folded: true, first_seq: events[0]!.seq, last_seq: events.at(-1)!.seq, count: events.length, tools };
123
99
  }
124
100
 
125
- function foldRows(projection: HistoryProjection, params: HistorySelection, selected: HistoryEvent[], cursors: Pick<HistoryPage, "page_older" | "page_newer">): HistoryFoldedRow[] {
126
- if (selected.length === 0) {
127
- // Even a range with no conversation can contain tool/context events.
128
- return foldedRuns(allItems(projection).filter((event) => inSelection(event, params) && isFoldableEvent(event)));
129
- }
130
- const windowEvents = allItems(projection).filter((event) => inSelection(event, params)).sort((a, b) => a.seq - b.seq);
131
- const folded: HistoryFoldedRow[] = [];
132
- const firstSeq = selected[0]!.seq;
133
- const lastSeq = selected.at(-1)!.seq;
134
- if (cursors.page_older === null) folded.push(...foldedRuns(windowEvents.filter((event) => event.seq < firstSeq && isFoldableEvent(event))));
135
- // pageData already ordered selected by seq.
136
- for (let i = 0; i + 1 < selected.length; i++) {
137
- const left = selected[i]!.seq;
138
- const right = selected[i + 1]!.seq;
139
- folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > left && event.seq < right && isFoldableEvent(event))));
101
+ /** Filter and order once. Conversation candidates own the folded gap immediately before them. */
102
+ function prepareSelection(projection: HistoryProjection, params: HistorySelection): PreparedSelection {
103
+ const folds = !params.roles && params.query === undefined;
104
+ const candidates: Candidate[] = [];
105
+ let run: HistoryEvent[] = [];
106
+ for (const event of filteredItems(projection, params, false)) {
107
+ if (folds && (event.role === "tool" || event.role === "context")) {
108
+ run.push(event);
109
+ continue;
110
+ }
111
+ if (folds && eventDocument(event) === "") continue;
112
+ const matchOffset = params.query === undefined ? undefined : earliestMatchOffsetChars(eventDocument(event), params.query as string[]);
113
+ if (matchOffset !== undefined && matchOffset < 0) continue;
114
+ candidates.push({ event, matchOffset, before: foldedRun(run) });
115
+ run = [];
140
116
  }
141
- if (cursors.page_newer === null) folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > lastSeq && isFoldableEvent(event))));
142
- return folded;
117
+ return { candidates, tail: foldedRun(run) };
143
118
  }
144
119
 
145
- function pageData(projection: HistoryProjection, params: HistorySelection, vis: HistoryEvent[], selected: Candidate[], maxChars: number, folds: boolean): HistoryPage {
146
- const orderedSelected = [...selected].sort((a, b) => a.event.seq - b.event.seq);
147
- const selectedEvents = orderedSelected.map((candidate) => candidate.event);
148
- const cursors = pageCursors(vis, selectedEvents, params.before_seq, params.after_seq);
149
- const visible = orderedSelected.map((candidate) => candidate.preview ?? visibleItem(candidate.event, maxChars, candidate.matchOffset));
150
- let rows: PageRow[] = visible;
151
- if (folds) {
152
- const folded = foldRows(projection, params, selectedEvents, cursors);
153
- rows = [...visible, ...folded].sort((a, b) => ("folded" in a ? a.first_seq : a.seq) - ("folded" in b ? b.first_seq : b.seq));
120
+ /** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
121
+ function pageData(prepared: PreparedSelection, start: number, end: number, maxChars: number, preview?: HistoryPageItem): HistoryPage {
122
+ const { candidates, tail } = prepared;
123
+ const items: HistoryPage["items"] = [];
124
+ for (let index = start; index < end; index++) {
125
+ const candidate = candidates[index]!;
126
+ if (candidate.before && (index > start || start === 0)) items.push(candidate.before);
127
+ items.push(preview ?? (candidate.preview ??= visibleItem(candidate.event, maxChars, candidate.matchOffset)));
154
128
  }
155
- return { items: rows, ...cursors };
156
- }
157
-
158
- /** Filter, then keep only literal matches when a normalized query is present. */
159
- function selectionCandidates(projection: HistoryProjection, params: HistorySelection): Candidate[] {
160
- const events = filteredItems(projection, params, params.query === undefined);
161
- if (params.query === undefined) return events.map((event) => ({ event }));
162
- const needles = params.query as string[];
163
- return events
164
- .map((event) => ({ event, matchOffset: earliestMatchOffsetChars(eventDocument(event), needles) }))
165
- .filter((candidate) => candidate.matchOffset >= 0);
129
+ if (end === candidates.length && tail) items.push(tail);
130
+ return {
131
+ items,
132
+ page_older: start > 0 && start < end ? { before_seq: candidates[start]!.event.seq } : null,
133
+ page_newer: end < candidates.length && start < end ? { after_seq: candidates[end - 1]!.event.seq, from: "oldest" } : null,
134
+ };
166
135
  }
167
136
 
168
137
  /**
@@ -180,24 +149,30 @@ export function selectPage(projection: HistoryProjection, params: HistorySelecti
180
149
  throw error;
181
150
  }
182
151
  const scoped = { ...params, ...bounds.data, query: queries.length ? queries : undefined };
183
- const vis = selectionCandidates(projection, scoped);
184
- // Take the limit from the end `from` names, so a budget for one row keeps the most important one.
185
- // At least one: `slice(-0)` would otherwise return the whole selection.
152
+ const prepared = prepareSelection(projection, scoped);
153
+ const { candidates } = prepared;
154
+ // Grow a contiguous interval from the requested end; even a byte-limited newest page stays ascending.
155
+ const newest = scoped.from !== "oldest";
156
+ let start = newest ? candidates.length : 0;
157
+ let end = start;
186
158
  const limit = Math.max(1, scoped.limit ?? 20);
187
- const folds = foldsRuns(scoped);
188
- const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
189
- const ordered = scoped.from === "oldest" ? ascending.slice(0, limit) : ascending.slice(-limit).reverse();
190
- const allVisible = vis.map((candidate) => candidate.event).sort((a, b) => a.seq - b.seq);
191
- const kept: Candidate[] = [];
192
- for (const candidate of ordered) {
193
- if (fits(pageData(projection, scoped, allVisible, [...kept, candidate], maxChars, folds))) {
194
- kept.push(candidate);
159
+ for (let count = 0; count < limit && (newest ? start > 0 : end < candidates.length); count++) {
160
+ const nextStart = newest ? start - 1 : start;
161
+ const nextEnd = newest ? end : end + 1;
162
+ if (fits(pageData(prepared, nextStart, nextEnd, maxChars))) {
163
+ start = nextStart;
164
+ end = nextEnd;
195
165
  continue;
196
166
  }
197
- if (kept.length === 0) kept.push({ ...candidate, preview: truncateHistoryItem(visibleItem(candidate.event, maxChars, candidate.matchOffset), (preview) => fits(pageData(projection, scoped, allVisible, [{ ...candidate, preview }], maxChars, folds))) });
167
+ if (start === end) {
168
+ start = nextStart;
169
+ end = nextEnd;
170
+ const candidate = candidates[start]!;
171
+ candidate.preview = truncateHistoryItem(candidate.preview!, (preview) => fits(pageData(prepared, start, end, maxChars, preview)));
172
+ }
198
173
  break;
199
174
  }
200
- const page = pageData(projection, scoped, allVisible, kept, maxChars, folds);
175
+ const page = pageData(prepared, start, end, maxChars);
201
176
  if (!fits(page)) {
202
177
  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.`);
203
178
  }
@@ -6,6 +6,17 @@ export type NoteAddress = { scope: Scope; path: string; who?: string };
6
6
 
7
7
  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.";
8
8
 
9
+ /** The one home-head vocabulary: the scope each public `@head` names, and the home directory family a head with `home` lists. */
10
+ export const HOME_HEADS: ReadonlyMap<string, { readonly scope: Scope; readonly home?: "project" | "agents" | "models" }> = new Map([
11
+ ["project", { scope: "project" }],
12
+ ["human", { scope: "human" }],
13
+ ["self", { scope: "agent" }],
14
+ ["model", { scope: "model" }],
15
+ ["projects", { scope: "project", home: "project" }],
16
+ ["agents", { scope: "agent", home: "agents" }],
17
+ ["models", { scope: "model", home: "models" }],
18
+ ]);
19
+
9
20
  /**
10
21
  * Minimal glob over virtual note paths: `*` matches any run within a segment (never
11
22
  * `/`), `**` matches any run across segments (a leading double-star followed by a
@@ -52,23 +63,15 @@ export function assertAddress(value: unknown): NoteAddress {
52
63
  let path = value;
53
64
  let who: string | undefined;
54
65
  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") scope = "project";
61
- else if (head === "human") scope = "human";
62
- else if (head === "self") scope = "agent";
63
- else if (head === "model") scope = "model";
64
- else if (head === "projects" || head === "agents" || head === "models") {
65
- const nameEnd = tail.indexOf("/");
66
- who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
66
+ const [rawHead, ...tail] = value.slice(1).split("/");
67
+ const head = HOME_HEADS.get(rawHead!);
68
+ if (head === undefined) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
69
+ scope = head.scope;
70
+ if (head.home === undefined) path = tail.join("/");
71
+ else {
72
+ who = tail[0] ?? "";
67
73
  if (!SLUG_PATTERN.test(who)) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
68
- scope = head === "projects" ? "project" : head === "agents" ? "agent" : "model";
69
- path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
70
- } else {
71
- throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
74
+ path = tail.slice(1).join("/");
72
75
  }
73
76
  if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
74
77
  if (path === "" && who === undefined) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
@@ -3,7 +3,7 @@ import type { Dirent } from "node:fs";
3
3
  import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { earliestMatchOffsetChars } from "../text-match.js";
6
- import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp } from "./address.js";
6
+ import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp, HOME_HEADS } from "./address.js";
7
7
  import { isFilesystemError } from "./fs-error.js";
8
8
  import { snapshotNotesIdentity, type NotesIdentity } from "./identity.js";
9
9
  import { NoteError } from "./errors.js";
@@ -121,19 +121,14 @@ type HomeRef = { scope: Scope; who?: string };
121
121
 
122
122
  async function homesForPattern(pattern: string | undefined, identity: NotesIdentity): Promise<HomeRef[] | undefined> {
123
123
  if (!pattern || !pattern.startsWith("@")) return undefined;
124
- const head = /^@([^/]+)\//.exec(pattern)?.[1];
125
- if (head === "project") return [{ scope: "project" }];
126
- if (head === "human") return [{ scope: "human" }];
127
- if (head === "self") return [{ scope: "agent" }];
128
- if (head === "model") return [{ scope: "model" }];
129
- if (head === "projects" || head === "agents" || head === "models") {
130
- const scope: Scope = head === "projects" ? "project" : head === "agents" ? "agent" : "model";
131
- const name = pattern.slice(head.length + 2).split("/")[0] ?? "";
132
- if (name.length > 0 && !/[*?]/.test(name)) return [{ scope, who: assertWho(name) }];
133
- const names = head === "projects" ? projectHomes(identity.home).map(home => home.name) : await namespaceSlugs(head, identity.home);
134
- return names.map((who) => ({ scope, who }));
135
- }
136
- return [];
124
+ const [rawHead, ...tail] = pattern.split("/");
125
+ const head = tail.length === 0 ? undefined : HOME_HEADS.get(rawHead!.slice(1)); // a bare "@projects" names no homes
126
+ if (head === undefined) return [];
127
+ if (head.home === undefined) return [{ scope: head.scope }];
128
+ const name = tail[0];
129
+ if (name !== undefined && name.length > 0 && !/[*?]/.test(name)) return [{ scope: head.scope, who: assertWho(name) }];
130
+ const names = head.home === "project" ? projectHomes(identity.home).map(home => home.name) : await namespaceSlugs(head.home, identity.home);
131
+ return names.map((who) => ({ scope: head.scope, who }));
137
132
  }
138
133
 
139
134
  /** Relative pattern heads resolve to canonical names, so they match canonical addresses. */
package/src/pi/boot.ts CHANGED
@@ -1,11 +1,11 @@
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 type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import { agentSlug, modelSlug, notesIdentityFromPi } from "./notes/adapter.js";
4
4
  import { loadNotesSnapshot, unavailableNotesSnapshot, type NotesSnapshot } from "../boot/snapshot.js";
5
5
  import { isFilesystemError } from "../notes/index.js";
6
6
  import { BOOT_TYPE } from "./entries.js";
7
7
  import { renderBootBlock } from "../boot/render.js";
8
- import { rootWindowId } from "./window.js";
8
+ import { historyFromSession, nextHistorySeq } from "./history.js";
9
9
 
10
10
  export type IncompleteNotesNotifier = (ctx: ExtensionContext, windowId: string, snapshot: NotesSnapshot) => void;
11
11
 
@@ -24,13 +24,35 @@ export type BootMessage = {
24
24
  export async function buildBootMessage(
25
25
  ctx: ExtensionContext,
26
26
  windowId: string,
27
- previousId: string | undefined,
27
+ firstSeq: number | undefined,
28
28
  notifyIncompleteNotes?: IncompleteNotesNotifier,
29
29
  isCurrent: () => boolean = () => true,
30
30
  ): Promise<BootMessage> {
31
31
  const agentName = agentSlug();
32
32
  const modelName = modelSlug(ctx);
33
- const sessionId = ctx.sessionManager.getSessionId();
33
+ const windows = historyFromSession(ctx).windows.map((window) => {
34
+ const seqs = window.items.map((item) => item.seq);
35
+ return {
36
+ shortName: window.windowId.slice(window.windowId.lastIndexOf(":") + 1),
37
+ firstSeq: firstSeq === undefined || seqs.length === 0 ? undefined : Math.min(...seqs),
38
+ lastSeq: firstSeq === undefined || seqs.length === 0 ? undefined : Math.max(...seqs),
39
+ isCurrent: window.windowId === windowId,
40
+ };
41
+ });
42
+ if (firstSeq !== undefined) {
43
+ // An empty old window will consume the pending boundary before its marker is written.
44
+ const last = windows.at(-1)!;
45
+ last.firstSeq ??= last.isCurrent ? firstSeq : nextHistorySeq(ctx);
46
+ }
47
+ if (!windows.some((window) => window.isCurrent)) {
48
+ windows.push({ shortName: windowId.slice(windowId.lastIndexOf(":") + 1), firstSeq, lastSeq: undefined, isCurrent: true });
49
+ }
50
+ // A closing boundary includes folded result slots, pending warnings and the old checkpoint.
51
+ for (let index = 0; index < windows.length - 1; index++) {
52
+ const nextFirst = windows[index + 1]!.firstSeq;
53
+ if (nextFirst !== undefined) windows[index]!.lastSeq = nextFirst - 1;
54
+ }
55
+ const tree = { trunk: windowId.slice(0, windowId.lastIndexOf(":")), windows };
34
56
  const openedAt = Date.now();
35
57
  let notes: NotesSnapshot;
36
58
  try {
@@ -42,7 +64,7 @@ export async function buildBootMessage(
42
64
  if (isCurrent()) notifyIncompleteNotes?.(ctx, windowId, notes);
43
65
  return {
44
66
  customType: BOOT_TYPE,
45
- content: renderBootBlock({ agentName, modelName, firstWindowId: rootWindowId(sessionId), currentWindowId: windowId, previousWindowId: previousId, notes, tools: DEFAULT_BOOT_TOOL_NAMES }),
67
+ content: renderBootBlock({ agentName, modelName, tree, notes, tools: { ...DEFAULT_BOOT_TOOL_NAMES, preResetHints: PI_PRE_RESET_HINTS } }),
46
68
  display: false,
47
69
  details: { windowId },
48
70
  };
package/src/pi/budget.ts CHANGED
@@ -3,9 +3,9 @@ import { remainingBudget, type ResolvedThresholds } from "../budget/policy.js";
3
3
  import { Type } from "@earendil-works/pi-ai";
4
4
  import { defineTool, type ExtensionAPI, type ExtensionContext, type SessionBoundaryDraft, type SettingsManager } 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, type ThresholdSettingsResolution } 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, type AnchorDetails } from "./anchored.js";
11
11
  import { output } from "./tool-result.js";
@@ -23,9 +23,6 @@ export function registerBudget(
23
23
  ) {
24
24
  let cachedPolicy: { thresholds: ResolvedThresholds; automatic: boolean } | undefined;
25
25
  const notifiedWarnings = new Set<string>();
26
- // The reset owner is wired after both sides exist, so no handler can observe a
27
- // half-constructed pair (a close-out request cannot arrive before registration ends).
28
- let onCloseOut: (windowId: string) => void = () => {};
29
26
  const resolvePolicy = (ctx: ExtensionContext): ThresholdSettingsResolution => {
30
27
  if (!settingsManager && cachedPolicy) return { ...cachedPolicy, warnings: [] };
31
28
  const resolution = readThresholdSettings(ctx, settingsManager);
@@ -46,31 +43,7 @@ export function registerBudget(
46
43
  };
47
44
  let pendingGuidance: { windowId: string; content: string } | undefined;
48
45
  let pendingWarning: { windowId: string; content: string } | undefined;
49
- let pendingNotices = new Map<string, { sessionId: string; windowId: string }>();
50
- const noticeKey = (sessionId: string, windowId: string) => `${sessionId}:${windowId}`;
51
- const warningCommittedInWindow = (ctx: ExtensionContext, notice: { sessionId: string; windowId: string }): boolean => {
52
- if (ctx.sessionManager.getSessionId() !== notice.sessionId) return false;
53
- let windowId = rootWindowId(notice.sessionId);
54
- for (const entry of ctx.sessionManager.getBranch()) {
55
- if (isWindowMarker(entry)) {
56
- windowId = entry.data.windowId;
57
- continue;
58
- }
59
- if (windowId === notice.windowId && entry.type === "custom_message" && entry.customType === WARNING_TYPE) return true;
60
- }
61
- return false;
62
- };
63
- const notifyCommittedWarnings = (ctx: ExtensionContext, settled = false) => {
64
- for (const [key, notice] of pendingNotices) {
65
- if (warningCommittedInWindow(ctx, notice)) {
66
- pendingNotices.delete(key);
67
- ctx.ui.notify("🥣 Brain almost full · taking notes", "warning");
68
- } else if (settled) {
69
- // An uncommitted draft must not be matched to a later manual warning.
70
- pendingNotices.delete(key);
71
- }
72
- }
73
- };
46
+ const notifiedWindows = new Set<string>();
74
47
 
75
48
  const clearStaged = () => {
76
49
  pendingGuidance = undefined;
@@ -78,7 +51,7 @@ export function registerBudget(
78
51
  };
79
52
  const resetForTransition = () => {
80
53
  clearStaged();
81
- pendingNotices.clear();
54
+ notifiedWindows.clear();
82
55
  cachedPolicy = undefined;
83
56
  notifiedWarnings.clear();
84
57
  };
@@ -91,10 +64,6 @@ export function registerBudget(
91
64
  clearStaged();
92
65
  const windowId = currentWindowId(ctx);
93
66
  const drafts = staged.filter((draft): draft is NonNullable<typeof draft> => draft !== undefined && draft.windowId === windowId);
94
- if (drafts.some((draft) => draft.customType === WARNING_TYPE)) {
95
- const sessionId = ctx.sessionManager.getSessionId();
96
- pendingNotices.set(noticeKey(sessionId, windowId), { sessionId, windowId });
97
- }
98
67
  return drafts.map((draft) => ({
99
68
  type: "custom_message" as const,
100
69
  customType: draft.customType,
@@ -108,14 +77,7 @@ export function registerBudget(
108
77
  pi.on("session_tree", resetForTransition);
109
78
  pi.on("model_select", resetForTransition);
110
79
  pi.on("session_shutdown", resetForTransition);
111
- // A warning can be committed at turn_end, before a tool turn or a reset changes the
112
- // active window. Observe the active branch at public lifecycle boundaries and match
113
- // the candidate against its originating window segment, not only the current window.
114
- pi.on("turn_start", (_event, ctx) => notifyCommittedWarnings(ctx));
115
- pi.on("agent_settled", (_event, ctx) => {
116
- notifyCommittedWarnings(ctx, true);
117
- clearStaged();
118
- });
80
+ pi.on("agent_settled", clearStaged);
119
81
  pi.on("context", (event, ctx) => {
120
82
  if (!isEnabled()) return undefined;
121
83
  // Durable reminders return to the slot where the model first read them.
@@ -133,14 +95,17 @@ export function registerBudget(
133
95
  const windowId = currentWindowId(ctx);
134
96
  const { reminder, warning } = thresholdsFor(ctx);
135
97
  if (remaining <= warning) {
136
- // Re-arm close-out on each eligible request. A prior request may have aborted
137
- // after persisting the warning, so warning deduplication must not own this state.
138
- onCloseOut(windowId);
139
98
  if (hasWindowMessage(ctx, WARNING_TYPE)) return result();
140
99
  // The critical close-out starts at reserve + runway, not at the hard reserve.
141
100
  // Another request in the same turn re-sends the staged text instead of re-measuring.
142
101
  pendingGuidance = undefined;
143
- if (pendingWarning?.windowId !== windowId) pendingWarning = { windowId, content: WARNING_CONTENT };
102
+ if (pendingWarning?.windowId !== windowId) pendingWarning = { windowId, content: warningContent() };
103
+ // Notify when injected, not after tools finish or a reset has already committed.
104
+ // An aborted request does not undo the low-budget condition or repeat the toast.
105
+ if (!notifiedWindows.has(windowId)) {
106
+ notifiedWindows.add(windowId);
107
+ ctx.ui.notify("🥣 Brain almost full · taking notes", "warning");
108
+ }
144
109
  return result({ customType: WARNING_TYPE, content: pendingWarning.content });
145
110
  }
146
111
  if (hasWindowMessage(ctx, WARNING_TYPE) || pendingWarning?.windowId === windowId) return result();
@@ -169,10 +134,8 @@ export function registerBudget(
169
134
  automaticResetEnabled,
170
135
  hardReserveDue,
171
136
  consumeTurnEnd,
172
- /** The reset owner wires its close-out here once the lifecycle reducer exists. */
173
- setCloseOut: (handler: (windowId: string) => void) => { onCloseOut = handler; },
174
137
  /** The same close-out countdown the model sees, for user-facing status; null when usage is unknown. */
175
138
  statusFor: (ctx: ExtensionContext): { remaining: number | null } => ({ remaining: remainingBudget(remainingTokens(ctx), thresholdsFor(ctx).warning) }),
176
- clear: () => { clearStaged(); pendingNotices.clear(); },
139
+ clear: () => { clearStaged(); notifiedWindows.clear(); },
177
140
  };
178
141
  }
package/src/pi/entries.ts CHANGED
@@ -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";
package/src/pi/history.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import type { ToolCall } from "@earendil-works/pi-ai";
12
12
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
13
- import type { SessionEntry } from "@earendil-works/pi-coding-agent";
13
+ import type { SessionBoundaryDraft, SessionEntry } from "@earendil-works/pi-coding-agent";
14
14
  import type { SessionReader } from "./session-reader.js";
15
15
  import { isWindowMarker, rootWindowId } from "./window.js";
16
16
  import { contentText, projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection, type NestedCallRecord, type ToolCallStatus } from "../history/history.js";
@@ -28,13 +28,18 @@ function isToolCall(part: unknown): part is ToolCall {
28
28
  }
29
29
 
30
30
  /** Seq allocation depends on entry kind and role, never on visible content. */
31
- function sequenceCount(entry: SessionEntry): number {
31
+ function sequenceCount(entry: SessionEntry | SessionBoundaryDraft): number {
32
32
  if (entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "custom_message") return 1;
33
33
  if (entry.type !== "message" || mapRole(entry.message.role) === undefined) return 0;
34
34
  if (entry.message.role !== "assistant" || !Array.isArray(entry.message.content)) return 1;
35
35
  return 1 + entry.message.content.filter(isToolCall).length;
36
36
  }
37
37
 
38
+ /** Pending boundary drafts use the same slots as persisted entries. */
39
+ export function nextHistorySeq(ctx: SessionReader, pending: readonly SessionBoundaryDraft[] = []): number {
40
+ return 1 + [...ctx.sessionManager.getEntries(), ...pending].reduce((sum, entry) => sum + sequenceCount(entry), 0);
41
+ }
42
+
38
43
  function messageContent(message: AgentMessage): string {
39
44
  switch (message.role) {
40
45
  case "bashExecution":