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
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("🥣 Context almost full · saving notes before memory clears", "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":
@@ -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(`🥣 Couldn't clear memory: ${errorMessage(error)}${prompt ? " · your prompt was 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) => {
@@ -323,7 +300,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
323
300
  const markerExists = currentReset(ctx) !== undefined;
324
301
  if (options.isEnabled() || markerExists) {
325
302
  if (event.reason === "manual") {
326
- ctx.ui.notify("🥣 /compact is off while notesoup is on · use /fresh-window", "warning");
303
+ ctx.ui.notify("🥣 No compacting brains here · use /fresh-window", "warning");
327
304
  }
328
305
  return { cancel: true };
329
306
  }
@@ -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
@@ -6,10 +6,11 @@ import { registerBudget } from "./budget.js";
6
6
  import { output } from "./tool-result.js";
7
7
  import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, projectRootWindow, projectWindow, rootWindowId, type WindowMarker } from "./window.js";
8
8
  import { registerResetLifecycle } from "./reset/lifecycle.js";
9
- import { buildResetDrafts, MAX_LAST_WORD_CHARS, repairResetTail, sanitizeLastWord } from "./reset/artifacts.js";
10
- import { BOOT_TYPE, MANUAL_WIPE_TYPE } from "./entries.js";
11
- import { WARNING_CONTENT } from "../budget/text.js";
9
+ import { buildResetDrafts, LAST_WORD_PREFIX, MAX_LAST_WORD_CHARS, repairResetTail, sanitizeLastWord } from "./reset/artifacts.js";
10
+ import { BOOT_TYPE, MANUAL_WIPE_TYPE, RESET_LAST_WORD_TYPE } from "./entries.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);
@@ -71,7 +72,10 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
71
72
  const marker = branch.find((entry): entry is WindowMarker => isWindowMarker(entry) && entry.data.windowId === windowId);
72
73
  if (!marker || !isCheckpointBackedReset(ctx, marker) || !resetBoundaryCommitted(ctx, marker.id, windowId)) continue;
73
74
  pendingResetNotices.delete(windowId);
74
- ctx.ui.notify("🥣 Memory cleared", "info");
75
+ const tail = branch.slice(branch.indexOf(marker) + 1);
76
+ const lastWordEntry = tail.find((entry) => (entry as { customType?: string }).customType === RESET_LAST_WORD_TYPE) as { content?: string } | undefined;
77
+ const lastWord = lastWordEntry?.content?.startsWith(LAST_WORD_PREFIX) ? lastWordEntry.content.slice(LAST_WORD_PREFIX.length) : undefined;
78
+ ctx.ui.notify(`🥣 Brain emptied${lastWord ? ` · last word: “${lastWord}”` : ""}`, "info");
75
79
  }
76
80
  };
77
81
  pi.on("turn_start", (_event, ctx) => notifyCommittedResets(ctx));
@@ -83,7 +87,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
83
87
  if (snapshot.unavailable.length === 0 || incompleteNotesNotified.has(windowId)) return;
84
88
  incompleteNotesNotified.add(windowId);
85
89
  const homes = snapshot.unavailable.map((home) => home.label).join(", ");
86
- ctx.ui.notify(`🥣 Some notes didn't load: ${homes}`, "warning");
90
+ ctx.ui.notify(`🥣 Some notes went missing: ${homes}`, "warning");
87
91
  };
88
92
  const budget = registerBudget(pi, () => enabled, settingsManager);
89
93
 
@@ -110,7 +114,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
110
114
  pi.on("session_before_tree", (event, ctx) => {
111
115
  if (!event.preparation.userWantsSummary) return undefined;
112
116
  if (!branchHasWindowMarker(ctx) && !branchHasWindowMarker(ctx, event.preparation.targetId)) return undefined;
113
- ctx.ui.notify("🥣 Branch summary skipped · it would bring back cleared memory", "info");
117
+ ctx.ui.notify("🥣 Branch summary skipped · it remembers too much", "info");
114
118
  return { summary: { summary: "" } };
115
119
  });
116
120
 
@@ -128,7 +132,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
128
132
  } catch (error) {
129
133
  if (missingBootNotice !== windowId) {
130
134
  missingBootNotice = windowId;
131
- ctx.ui.notify("🥣 Request cancelled · this memory window is broken, run /fresh-window", "error");
135
+ ctx.ui.notify("🥣 Request cancelled · brain is broken, run /fresh-window", "error");
132
136
  }
133
137
  ctx.abort();
134
138
  const safeHead = getCurrentSystemMessage(event.messages);
@@ -167,7 +171,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
167
171
  description: "Flush memory to notes and continue in a fresh window; optional prompt runs there",
168
172
  handler: async (args: string, cmdCtx: ExtensionCommandContext) => {
169
173
  if (!enabled) {
170
- cmdCtx.ui.notify("🥣 notesoup is off · run /notesoup on first", "error");
174
+ cmdCtx.ui.notify("🥣 notesoup is off · no brain to empty", "error");
171
175
  return;
172
176
  }
173
177
  const requestedWindowId = currentWindowId(cmdCtx);
@@ -179,19 +183,17 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
179
183
  // steered into the running turn when busy — so the agent closes out promptly
180
184
  // instead of the reset waiting for the whole run.
181
185
  const prompt = args.trim() || undefined;
182
- const armed = resets.closeOut(requestedWindowId, "manual", prompt);
186
+ const armed = resets.command(requestedWindowId, prompt !== undefined);
183
187
  if (armed === "already-pending") {
184
- cmdCtx.ui.notify("🥣 Empty brain already queued · the first prompt is kept", "info");
188
+ cmdCtx.ui.notify("🥣 Brain already being emptied", "info");
185
189
  return;
186
190
  }
187
- cmdCtx.ui.notify(prompt
188
- ? "🥣 Clearing memory · notes first, then your prompt runs"
189
- : "🥣 Clearing memory · notes first, then it stops", "info");
191
+ cmdCtx.ui.notify("🥣 Brain being emptied", "info");
190
192
  try {
191
- 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" });
192
194
  } catch (error) {
193
195
  resets.clear();
194
- cmdCtx.ui.notify(`🥣 Couldn't start /fresh-window: ${errorMessage(error)}`, "error");
196
+ cmdCtx.ui.notify(`🥣 Brain refused to empty: ${errorMessage(error)}`, "error");
195
197
  }
196
198
  },
197
199
  };
@@ -214,7 +216,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
214
216
 
215
217
  const resets = registerResetLifecycle(pi, {
216
218
  isEnabled: () => enabled,
217
- 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),
218
220
  getLifecycleGeneration: () => lifecycleGeneration,
219
221
  onResetReady: (_ctx, drafts) => {
220
222
  const boot = drafts.find((draft) => draft.type === "custom_message" && draft.customType === BOOT_TYPE);
@@ -225,5 +227,4 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
225
227
  },
226
228
  budget,
227
229
  });
228
- budget.setCloseOut((windowId) => resets.closeOut(windowId, "automatic"));
229
230
  }