notesoup 0.47.1 → 0.48.1

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 (88) hide show
  1. package/README.md +2 -2
  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 +60 -13
  6. package/dist/src/budget/constants.d.ts +2 -4
  7. package/dist/src/budget/constants.js +2 -4
  8. package/dist/src/budget/policy.d.ts +2 -2
  9. package/dist/src/budget/policy.js +3 -3
  10. package/dist/src/budget/text.d.ts +29 -9
  11. package/dist/src/budget/text.js +51 -10
  12. package/dist/src/claude/helper.d.ts +2 -3
  13. package/dist/src/claude/helper.js +45 -11
  14. package/dist/src/claude/history.d.ts +9 -0
  15. package/dist/src/claude/history.js +271 -0
  16. package/dist/src/dsh/budget.js +1 -1
  17. package/dist/src/dsh/engine.d.ts +2 -1
  18. package/dist/src/dsh/engine.js +18 -9
  19. package/dist/src/dsh/index.js +9 -4
  20. package/dist/src/dsh/tools.js +1 -1
  21. package/dist/src/dsh/window.d.ts +2 -1
  22. package/dist/src/dsh/window.js +14 -8
  23. package/dist/src/history/query.js +59 -81
  24. package/dist/src/notes/address.d.ts +5 -0
  25. package/dist/src/notes/address.js +20 -21
  26. package/dist/src/notes/store.js +12 -19
  27. package/dist/src/pi/boot.d.ts +1 -1
  28. package/dist/src/pi/boot.js +28 -5
  29. package/dist/src/pi/budget.d.ts +1 -3
  30. package/dist/src/pi/budget.js +20 -61
  31. package/dist/src/pi/entries.d.ts +0 -1
  32. package/dist/src/pi/entries.js +0 -1
  33. package/dist/src/pi/history.d.ts +3 -0
  34. package/dist/src/pi/history.js +4 -0
  35. package/dist/src/pi/reset/artifacts.d.ts +7 -2
  36. package/dist/src/pi/reset/artifacts.js +16 -14
  37. package/dist/src/pi/reset/lifecycle.d.ts +21 -25
  38. package/dist/src/pi/reset/lifecycle.js +48 -72
  39. package/dist/src/pi/runtime.js +9 -8
  40. package/dist/src/pi/window.d.ts +12 -6
  41. package/dist/src/pi/window.js +7 -0
  42. package/dist/test/agent-loop.test.js +53 -30
  43. package/dist/test/boot.integration.test.js +123 -12
  44. package/dist/test/budget-settings.integration.test.js +10 -6
  45. package/dist/test/claude-history.test.d.ts +1 -0
  46. package/dist/test/claude-history.test.js +184 -0
  47. package/dist/test/claude-mod.test.js +236 -42
  48. package/dist/test/dsh.test.js +80 -3
  49. package/dist/test/helpers/extension.d.ts +3 -0
  50. package/dist/test/helpers/extension.js +33 -5
  51. package/dist/test/history.integration.test.js +66 -0
  52. package/dist/test/host-neutral.test.js +1 -1
  53. package/dist/test/model-facing-text.test.d.ts +1 -0
  54. package/dist/test/model-facing-text.test.js +181 -0
  55. package/dist/test/notes.integration.test.js +16 -18
  56. package/dist/test/reset-lifecycle.test.js +201 -46
  57. package/docs/architecture.md +3 -3
  58. package/docs/claude-code-mod.md +15 -3
  59. package/docs/dsh.md +2 -2
  60. package/docs/reset-lifecycle.md +32 -20
  61. package/docs/skills.md +1 -1
  62. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  63. package/mods/notesoup/dist/claude/helper.js +836 -92
  64. package/mods/notesoup/hooks/register.ts +140 -38
  65. package/package.json +1 -1
  66. package/src/boot/render.ts +41 -23
  67. package/src/boot/text.ts +69 -13
  68. package/src/budget/constants.ts +2 -4
  69. package/src/budget/policy.ts +3 -3
  70. package/src/budget/text.ts +61 -10
  71. package/src/claude/helper.ts +53 -22
  72. package/src/claude/history.ts +228 -0
  73. package/src/dsh/budget.ts +1 -1
  74. package/src/dsh/engine.ts +16 -9
  75. package/src/dsh/index.ts +8 -3
  76. package/src/dsh/tools.ts +1 -1
  77. package/src/dsh/window.ts +15 -9
  78. package/src/history/query.ts +57 -82
  79. package/src/notes/address.ts +19 -16
  80. package/src/notes/store.ts +9 -14
  81. package/src/pi/boot.ts +27 -5
  82. package/src/pi/budget.ts +20 -58
  83. package/src/pi/entries.ts +0 -1
  84. package/src/pi/history.ts +7 -2
  85. package/src/pi/reset/artifacts.ts +17 -14
  86. package/src/pi/reset/lifecycle.ts +56 -79
  87. package/src/pi/runtime.ts +9 -8
  88. package/src/pi/window.ts +11 -1
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { BOOT_TYPE, CONTINUATION_TYPE, RESET_LAST_WORD_TYPE, RESET_MARKER_TYPE, RESET_PROMPT_TYPE } from "../entries.js";
3
- import { CONTINUATION } from "../../budget/text.js";
4
- import { currentWindowId, isForeignResetTailEntry, isWindowBootEntry, isWindowMarker, previousWindowId } from "../window.js";
2
+ import { BOOT_TYPE, CONTINUATION_TYPE, RESET_LAST_WORD_TYPE, RESET_MARKER_TYPE } from "../entries.js";
3
+ import { selectContinuation } from "../../budget/text.js";
4
+ import { isForeignResetTailEntry, isWindowBootEntry, isWindowMarker, markerResetOrigin } from "../window.js";
5
5
  import { buildBootMessage, sendBoot } from "../boot.js";
6
6
  /** A sticky note, not a letter: over this, empty_brain refuses instead of truncating. */
7
7
  export const MAX_LAST_WORD_CHARS = 250;
@@ -16,30 +16,32 @@ export function isWindowContinuationEntry(entry) {
16
16
  return entry.type === "custom_message" && entry.customType === CONTINUATION_TYPE;
17
17
  }
18
18
  /** The single continuation sender: the only reset prose persisted for a window. */
19
- function sendContinuation(pi) {
20
- pi.sendMessage({ customType: CONTINUATION_TYPE, content: CONTINUATION, display: false }, { triggerTurn: false });
19
+ function sendContinuation(pi, content) {
20
+ pi.sendMessage({ customType: CONTINUATION_TYPE, content, display: false }, { triggerTurn: false });
21
21
  }
22
22
  /**
23
23
  * The closed, ordered reset shape: retain-none native checkpoint, marker, matching boot,
24
- * continuation, then an optional parting line and command prompt. The boot snapshot is acquired asynchronously after capturing this identity.
24
+ * continuation, then an optional parting line. The prompt is not persisted here — it reached the
25
+ * closing window inside the warning. The boot snapshot is acquired asynchronously after capturing
26
+ * this identity. The continuation is drawn from the pool its origin names, here, once: the caller
27
+ * persists the returned text and no read, render, or repair draws it again. The origin defaults to
28
+ * `normal`, the same reading a legacy marker with no origin gets.
25
29
  */
26
- export async function buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent = () => true, prompt, lastWord) {
30
+ export async function buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent = () => true, lastWord, firstSeq, origin = "normal") {
27
31
  const sessionId = ctx.sessionManager.getSessionId();
28
- const previousId = currentWindowId(ctx);
29
32
  const sessionPrefix = sessionId.slice(0, 8);
30
33
  const usedWindowIds = new Set(ctx.sessionManager.getBranch().filter(isWindowMarker).map((entry) => entry.data.windowId));
31
34
  let windowId;
32
35
  do {
33
36
  windowId = `pcw:${sessionPrefix}:${randomUUID().slice(0, 8)}`;
34
37
  } while (usedWindowIds.has(windowId));
35
- const boot = await buildBootMessage(ctx, windowId, previousId, notifyIncompleteNotes, isCurrent);
38
+ const boot = await buildBootMessage(ctx, windowId, firstSeq, notifyIncompleteNotes, isCurrent);
36
39
  return [
37
40
  { type: "compaction", summary: "", firstKeptEntryId: null },
38
- { type: "custom", customType: RESET_MARKER_TYPE, data: { windowId } },
41
+ { type: "custom", customType: RESET_MARKER_TYPE, data: { windowId, origin } },
39
42
  { type: "custom_message", customType: BOOT_TYPE, content: boot.content, display: false, details: { windowId } },
40
- { type: "custom_message", customType: CONTINUATION_TYPE, content: CONTINUATION, display: false },
43
+ { type: "custom_message", customType: CONTINUATION_TYPE, content: selectContinuation(origin), display: false },
41
44
  ...(lastWord ? [{ type: "custom_message", customType: RESET_LAST_WORD_TYPE, content: `${LAST_WORD_PREFIX}${lastWord}`, display: true }] : []),
42
- ...(prompt ? [{ type: "custom_message", customType: RESET_PROMPT_TYPE, content: prompt, display: true }] : []),
43
45
  ];
44
46
  }
45
47
  /**
@@ -80,7 +82,7 @@ export async function repairResetTail(pi, ctx, marker, notifyIncompleteNotes, is
80
82
  const tail = inspectResetTail(ctx, marker.id, marker.data.windowId);
81
83
  if (!tail || (tail.boot && tail.continuation))
82
84
  return;
83
- const boot = tail.boot ? undefined : await buildBootMessage(ctx, marker.data.windowId, previousWindowId(ctx, marker.id), notifyIncompleteNotes, isCurrent);
85
+ const boot = tail.boot ? undefined : await buildBootMessage(ctx, marker.data.windowId, undefined, notifyIncompleteNotes, isCurrent);
84
86
  if (!isCurrent())
85
87
  return;
86
88
  const latest = inspectResetTail(ctx, marker.id, marker.data.windowId);
@@ -89,5 +91,5 @@ export async function repairResetTail(pi, ctx, marker, notifyIncompleteNotes, is
89
91
  if (!latest.boot && boot)
90
92
  sendBoot(pi, boot);
91
93
  if (!latest.continuation && (latest.boot || boot))
92
- sendContinuation(pi);
94
+ sendContinuation(pi, selectContinuation(markerResetOrigin(marker)));
93
95
  }
@@ -1,4 +1,5 @@
1
1
  import type { ExtensionAPI, ExtensionContext, SessionBoundaryDraft } from "@earendil-works/pi-coding-agent";
2
+ import type { ResetOrigin } from "../../budget/text.js";
2
3
  type BudgetOwner = {
3
4
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
4
5
  hardReserveDue: (ctx: ExtensionContext) => boolean;
@@ -8,28 +9,27 @@ type BudgetOwner = {
8
9
  type ResetOptions = {
9
10
  isEnabled: () => boolean;
10
11
  budget: BudgetOwner;
11
- buildReset: (ctx: ExtensionContext, isCurrent: () => boolean, prompt?: string, lastWord?: string) => SessionBoundaryDraft[] | Promise<SessionBoundaryDraft[]>;
12
+ buildReset: (ctx: ExtensionContext, isCurrent: () => boolean, lastWord: string | undefined, firstSeq: number, origin: ResetOrigin) => SessionBoundaryDraft[] | Promise<SessionBoundaryDraft[]>;
12
13
  getLifecycleGeneration?: () => number;
13
14
  onResetReady?: (ctx: ExtensionContext, drafts: readonly SessionBoundaryDraft[]) => void;
14
15
  };
15
- export type ResetRequestSource = "manual" | "automatic";
16
- type ToolResetRequestSource = "automatic" | "tool";
17
16
  export type ResetRequest = {
18
17
  readonly phase: "none";
19
18
  } | {
20
19
  readonly phase: "stop-pending";
21
20
  readonly windowId: string;
21
+ readonly tool?: {
22
+ readonly lastWord?: string;
23
+ };
22
24
  } | {
23
- readonly phase: "close-out";
25
+ readonly phase: "pending";
24
26
  readonly windowId: string;
25
- readonly source: ResetRequestSource;
26
- readonly prompt?: string;
27
- readonly lastWord?: string;
28
- } | {
29
- readonly phase: "tool-requested";
30
- readonly windowId: string;
31
- readonly source: ToolResetRequestSource;
32
- readonly lastWord?: string;
27
+ readonly command?: {
28
+ readonly continueAfterReset: boolean;
29
+ };
30
+ readonly tool?: {
31
+ readonly lastWord?: string;
32
+ };
33
33
  };
34
34
  export type ResetOverflowPhase = "idle" | "pending" | "pending-spent" | "spent";
35
35
  export interface ResetControlState {
@@ -58,10 +58,9 @@ export interface ResetBeforeSettleFacts {
58
58
  readonly failed: boolean;
59
59
  }
60
60
  export type ResetControlEvent = {
61
- readonly type: "close_out";
61
+ readonly type: "command";
62
62
  readonly windowId: string;
63
- readonly source: ResetRequestSource;
64
- readonly prompt?: string;
63
+ readonly continueAfterReset: boolean;
65
64
  } | {
66
65
  readonly type: "tool_request";
67
66
  readonly windowId: string;
@@ -83,22 +82,19 @@ export type ResetControlEffect = "none" | "close-out-armed" | "already-pending"
83
82
  export interface ResetControlResult {
84
83
  readonly state: ResetControlState;
85
84
  readonly effect: ResetControlEffect;
86
- readonly prompt?: string;
87
85
  readonly lastWord?: string;
86
+ /** The origin of the boundary this decision commits. Absent means no `empty_brain` call was recorded, so forced. */
87
+ readonly origin?: ResetOrigin;
88
88
  }
89
- /** Pure reset-control transitions: request phases own close-out, tool commit, and fallback. */
89
+ /** Pure transitions: command policy schedules a reset without disguising actual tool calls. */
90
90
  export declare function reduceResetControl(state: ResetControlState, event: ResetControlEvent): ResetControlResult;
91
91
  /**
92
- * Own close-out requests at Pi's public turn and pre-settlement boundaries. Manual and budget
93
- * close-outs remain armed across note/tool turns. Only manual close-outs commit at a
94
- * successful agent_before_settle; budget warnings alone never authorize a reset.
95
- * A hard-reserve safety reset can commit earlier, but preserves a
96
- * run-scoped manual stop and cancels an otherwise automatic fresh-window request through
97
- * the public abort API. Direct tool requests commit at turn_end and continue normally.
98
- * Overflow recovery remains bounded.
92
+ * Tool-only requests commit at turn_end; command policy waits for settlement.
93
+ * Hard reserve may commit earlier while preserving a command's stop latch.
94
+ * Budget warnings carry no lifecycle state. Overflow recovery remains bounded.
99
95
  */
100
96
  export declare function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions): {
101
- closeOut(windowId: string, source: ResetRequestSource, prompt?: string): ResetControlEffect;
97
+ command(windowId: string, continueAfterReset: boolean): ResetControlEffect;
102
98
  request(windowId: string, lastWord?: string): "rollover_already_pending" | "rollover_requested";
103
99
  clear: () => void;
104
100
  };
@@ -1,5 +1,6 @@
1
1
  import { getCurrentSystemMessage, isContextOverflow, isRecoverableLength } from "@earendil-works/pi-ai";
2
2
  import { currentReset, currentWindowId } from "../window.js";
3
+ import { nextHistorySeq } from "../history.js";
3
4
  import { resetBoundaryCommitted } from "./committed.js";
4
5
  import { errorMessage } from "../../error-message.js";
5
6
  function isAbort(message, outcome, ctx) {
@@ -18,59 +19,37 @@ export function initialResetControl() {
18
19
  function requestForWindow(request, windowId) {
19
20
  return request.phase === "stop-pending" || (request.phase !== "none" && request.windowId === windowId) ? request : NO_REQUEST;
20
21
  }
21
- function manualCommit(prompt, lastWord) {
22
- const parting = lastWord ? { lastWord } : {};
23
- return prompt
24
- ? { state: initialResetControl(), effect: "commit-boundary", prompt, ...parting }
25
- : { state: initialResetControl(), effect: "commit-boundary-stop", ...parting };
22
+ function commandCommit(request) {
23
+ return {
24
+ state: initialResetControl(),
25
+ effect: request.command?.continueAfterReset ? "commit-boundary" : "commit-boundary-stop",
26
+ ...requestDetails(request),
27
+ };
26
28
  }
27
- /** The parting line rides either committing phase; other phases never carry one. */
28
- function requestLastWord(request) {
29
- return request.phase === "close-out" || request.phase === "tool-requested" ? request.lastWord : undefined;
29
+ /** The tool request itself is the origin fact; the stop latch retains it for construction retry. */
30
+ function requestDetails(request) {
31
+ const tool = request.phase === "none" ? undefined : request.tool;
32
+ return { origin: tool ? "normal" : "forced", ...tool };
30
33
  }
31
- /** Pure reset-control transitions: request phases own close-out, tool commit, and fallback. */
34
+ /** Pure transitions: command policy schedules a reset without disguising actual tool calls. */
32
35
  export function reduceResetControl(state, event) {
33
36
  switch (event.type) {
34
- case "close_out": {
35
- const request = state.request;
36
- const prompt = event.source === "manual" && event.prompt?.trim() ? { prompt: event.prompt.trim() } : {};
37
- if (request.phase === "stop-pending")
38
- return { state, effect: "already-pending" };
39
- if (request.phase === "tool-requested" && request.windowId === event.windowId) {
40
- // A manual wipe outranks a pending rollover: close out before committing.
41
- if (event.source === "manual") {
42
- return { state: { ...state, request: { phase: "close-out", windowId: event.windowId, source: "manual", ...prompt } }, effect: "close-out-armed" };
43
- }
44
- return { state, effect: "already-pending" };
45
- }
46
- if (request.phase === "close-out" && request.windowId === event.windowId) {
47
- if (request.source === "manual" || event.source === "automatic")
48
- return { state, effect: "already-pending" };
49
- return { state: { ...state, request: { ...request, source: "manual", ...prompt } }, effect: "close-out-armed" };
50
- }
51
- return { state: { ...state, request: { phase: "close-out", windowId: event.windowId, source: event.source, ...prompt } }, effect: "close-out-armed" };
52
- }
37
+ case "command":
53
38
  case "tool_request": {
54
- const request = state.request;
55
- if (request.phase === "stop-pending")
56
- return { state, effect: "already-pending" };
57
- if (request.phase === "tool-requested" && request.windowId === event.windowId) {
39
+ const current = requestForWindow(state.request, event.windowId);
40
+ if (current.phase === "stop-pending")
58
41
  return { state, effect: "already-pending" };
42
+ const request = current.phase === "pending" ? current : { phase: "pending", windowId: event.windowId };
43
+ if (event.type === "command") {
44
+ if (request.command)
45
+ return { state, effect: "already-pending" };
46
+ return { state: { ...state, request: { ...request, command: { continueAfterReset: event.continueAfterReset } } }, effect: "close-out-armed" };
59
47
  }
60
- const parting = event.lastWord ? { lastWord: event.lastWord } : {};
61
- // A manual close-out must settle so the stop actually lands; the agent's own wipe
62
- // call during one is only an acknowledgement, never a conversion to a turn-end
63
- // commit that pi's tool-batch continuation can overrun. A budget close-out still
64
- // upgrades: context pressure cannot wait for settlement.
65
- if (request.phase === "close-out" && request.windowId === event.windowId) {
66
- // The acknowledging call still contributes its last word; the manual commit keeps the wheel.
67
- if (request.source === "manual") {
68
- const lastWord = request.lastWord ?? event.lastWord;
69
- return { state: { ...state, request: { ...request, ...(lastWord ? { lastWord } : {}) } }, effect: "already-pending" };
70
- }
71
- return { state: { ...state, request: { phase: "tool-requested", windowId: event.windowId, source: "automatic", ...parting } }, effect: "close-out-armed" };
72
- }
73
- return { state: { ...state, request: { phase: "tool-requested", windowId: event.windowId, source: "tool", ...parting } }, effect: "close-out-armed" };
48
+ // The call remains a real request even when command policy delays its commit.
49
+ const duplicate = request.tool !== undefined;
50
+ const lastWord = request.tool?.lastWord ?? event.lastWord;
51
+ const tool = duplicate && !request.command ? request.tool : (lastWord ? { lastWord } : {});
52
+ return { state: { ...state, request: { ...request, tool } }, effect: duplicate ? "already-pending" : "close-out-armed" };
74
53
  }
75
54
  case "turn_end": {
76
55
  const facts = event.facts;
@@ -79,7 +58,7 @@ export function reduceResetControl(state, event) {
79
58
  return { state: initialResetControl(), effect: "none" };
80
59
  if (request.phase === "stop-pending")
81
60
  return { state: { request, overflow: "idle" }, effect: "none" };
82
- const manual = request.phase === "close-out" && request.source === "manual";
61
+ const manual = request.phase === "pending" && request.command !== undefined;
83
62
  if (facts.overflow) {
84
63
  const pending = manual ? facts.enabled : !facts.queued && facts.enabled && facts.automaticResetEnabled;
85
64
  const spent = state.overflow === "pending-spent" || state.overflow === "spent";
@@ -95,13 +74,12 @@ export function reduceResetControl(state, event) {
95
74
  }
96
75
  // A direct tool request commits after the whole tool batch. The budget cutoff is
97
76
  // a separate hard-reserve safety path; ordinary close-out waits for settlement.
98
- if (request.phase === "tool-requested" || facts.hardReserveDue) {
99
- const lastWord = requestLastWord(request);
100
- if (manual && request.prompt)
101
- return manualCommit(request.prompt, lastWord);
77
+ if ((request.phase === "pending" && request.tool && !manual) || facts.hardReserveDue) {
78
+ if (manual && request.command?.continueAfterReset)
79
+ return commandCommit(request);
102
80
  if (manual)
103
- return { state: { request: { phase: "stop-pending", windowId: facts.windowId }, overflow: "idle" }, effect: "commit-boundary-stop", ...(lastWord ? { lastWord } : {}) };
104
- return { state: { request: NO_REQUEST, overflow: "idle" }, effect: "commit-boundary", ...(lastWord ? { lastWord } : {}) };
81
+ return { state: { request: { phase: "stop-pending", windowId: facts.windowId, ...(request.tool ? { tool: request.tool } : {}) }, overflow: "idle" }, effect: "commit-boundary-stop", ...requestDetails(request) };
82
+ return { state: { request: NO_REQUEST, overflow: "idle" }, effect: "commit-boundary", ...requestDetails(request) };
105
83
  }
106
84
  return { state: { request, overflow: "idle" }, effect: "none" };
107
85
  }
@@ -117,9 +95,9 @@ export function reduceResetControl(state, event) {
117
95
  // stop without a second wipe, even if a queued turn subsequently failed.
118
96
  if (request.windowId !== facts.windowId)
119
97
  return { state: initialResetControl(), effect: "stop" };
120
- return { state: initialResetControl(), effect: facts.failed || !facts.enabled ? "none" : "commit-boundary-stop" };
98
+ return { state: initialResetControl(), effect: facts.failed || !facts.enabled ? "none" : "commit-boundary-stop", ...requestDetails(request) };
121
99
  }
122
- const manual = request.phase === "close-out" && request.source === "manual";
100
+ const manual = request.phase === "pending" && request.command !== undefined;
123
101
  if (state.overflow === "pending" || state.overflow === "pending-spent") {
124
102
  if (facts.queued) {
125
103
  return { state: { ...state, request: facts.failed && !manual ? NO_REQUEST : request }, effect: "none" };
@@ -127,19 +105,19 @@ export function reduceResetControl(state, event) {
127
105
  // An explicit manual wipe is not an automatic recovery/retry. It must still
128
106
  // clear on overflow, including when automatic reset is disabled.
129
107
  if (manual && facts.enabled)
130
- return manualCommit(request.prompt, requestLastWord(request));
108
+ return commandCommit(request);
131
109
  const spent = state.overflow === "pending-spent";
132
110
  if (!facts.enabled || !facts.automaticResetEnabled) {
133
111
  return { state: { request: facts.failed ? NO_REQUEST : request, overflow: spent ? "spent" : "idle" }, effect: "none" };
134
112
  }
135
- return { state: { request: NO_REQUEST, overflow: "spent" }, effect: spent ? "none" : "recover-overflow" };
113
+ return { state: { request: NO_REQUEST, overflow: "spent" }, effect: spent ? "none" : "recover-overflow", ...requestDetails(request) };
136
114
  }
137
115
  if (facts.failed || !facts.enabled || !manual) {
138
116
  return { state: { ...state, request: NO_REQUEST }, effect: "none" };
139
117
  }
140
118
  if (facts.queued)
141
119
  return { state: { ...state, request }, effect: "none" };
142
- return manualCommit(request.prompt, requestLastWord(request));
120
+ return commandCommit(request);
143
121
  }
144
122
  case "settled":
145
123
  return { state: initialResetControl(), effect: "none" };
@@ -149,20 +127,16 @@ export function reduceResetControl(state, event) {
149
127
  }
150
128
  }
151
129
  /**
152
- * Own close-out requests at Pi's public turn and pre-settlement boundaries. Manual and budget
153
- * close-outs remain armed across note/tool turns. Only manual close-outs commit at a
154
- * successful agent_before_settle; budget warnings alone never authorize a reset.
155
- * A hard-reserve safety reset can commit earlier, but preserves a
156
- * run-scoped manual stop and cancels an otherwise automatic fresh-window request through
157
- * the public abort API. Direct tool requests commit at turn_end and continue normally.
158
- * Overflow recovery remains bounded.
130
+ * Tool-only requests commit at turn_end; command policy waits for settlement.
131
+ * Hard reserve may commit earlier while preserving a command's stop latch.
132
+ * Budget warnings carry no lifecycle state. Overflow recovery remains bounded.
159
133
  */
160
134
  export function registerResetLifecycle(pi, options) {
161
135
  let sessionActive = true;
162
136
  let lifecycleGeneration = 0;
163
137
  let control = initialResetControl();
164
138
  const clear = () => { control = reduceResetControl(control, { type: "clear" }).state; };
165
- const resetBoundaryResult = async (entries, ctx, continueAfterReset, prompt, lastWord) => {
139
+ const resetBoundaryResult = async (entries, ctx, continueAfterReset, lastWord, origin) => {
166
140
  const generation = lifecycleGeneration;
167
141
  const outerGeneration = options.getLifecycleGeneration?.();
168
142
  const sessionId = ctx.sessionManager.getSessionId();
@@ -170,13 +144,15 @@ export function registerResetLifecycle(pi, options) {
170
144
  const isCurrent = () => sessionActive && lifecycleGeneration === generation &&
171
145
  (outerGeneration === undefined || options.getLifecycleGeneration?.() === outerGeneration) && options.isEnabled() &&
172
146
  ctx.signal?.aborted !== true && ctx.sessionManager.getSessionId() === sessionId && currentWindowId(ctx) === windowId;
147
+ // The retain-none checkpoint belongs to the old window; capture its successor before notes await.
148
+ const firstSeq = nextHistorySeq(ctx, entries) + 1;
173
149
  let resetDrafts;
174
150
  try {
175
- resetDrafts = await options.buildReset(ctx, isCurrent, prompt, lastWord);
151
+ resetDrafts = await options.buildReset(ctx, isCurrent, lastWord, firstSeq, origin);
176
152
  }
177
153
  catch (error) {
178
154
  if (isCurrent())
179
- ctx.ui.notify(`🥣 Brain still full: ${errorMessage(error)}${prompt ? " · prompt not sent" : ""}`, "warning");
155
+ ctx.ui.notify(`🥣 Brain still full: ${errorMessage(error)}`, "warning");
180
156
  return entries.length > 0 ? { entries } : undefined;
181
157
  }
182
158
  if (!isCurrent())
@@ -224,7 +200,7 @@ export function registerResetLifecycle(pi, options) {
224
200
  });
225
201
  control = decision.state;
226
202
  if (decision.effect === "commit-boundary" || decision.effect === "commit-boundary-stop")
227
- return await resetBoundaryResult(entries, ctx, decision.effect === "commit-boundary", decision.prompt, decision.lastWord);
203
+ return await resetBoundaryResult(entries, ctx, decision.effect === "commit-boundary", decision.lastWord, decision.origin ?? "forced");
228
204
  return entries.length > 0 ? { entries } : undefined;
229
205
  });
230
206
  pi.on("agent_before_settle", async (event, ctx) => {
@@ -246,7 +222,7 @@ export function registerResetLifecycle(pi, options) {
246
222
  return { entries: event.entries, continue: false };
247
223
  if (decision.effect !== "commit-boundary" && decision.effect !== "commit-boundary-stop" && decision.effect !== "recover-overflow")
248
224
  return undefined;
249
- return await resetBoundaryResult(event.entries, ctx, decision.effect !== "commit-boundary-stop", decision.prompt, decision.lastWord);
225
+ return await resetBoundaryResult(event.entries, ctx, decision.effect !== "commit-boundary-stop", decision.lastWord, decision.origin ?? "forced");
250
226
  });
251
227
  pi.on("session_before_compact", (event, ctx) => {
252
228
  if (!sessionActive)
@@ -273,8 +249,8 @@ export function registerResetLifecycle(pi, options) {
273
249
  pi.on("session_tree", () => { lifecycleGeneration++; clear(); });
274
250
  pi.on("session_shutdown", () => { lifecycleGeneration++; clear(); options.budget.clear(); sessionActive = false; });
275
251
  return {
276
- closeOut(windowId, source, prompt) {
277
- const decision = reduceResetControl(control, { type: "close_out", windowId, source, prompt });
252
+ command(windowId, continueAfterReset) {
253
+ const decision = reduceResetControl(control, { type: "command", windowId, continueAfterReset });
278
254
  control = decision.state;
279
255
  return decision.effect;
280
256
  },
@@ -4,12 +4,13 @@ import { getCurrentSystemMessage, Type } from "@earendil-works/pi-ai";
4
4
  import { VERSION, defineTool } from "@earendil-works/pi-coding-agent";
5
5
  import { registerBudget } from "./budget.js";
6
6
  import { output } from "./tool-result.js";
7
- import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, projectRootWindow, projectWindow, rootWindowId } from "./window.js";
7
+ import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, markerResetOrigin, projectRootWindow, projectWindow, rootWindowId } from "./window.js";
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 } from "./boot.js";
13
+ import { nextHistorySeq } from "./history.js";
13
14
  import { errorMessage } from "../error-message.js";
14
15
  function readPackageVersion() {
15
16
  for (const up of ["../../package.json", "../../../package.json"]) {
@@ -44,7 +45,7 @@ async function ensureBoot(pi, ctx, notifyIncompleteNotes, isCurrent = () => true
44
45
  }
45
46
  if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId)))
46
47
  return;
47
- const boot = await buildBootMessage(ctx, windowId, undefined, notifyIncompleteNotes, stillCurrent);
48
+ const boot = await buildBootMessage(ctx, windowId, nextHistorySeq(ctx), notifyIncompleteNotes, stillCurrent);
48
49
  if (!stillCurrent())
49
50
  return;
50
51
  if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId)))
@@ -74,7 +75,8 @@ export function registerContext(pi, settingsManager) {
74
75
  const tail = branch.slice(branch.indexOf(marker) + 1);
75
76
  const lastWordEntry = tail.find((entry) => entry.customType === RESET_LAST_WORD_TYPE);
76
77
  const lastWord = lastWordEntry?.content?.startsWith(LAST_WORD_PREFIX) ? lastWordEntry.content.slice(LAST_WORD_PREFIX.length) : undefined;
77
- ctx.ui.notify(`🥣 Brain emptied${lastWord ? ` · last word: “${lastWord}”` : ""}`, "info");
78
+ const forced = markerResetOrigin(marker) === "forced";
79
+ ctx.ui.notify(`🥣 Brain emptied${forced ? " forcibly: overflow" : ""}${lastWord ? ` · last word: “${lastWord}”` : ""}`, forced ? "warning" : "info");
78
80
  }
79
81
  };
80
82
  pi.on("turn_start", (_event, ctx) => notifyCommittedResets(ctx));
@@ -186,14 +188,14 @@ export function registerContext(pi, settingsManager) {
186
188
  // steered into the running turn when busy — so the agent closes out promptly
187
189
  // instead of the reset waiting for the whole run.
188
190
  const prompt = args.trim() || undefined;
189
- const armed = resets.closeOut(requestedWindowId, "manual", prompt);
191
+ const armed = resets.command(requestedWindowId, prompt !== undefined);
190
192
  if (armed === "already-pending") {
191
193
  cmdCtx.ui.notify("🥣 Brain already being emptied", "info");
192
194
  return;
193
195
  }
194
196
  cmdCtx.ui.notify("🥣 Brain being emptied", "info");
195
197
  try {
196
- pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: WARNING_CONTENT, display: false }, { triggerTurn: true, deliverAs: "steer" });
198
+ pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: warningContent(prompt ? `/empty-brain ${prompt}` : undefined), display: false }, { triggerTurn: true, deliverAs: "steer" });
197
199
  }
198
200
  catch (error) {
199
201
  resets.clear();
@@ -220,7 +222,7 @@ export function registerContext(pi, settingsManager) {
220
222
  }));
221
223
  const resets = registerResetLifecycle(pi, {
222
224
  isEnabled: () => enabled,
223
- buildReset: (ctx, isCurrent, prompt, lastWord) => buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent, prompt, lastWord),
225
+ buildReset: (ctx, isCurrent, lastWord, firstSeq, origin) => buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent, lastWord, firstSeq, origin),
224
226
  getLifecycleGeneration: () => lifecycleGeneration,
225
227
  onResetReady: (_ctx, drafts) => {
226
228
  const boot = drafts.find((draft) => draft.type === "custom_message" && draft.customType === BOOT_TYPE);
@@ -232,5 +234,4 @@ export function registerContext(pi, settingsManager) {
232
234
  },
233
235
  budget,
234
236
  });
235
- budget.setCloseOut((windowId) => resets.closeOut(windowId, "automatic"));
236
237
  }
@@ -1,14 +1,20 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import { type CustomEntry, type ExtensionContext, type SessionEntry } from "@earendil-works/pi-coding-agent";
3
+ import type { ResetOrigin } from "../budget/text.js";
3
4
  import type { SessionReader } from "./session-reader.js";
4
- export type WindowMarker = CustomEntry<{
5
- windowId: string;
6
- }> & {
7
- data: {
8
- windowId: string;
9
- };
5
+ export type WindowMarkerData = {
6
+ readonly windowId: string;
7
+ readonly origin?: ResetOrigin;
8
+ };
9
+ export type WindowMarker = CustomEntry<WindowMarkerData> & {
10
+ data: WindowMarkerData;
10
11
  };
11
12
  export declare function isWindowMarker(entry: SessionEntry): entry is WindowMarker;
13
+ /**
14
+ * The origin a marker records for missing-tail repair. A marker written before the fact was
15
+ * carried, or with an unreadable one, was the model's own reset.
16
+ */
17
+ export declare function markerResetOrigin(marker: WindowMarker): ResetOrigin;
12
18
  /** Only the active branch can supply a window boundary. */
13
19
  export declare function currentReset(ctx: SessionReader): WindowMarker | undefined;
14
20
  /** A reset is checkpoint-backed only when its marker directly follows a native compaction. */
@@ -8,6 +8,13 @@ export function isWindowMarker(entry) {
8
8
  typeof entry.data.windowId === "string" &&
9
9
  entry.data.windowId.length > 0;
10
10
  }
11
+ /**
12
+ * The origin a marker records for missing-tail repair. A marker written before the fact was
13
+ * carried, or with an unreadable one, was the model's own reset.
14
+ */
15
+ export function markerResetOrigin(marker) {
16
+ return marker.data.origin === "forced" ? "forced" : "normal";
17
+ }
11
18
  /** Only the active branch can supply a window boundary. */
12
19
  export function currentReset(ctx) {
13
20
  const branch = ctx.sessionManager.getBranch();