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
@@ -1,8 +1,8 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import type { ExtensionAPI, ExtensionContext, SessionBoundaryDraft, SessionEntry } from "@earendil-works/pi-coding-agent";
3
- import { BOOT_TYPE, CONTINUATION_TYPE, RESET_LAST_WORD_TYPE, RESET_MARKER_TYPE, RESET_PROMPT_TYPE } from "../entries.js";
4
- import { CONTINUATION } from "../../budget/text.js";
5
- import { currentWindowId, isForeignResetTailEntry, isWindowBootEntry, isWindowMarker, previousWindowId, type WindowMarker } from "../window.js";
3
+ import { BOOT_TYPE, CONTINUATION_TYPE, RESET_LAST_WORD_TYPE, RESET_MARKER_TYPE } from "../entries.js";
4
+ import { selectContinuation, type ResetOrigin } from "../../budget/text.js";
5
+ import { isForeignResetTailEntry, isWindowBootEntry, isWindowMarker, markerResetOrigin, type WindowMarker } from "../window.js";
6
6
  import { buildBootMessage, sendBoot, type IncompleteNotesNotifier } from "../boot.js";
7
7
 
8
8
  export type ResetTailState = { readonly boot: boolean; readonly continuation: boolean };
@@ -24,26 +24,30 @@ export function isWindowContinuationEntry(entry: SessionEntry): boolean {
24
24
  }
25
25
 
26
26
  /** The single continuation sender: the only reset prose persisted for a window. */
27
- function sendContinuation(pi: ExtensionAPI): void {
27
+ function sendContinuation(pi: ExtensionAPI, content: string): void {
28
28
  pi.sendMessage(
29
- { customType: CONTINUATION_TYPE, content: CONTINUATION, display: false },
29
+ { customType: CONTINUATION_TYPE, content, display: false },
30
30
  { triggerTurn: false },
31
31
  );
32
32
  }
33
33
 
34
34
  /**
35
35
  * The closed, ordered reset shape: retain-none native checkpoint, marker, matching boot,
36
- * continuation, then an optional parting line and command prompt. The boot snapshot is acquired asynchronously after capturing this identity.
36
+ * continuation, then an optional parting line. The prompt is not persisted here — it reached the
37
+ * closing window inside the warning. The boot snapshot is acquired asynchronously after capturing
38
+ * this identity. The continuation is drawn from the pool its origin names, here, once: the caller
39
+ * persists the returned text and no read, render, or repair draws it again. The origin defaults to
40
+ * `normal`, the same reading a legacy marker with no origin gets.
37
41
  */
38
42
  export async function buildResetDrafts(
39
43
  ctx: ExtensionContext,
40
44
  notifyIncompleteNotes?: IncompleteNotesNotifier,
41
45
  isCurrent: () => boolean = () => true,
42
- prompt?: string,
43
46
  lastWord?: string,
47
+ firstSeq?: number,
48
+ origin: ResetOrigin = "normal",
44
49
  ): Promise<SessionBoundaryDraft[]> {
45
50
  const sessionId = ctx.sessionManager.getSessionId();
46
- const previousId = currentWindowId(ctx);
47
51
  const sessionPrefix = sessionId.slice(0, 8);
48
52
  const usedWindowIds = new Set(
49
53
  ctx.sessionManager.getBranch().filter(isWindowMarker).map((entry) => entry.data.windowId),
@@ -52,14 +56,13 @@ export async function buildResetDrafts(
52
56
  do {
53
57
  windowId = `pcw:${sessionPrefix}:${randomUUID().slice(0, 8)}`;
54
58
  } while (usedWindowIds.has(windowId));
55
- const boot = await buildBootMessage(ctx, windowId, previousId, notifyIncompleteNotes, isCurrent);
59
+ const boot = await buildBootMessage(ctx, windowId, firstSeq, notifyIncompleteNotes, isCurrent);
56
60
  return [
57
61
  { type: "compaction", summary: "", firstKeptEntryId: null },
58
- { type: "custom", customType: RESET_MARKER_TYPE, data: { windowId } },
62
+ { type: "custom", customType: RESET_MARKER_TYPE, data: { windowId, origin } },
59
63
  { type: "custom_message", customType: BOOT_TYPE, content: boot.content, display: false, details: { windowId } },
60
- { type: "custom_message", customType: CONTINUATION_TYPE, content: CONTINUATION, display: false },
64
+ { type: "custom_message", customType: CONTINUATION_TYPE, content: selectContinuation(origin), display: false },
61
65
  ...(lastWord ? [{ type: "custom_message" as const, customType: RESET_LAST_WORD_TYPE, content: `${LAST_WORD_PREFIX}${lastWord}`, display: true }] : []),
62
- ...(prompt ? [{ type: "custom_message" as const, customType: RESET_PROMPT_TYPE, content: prompt, display: true }] : []),
63
66
  ];
64
67
  }
65
68
 
@@ -104,10 +107,10 @@ export async function repairResetTail(
104
107
  ): Promise<void> {
105
108
  const tail = inspectResetTail(ctx, marker.id, marker.data.windowId);
106
109
  if (!tail || (tail.boot && tail.continuation)) return;
107
- const boot = tail.boot ? undefined : await buildBootMessage(ctx, marker.data.windowId, previousWindowId(ctx, marker.id), notifyIncompleteNotes, isCurrent);
110
+ const boot = tail.boot ? undefined : await buildBootMessage(ctx, marker.data.windowId, undefined, notifyIncompleteNotes, isCurrent);
108
111
  if (!isCurrent()) return;
109
112
  const latest = inspectResetTail(ctx, marker.id, marker.data.windowId);
110
113
  if (!latest) return;
111
114
  if (!latest.boot && boot) sendBoot(pi, boot);
112
- if (!latest.continuation && (latest.boot || boot)) sendContinuation(pi);
115
+ if (!latest.continuation && (latest.boot || boot)) sendContinuation(pi, selectContinuation(markerResetOrigin(marker)));
113
116
  }
@@ -2,7 +2,9 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import { getCurrentSystemMessage, isContextOverflow, isRecoverableLength } from "@earendil-works/pi-ai";
3
3
  import type { AgentBeforeSettleEvent, ExtensionAPI, ExtensionContext, SessionBoundaryDraft } from "@earendil-works/pi-coding-agent";
4
4
  import { currentReset, currentWindowId } from "../window.js";
5
+ import { nextHistorySeq } from "../history.js";
5
6
  import { resetBoundaryCommitted } from "./committed.js";
7
+ import type { ResetOrigin } from "../../budget/text.js";
6
8
  import { errorMessage } from "../../error-message.js";
7
9
 
8
10
  type BudgetOwner = {
@@ -15,7 +17,7 @@ type BudgetOwner = {
15
17
  type ResetOptions = {
16
18
  isEnabled: () => boolean;
17
19
  budget: BudgetOwner;
18
- buildReset: (ctx: ExtensionContext, isCurrent: () => boolean, prompt?: string, lastWord?: string) => SessionBoundaryDraft[] | Promise<SessionBoundaryDraft[]>;
20
+ buildReset: (ctx: ExtensionContext, isCurrent: () => boolean, lastWord: string | undefined, firstSeq: number, origin: ResetOrigin) => SessionBoundaryDraft[] | Promise<SessionBoundaryDraft[]>;
19
21
  getLifecycleGeneration?: () => number;
20
22
  onResetReady?: (ctx: ExtensionContext, drafts: readonly SessionBoundaryDraft[]) => void;
21
23
  };
@@ -30,15 +32,13 @@ function isOverflowLike(message: AgentMessage, ctx: ExtensionContext): boolean {
30
32
  (ctx.model !== undefined && isRecoverableLength(message, ctx.model.maxTokens));
31
33
  }
32
34
 
33
- export type ResetRequestSource = "manual" | "automatic";
34
- type ToolResetRequestSource = "automatic" | "tool";
35
35
  export type ResetRequest =
36
36
  | { readonly phase: "none" }
37
- // The safety reset may change windows before Pi finishes its tool-batch continuation.
38
- // This run-scoped stop intent survives that change; windowId is the pre-reset window.
39
- | { readonly phase: "stop-pending"; readonly windowId: string }
40
- | { readonly phase: "close-out"; readonly windowId: string; readonly source: ResetRequestSource; readonly prompt?: string; readonly lastWord?: string }
41
- | { readonly phase: "tool-requested"; readonly windowId: string; readonly source: ToolResetRequestSource; readonly lastWord?: string };
37
+ // A hard-reserve reset may precede the end of Pi's tool-batch continuation.
38
+ | { readonly phase: "stop-pending"; readonly windowId: string; readonly tool?: { readonly lastWord?: string } }
39
+ | { readonly phase: "pending"; readonly windowId: string;
40
+ readonly command?: { readonly continueAfterReset: boolean };
41
+ readonly tool?: { readonly lastWord?: string } };
42
42
  export type ResetOverflowPhase = "idle" | "pending" | "pending-spent" | "spent";
43
43
 
44
44
  export interface ResetControlState {
@@ -75,7 +75,7 @@ export interface ResetBeforeSettleFacts {
75
75
  }
76
76
 
77
77
  export type ResetControlEvent =
78
- | { readonly type: "close_out"; readonly windowId: string; readonly source: ResetRequestSource; readonly prompt?: string }
78
+ | { readonly type: "command"; readonly windowId: string; readonly continueAfterReset: boolean }
79
79
  | { readonly type: "tool_request"; readonly windowId: string; readonly lastWord?: string }
80
80
  | { readonly type: "turn_end"; readonly facts: ResetTurnEndFacts }
81
81
  | { readonly type: "before_settle"; readonly facts: ResetBeforeSettleFacts }
@@ -95,73 +95,53 @@ export type ResetControlEffect =
95
95
  export interface ResetControlResult {
96
96
  readonly state: ResetControlState;
97
97
  readonly effect: ResetControlEffect;
98
- readonly prompt?: string;
99
98
  readonly lastWord?: string;
99
+ /** The origin of the boundary this decision commits. Absent means no `empty_brain` call was recorded, so forced. */
100
+ readonly origin?: ResetOrigin;
100
101
  }
101
102
 
102
103
  function requestForWindow(request: ResetRequest, windowId: string): ResetRequest {
103
104
  return request.phase === "stop-pending" || (request.phase !== "none" && request.windowId === windowId) ? request : NO_REQUEST;
104
105
  }
105
106
 
106
- function manualCommit(prompt?: string, lastWord?: string): ResetControlResult {
107
- const parting = lastWord ? { lastWord } : {};
108
- return prompt
109
- ? { state: initialResetControl(), effect: "commit-boundary", prompt, ...parting }
110
- : { state: initialResetControl(), effect: "commit-boundary-stop", ...parting };
107
+ function commandCommit(request: Extract<ResetRequest, { phase: "pending" }>): ResetControlResult {
108
+ return {
109
+ state: initialResetControl(),
110
+ effect: request.command?.continueAfterReset ? "commit-boundary" : "commit-boundary-stop",
111
+ ...requestDetails(request),
112
+ };
111
113
  }
112
114
 
113
- /** The parting line rides either committing phase; other phases never carry one. */
114
- function requestLastWord(request: ResetRequest): string | undefined {
115
- return request.phase === "close-out" || request.phase === "tool-requested" ? request.lastWord : undefined;
115
+ /** The tool request itself is the origin fact; the stop latch retains it for construction retry. */
116
+ function requestDetails(request: ResetRequest): { origin: ResetOrigin; lastWord?: string } {
117
+ const tool = request.phase === "none" ? undefined : request.tool;
118
+ return { origin: tool ? "normal" : "forced", ...tool };
116
119
  }
117
120
 
118
- /** Pure reset-control transitions: request phases own close-out, tool commit, and fallback. */
121
+ /** Pure transitions: command policy schedules a reset without disguising actual tool calls. */
119
122
  export function reduceResetControl(state: ResetControlState, event: ResetControlEvent): ResetControlResult {
120
123
  switch (event.type) {
121
- case "close_out": {
122
- const request = state.request;
123
- const prompt = event.source === "manual" && event.prompt?.trim() ? { prompt: event.prompt.trim() } : {};
124
- if (request.phase === "stop-pending") return { state, effect: "already-pending" };
125
- if (request.phase === "tool-requested" && request.windowId === event.windowId) {
126
- // A manual wipe outranks a pending rollover: close out before committing.
127
- if (event.source === "manual") {
128
- return { state: { ...state, request: { phase: "close-out", windowId: event.windowId, source: "manual", ...prompt } }, effect: "close-out-armed" };
129
- }
130
- return { state, effect: "already-pending" };
131
- }
132
- if (request.phase === "close-out" && request.windowId === event.windowId) {
133
- if (request.source === "manual" || event.source === "automatic") return { state, effect: "already-pending" };
134
- return { state: { ...state, request: { ...request, source: "manual", ...prompt } }, effect: "close-out-armed" };
135
- }
136
- return { state: { ...state, request: { phase: "close-out", windowId: event.windowId, source: event.source, ...prompt } }, effect: "close-out-armed" };
137
- }
124
+ case "command":
138
125
  case "tool_request": {
139
- const request = state.request;
140
- if (request.phase === "stop-pending") return { state, effect: "already-pending" };
141
- if (request.phase === "tool-requested" && request.windowId === event.windowId) {
142
- return { state, effect: "already-pending" };
143
- }
144
- const parting = event.lastWord ? { lastWord: event.lastWord } : {};
145
- // A manual close-out must settle so the stop actually lands; the agent's own wipe
146
- // call during one is only an acknowledgement, never a conversion to a turn-end
147
- // commit that pi's tool-batch continuation can overrun. A budget close-out still
148
- // upgrades: context pressure cannot wait for settlement.
149
- if (request.phase === "close-out" && request.windowId === event.windowId) {
150
- // The acknowledging call still contributes its last word; the manual commit keeps the wheel.
151
- if (request.source === "manual") {
152
- const lastWord = request.lastWord ?? event.lastWord;
153
- return { state: { ...state, request: { ...request, ...(lastWord ? { lastWord } : {}) } }, effect: "already-pending" };
154
- }
155
- return { state: { ...state, request: { phase: "tool-requested", windowId: event.windowId, source: "automatic", ...parting } }, effect: "close-out-armed" };
126
+ const current = requestForWindow(state.request, event.windowId);
127
+ if (current.phase === "stop-pending") return { state, effect: "already-pending" };
128
+ const request = current.phase === "pending" ? current : { phase: "pending" as const, windowId: event.windowId };
129
+ if (event.type === "command") {
130
+ if (request.command) return { state, effect: "already-pending" };
131
+ return { state: { ...state, request: { ...request, command: { continueAfterReset: event.continueAfterReset } } }, effect: "close-out-armed" };
156
132
  }
157
- return { state: { ...state, request: { phase: "tool-requested", windowId: event.windowId, source: "tool", ...parting } }, effect: "close-out-armed" };
133
+ // The call remains a real request even when command policy delays its commit.
134
+ const duplicate = request.tool !== undefined;
135
+ const lastWord = request.tool?.lastWord ?? event.lastWord;
136
+ const tool = duplicate && !request.command ? request.tool : (lastWord ? { lastWord } : {});
137
+ return { state: { ...state, request: { ...request, tool } }, effect: duplicate ? "already-pending" : "close-out-armed" };
158
138
  }
159
139
  case "turn_end": {
160
140
  const facts = event.facts;
161
141
  const request = requestForWindow(state.request, facts.windowId);
162
142
  if (facts.aborted) return { state: initialResetControl(), effect: "none" };
163
143
  if (request.phase === "stop-pending") return { state: { request, overflow: "idle" }, effect: "none" };
164
- const manual = request.phase === "close-out" && request.source === "manual";
144
+ const manual = request.phase === "pending" && request.command !== undefined;
165
145
  if (facts.overflow) {
166
146
  const pending = manual ? facts.enabled : !facts.queued && facts.enabled && facts.automaticResetEnabled;
167
147
  const spent = state.overflow === "pending-spent" || state.overflow === "spent";
@@ -176,11 +156,10 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
176
156
  }
177
157
  // A direct tool request commits after the whole tool batch. The budget cutoff is
178
158
  // a separate hard-reserve safety path; ordinary close-out waits for settlement.
179
- if (request.phase === "tool-requested" || facts.hardReserveDue) {
180
- const lastWord = requestLastWord(request);
181
- if (manual && request.prompt) return manualCommit(request.prompt, lastWord);
182
- if (manual) return { state: { request: { phase: "stop-pending", windowId: facts.windowId }, overflow: "idle" }, effect: "commit-boundary-stop", ...(lastWord ? { lastWord } : {}) };
183
- return { state: { request: NO_REQUEST, overflow: "idle" }, effect: "commit-boundary", ...(lastWord ? { lastWord } : {}) };
159
+ if ((request.phase === "pending" && request.tool && !manual) || facts.hardReserveDue) {
160
+ if (manual && request.command?.continueAfterReset) return commandCommit(request);
161
+ if (manual) return { state: { request: { phase: "stop-pending", windowId: facts.windowId, ...(request.tool ? { tool: request.tool } : {}) }, overflow: "idle" }, effect: "commit-boundary-stop", ...requestDetails(request) };
162
+ return { state: { request: NO_REQUEST, overflow: "idle" }, effect: "commit-boundary", ...requestDetails(request) };
184
163
  }
185
164
  return { state: { request, overflow: "idle" }, effect: "none" };
186
165
  }
@@ -193,27 +172,27 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
193
172
  // Only retry construction if the safety boundary never committed. Otherwise
194
173
  // stop without a second wipe, even if a queued turn subsequently failed.
195
174
  if (request.windowId !== facts.windowId) return { state: initialResetControl(), effect: "stop" };
196
- return { state: initialResetControl(), effect: facts.failed || !facts.enabled ? "none" : "commit-boundary-stop" };
175
+ return { state: initialResetControl(), effect: facts.failed || !facts.enabled ? "none" : "commit-boundary-stop", ...requestDetails(request) };
197
176
  }
198
- const manual = request.phase === "close-out" && request.source === "manual";
177
+ const manual = request.phase === "pending" && request.command !== undefined;
199
178
  if (state.overflow === "pending" || state.overflow === "pending-spent") {
200
179
  if (facts.queued) {
201
180
  return { state: { ...state, request: facts.failed && !manual ? NO_REQUEST : request }, effect: "none" };
202
181
  }
203
182
  // An explicit manual wipe is not an automatic recovery/retry. It must still
204
183
  // clear on overflow, including when automatic reset is disabled.
205
- if (manual && facts.enabled) return manualCommit(request.prompt, requestLastWord(request));
184
+ if (manual && facts.enabled) return commandCommit(request);
206
185
  const spent = state.overflow === "pending-spent";
207
186
  if (!facts.enabled || !facts.automaticResetEnabled) {
208
187
  return { state: { request: facts.failed ? NO_REQUEST : request, overflow: spent ? "spent" : "idle" }, effect: "none" };
209
188
  }
210
- return { state: { request: NO_REQUEST, overflow: "spent" }, effect: spent ? "none" : "recover-overflow" };
189
+ return { state: { request: NO_REQUEST, overflow: "spent" }, effect: spent ? "none" : "recover-overflow", ...requestDetails(request) };
211
190
  }
212
191
  if (facts.failed || !facts.enabled || !manual) {
213
192
  return { state: { ...state, request: NO_REQUEST }, effect: "none" };
214
193
  }
215
194
  if (facts.queued) return { state: { ...state, request }, effect: "none" };
216
- return manualCommit(request.prompt, requestLastWord(request));
195
+ return commandCommit(request);
217
196
  }
218
197
  case "settled":
219
198
  return { state: initialResetControl(), effect: "none" };
@@ -224,13 +203,9 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
224
203
  }
225
204
 
226
205
  /**
227
- * Own close-out requests at Pi's public turn and pre-settlement boundaries. Manual and budget
228
- * close-outs remain armed across note/tool turns. Only manual close-outs commit at a
229
- * successful agent_before_settle; budget warnings alone never authorize a reset.
230
- * A hard-reserve safety reset can commit earlier, but preserves a
231
- * run-scoped manual stop and cancels an otherwise automatic fresh-window request through
232
- * the public abort API. Direct tool requests commit at turn_end and continue normally.
233
- * Overflow recovery remains bounded.
206
+ * Tool-only requests commit at turn_end; command policy waits for settlement.
207
+ * Hard reserve may commit earlier while preserving a command's stop latch.
208
+ * Budget warnings carry no lifecycle state. Overflow recovery remains bounded.
234
209
  */
235
210
  export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions) {
236
211
  let sessionActive = true;
@@ -238,7 +213,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
238
213
  let control = initialResetControl();
239
214
 
240
215
  const clear = () => { control = reduceResetControl(control, { type: "clear" }).state; };
241
- const resetBoundaryResult = async (entries: SessionBoundaryDraft[], ctx: ExtensionContext, continueAfterReset: boolean, prompt?: string, lastWord?: string) => {
216
+ const resetBoundaryResult = async (entries: SessionBoundaryDraft[], ctx: ExtensionContext, continueAfterReset: boolean, lastWord: string | undefined, origin: ResetOrigin) => {
242
217
  const generation = lifecycleGeneration;
243
218
  const outerGeneration = options.getLifecycleGeneration?.();
244
219
  const sessionId = ctx.sessionManager.getSessionId();
@@ -246,11 +221,13 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
246
221
  const isCurrent = () => sessionActive && lifecycleGeneration === generation &&
247
222
  (outerGeneration === undefined || options.getLifecycleGeneration?.() === outerGeneration) && options.isEnabled() &&
248
223
  ctx.signal?.aborted !== true && ctx.sessionManager.getSessionId() === sessionId && currentWindowId(ctx) === windowId;
224
+ // The retain-none checkpoint belongs to the old window; capture its successor before notes await.
225
+ const firstSeq = nextHistorySeq(ctx, entries) + 1;
249
226
  let resetDrafts: SessionBoundaryDraft[];
250
227
  try {
251
- resetDrafts = await options.buildReset(ctx, isCurrent, prompt, lastWord);
228
+ resetDrafts = await options.buildReset(ctx, isCurrent, lastWord, firstSeq, origin);
252
229
  } catch (error) {
253
- if (isCurrent()) ctx.ui.notify(`🥣 Brain still full: ${errorMessage(error)}${prompt ? " · prompt not sent" : ""}`, "warning");
230
+ if (isCurrent()) ctx.ui.notify(`🥣 Brain still full: ${errorMessage(error)}`, "warning");
254
231
  return entries.length > 0 ? { entries } : undefined;
255
232
  }
256
233
  if (!isCurrent()) return entries.length > 0 ? { entries } : undefined;
@@ -294,7 +271,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
294
271
  },
295
272
  });
296
273
  control = decision.state;
297
- if (decision.effect === "commit-boundary" || decision.effect === "commit-boundary-stop") return await resetBoundaryResult(entries, ctx, decision.effect === "commit-boundary", decision.prompt, decision.lastWord);
274
+ if (decision.effect === "commit-boundary" || decision.effect === "commit-boundary-stop") return await resetBoundaryResult(entries, ctx, decision.effect === "commit-boundary", decision.lastWord, decision.origin ?? "forced");
298
275
  return entries.length > 0 ? { entries } : undefined;
299
276
  });
300
277
 
@@ -314,7 +291,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
314
291
  control = decision.state;
315
292
  if (decision.effect === "stop") return { entries: event.entries, continue: false };
316
293
  if (decision.effect !== "commit-boundary" && decision.effect !== "commit-boundary-stop" && decision.effect !== "recover-overflow") return undefined;
317
- return await resetBoundaryResult(event.entries, ctx, decision.effect !== "commit-boundary-stop", decision.prompt, decision.lastWord);
294
+ return await resetBoundaryResult(event.entries, ctx, decision.effect !== "commit-boundary-stop", decision.lastWord, decision.origin ?? "forced");
318
295
  });
319
296
 
320
297
  pi.on("session_before_compact", (event, ctx) => {
@@ -341,8 +318,8 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
341
318
  pi.on("session_shutdown", () => { lifecycleGeneration++; clear(); options.budget.clear(); sessionActive = false; });
342
319
 
343
320
  return {
344
- closeOut(windowId: string, source: ResetRequestSource, prompt?: string) {
345
- const decision = reduceResetControl(control, { type: "close_out", windowId, source, prompt });
321
+ command(windowId: string, continueAfterReset: boolean) {
322
+ const decision = reduceResetControl(control, { type: "command", windowId, continueAfterReset });
346
323
  control = decision.state;
347
324
  return decision.effect;
348
325
  },
package/src/pi/runtime.ts CHANGED
@@ -8,8 +8,9 @@ import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, i
8
8
  import { registerResetLifecycle } from "./reset/lifecycle.js";
9
9
  import { buildResetDrafts, LAST_WORD_PREFIX, MAX_LAST_WORD_CHARS, repairResetTail, sanitizeLastWord } from "./reset/artifacts.js";
10
10
  import { BOOT_TYPE, MANUAL_WIPE_TYPE, RESET_LAST_WORD_TYPE } from "./entries.js";
11
- import { WARNING_CONTENT } from "../budget/text.js";
11
+ import { warningContent } from "../budget/text.js";
12
12
  import { buildBootMessage, sendBoot, type IncompleteNotesNotifier } from "./boot.js";
13
+ import { nextHistorySeq } from "./history.js";
13
14
  import { errorMessage } from "../error-message.js";
14
15
 
15
16
  function readPackageVersion(): string {
@@ -48,7 +49,7 @@ async function ensureBoot(
48
49
  return;
49
50
  }
50
51
  if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId))) return;
51
- const boot = await buildBootMessage(ctx, windowId, undefined, notifyIncompleteNotes, stillCurrent);
52
+ const boot = await buildBootMessage(ctx, windowId, nextHistorySeq(ctx), notifyIncompleteNotes, stillCurrent);
52
53
  if (!stillCurrent()) return;
53
54
  if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId))) return;
54
55
  sendBoot(pi, boot);
@@ -182,14 +183,14 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
182
183
  // steered into the running turn when busy — so the agent closes out promptly
183
184
  // instead of the reset waiting for the whole run.
184
185
  const prompt = args.trim() || undefined;
185
- const armed = resets.closeOut(requestedWindowId, "manual", prompt);
186
+ const armed = resets.command(requestedWindowId, prompt !== undefined);
186
187
  if (armed === "already-pending") {
187
188
  cmdCtx.ui.notify("🥣 Brain already being emptied", "info");
188
189
  return;
189
190
  }
190
191
  cmdCtx.ui.notify("🥣 Brain being emptied", "info");
191
192
  try {
192
- pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: WARNING_CONTENT, display: false }, { triggerTurn: true, deliverAs: "steer" });
193
+ pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: warningContent(prompt ? `/empty-brain ${prompt}` : undefined), display: false }, { triggerTurn: true, deliverAs: "steer" });
193
194
  } catch (error) {
194
195
  resets.clear();
195
196
  cmdCtx.ui.notify(`🥣 Brain refused to empty: ${errorMessage(error)}`, "error");
@@ -215,7 +216,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
215
216
 
216
217
  const resets = registerResetLifecycle(pi, {
217
218
  isEnabled: () => enabled,
218
- buildReset: (ctx, isCurrent, prompt, lastWord) => buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent, prompt, lastWord),
219
+ buildReset: (ctx, isCurrent, lastWord, firstSeq, origin) => buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent, lastWord, firstSeq, origin),
219
220
  getLifecycleGeneration: () => lifecycleGeneration,
220
221
  onResetReady: (_ctx, drafts) => {
221
222
  const boot = drafts.find((draft) => draft.type === "custom_message" && draft.customType === BOOT_TYPE);
@@ -226,5 +227,4 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
226
227
  },
227
228
  budget,
228
229
  });
229
- budget.setCloseOut((windowId) => resets.closeOut(windowId, "automatic"));
230
230
  }
package/src/pi/window.ts CHANGED
@@ -3,9 +3,11 @@ import { getCurrentSystemMessage } from "@earendil-works/pi-ai";
3
3
  import { estimateContextTokens } from "./estimate.js";
4
4
  import { convertToLlm, type CustomEntry, type ExtensionContext, type SessionEntry } from "@earendil-works/pi-coding-agent";
5
5
  import { BOOT_TYPE, RESET_MARKER_TYPE } from "./entries.js";
6
+ import type { ResetOrigin } from "../budget/text.js";
6
7
  import type { SessionReader } from "./session-reader.js";
7
8
 
8
- export type WindowMarker = CustomEntry<{ windowId: string }> & { data: { windowId: string } };
9
+ export type WindowMarkerData = { readonly windowId: string; readonly origin?: ResetOrigin };
10
+ export type WindowMarker = CustomEntry<WindowMarkerData> & { data: WindowMarkerData };
9
11
 
10
12
  export function isWindowMarker(entry: SessionEntry): entry is WindowMarker {
11
13
  return entry.type === "custom" && entry.customType === RESET_MARKER_TYPE &&
@@ -14,6 +16,14 @@ export function isWindowMarker(entry: SessionEntry): entry is WindowMarker {
14
16
  (entry.data as { windowId: string }).windowId.length > 0;
15
17
  }
16
18
 
19
+ /**
20
+ * The origin a marker records for missing-tail repair. A marker written before the fact was
21
+ * carried, or with an unreadable one, was the model's own reset.
22
+ */
23
+ export function markerResetOrigin(marker: WindowMarker): ResetOrigin {
24
+ return marker.data.origin === "forced" ? "forced" : "normal";
25
+ }
26
+
17
27
  /** Only the active branch can supply a window boundary. */
18
28
  export function currentReset(ctx: SessionReader): WindowMarker | undefined {
19
29
  const branch = ctx.sessionManager.getBranch();