notesoup 0.51.2 → 0.51.3

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.
@@ -16,12 +16,6 @@ type ResetOptions = {
16
16
  };
17
17
  export type ResetRequest = {
18
18
  readonly phase: "none";
19
- } | {
20
- readonly phase: "stop-pending";
21
- readonly windowId: string;
22
- readonly tool?: {
23
- readonly lastWord?: string;
24
- };
25
19
  } | {
26
20
  readonly phase: "pending";
27
21
  readonly windowId: string;
@@ -36,6 +30,8 @@ export type ResetRequest = {
36
30
  export type ResetOverflowPhase = "idle" | "pending" | "pending-spent" | "spent";
37
31
  export interface ResetControlState {
38
32
  readonly request: ResetRequest;
33
+ /** Await settlement after a safety reset; retain its intent to retry if it never committed. */
34
+ readonly stopAfterReset?: ResetBoundaryIntent;
39
35
  readonly overflow: ResetOverflowPhase;
40
36
  }
41
37
  export declare function initialResetControl(): ResetControlState;
@@ -79,15 +75,34 @@ export type ResetControlEvent = {
79
75
  readonly type: "before_settle";
80
76
  readonly facts: ResetBeforeSettleFacts;
81
77
  };
82
- export type ResetControlEffect = "none" | "close-out-armed" | "already-pending" | "commit-boundary" | "commit-boundary-stop" | "stop" | "recover-overflow";
83
- export interface ResetControlResult {
84
- readonly state: ResetControlState;
85
- readonly effect: ResetControlEffect;
86
- readonly lastWord?: string;
87
- /** The origin of the boundary this decision commits. Absent means no `empty_brain` call was recorded, so forced. */
88
- readonly origin?: ResetOrigin;
78
+ /** Construction intent, not final state: handled inputs can still arrive while notes load. Only `turn-end`
79
+ * may latch a stop; overflow kinds spend recovery; only `overflow-recovery` carries passive run inputs. */
80
+ export interface ResetBoundaryIntent {
81
+ readonly effect: "build-boundary";
82
+ readonly boundary: "turn-end" | "settle" | "command-overflow" | "overflow-recovery";
83
+ readonly windowId: string;
84
+ readonly continueAfterReset: boolean;
85
+ readonly origin: ResetOrigin;
86
+ readonly tool?: {
87
+ readonly lastWord?: string;
88
+ };
89
89
  }
90
+ export type ResetControlResult = ResetBoundaryIntent | {
91
+ readonly state: ResetControlState;
92
+ readonly effect: "none" | "close-out-armed" | "already-pending" | "stop";
93
+ };
94
+ /** Resolve once, after a successful current build. No delivery policy is left to the adapter. */
95
+ export declare function finalizeResetBoundary(intent: ResetBoundaryIntent, request: ResetRequest, passiveInputs?: readonly CarriedInput[]): {
96
+ state: ResetControlState;
97
+ inputs: readonly (string | (import("@earendil-works/pi-ai").TextContent | import("@earendil-works/pi-ai").ImageContent)[])[];
98
+ resumeModel: boolean;
99
+ };
90
100
  /** Pure transitions: command policy schedules a reset without disguising actual tool calls. */
101
+ export declare function reduceResetControl(state: ResetControlState, event: Extract<ResetControlEvent, {
102
+ type: "input" | "command" | "tool_request";
103
+ }>): Extract<ResetControlResult, {
104
+ state: ResetControlState;
105
+ }>;
91
106
  export declare function reduceResetControl(state: ResetControlState, event: ResetControlEvent): ResetControlResult;
92
107
  /**
93
108
  * Tool-only requests commit at turn_end; command policy waits for settlement.
@@ -95,7 +110,7 @@ export declare function reduceResetControl(state: ResetControlState, event: Rese
95
110
  * Budget warnings carry no lifecycle state. Overflow recovery remains bounded.
96
111
  */
97
112
  export declare function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions): {
98
- command(windowId: string, continueAfterReset: boolean, input?: CarriedInput): ResetControlEffect;
113
+ command(windowId: string, continueAfterReset: boolean, input?: CarriedInput): "none" | "stop" | "close-out-armed" | "already-pending";
99
114
  request(windowId: string, lastWord?: string): "rollover_already_pending" | "rollover_requested";
100
115
  clear: (preserveInputs?: boolean) => void;
101
116
  };
@@ -21,25 +21,26 @@ export function initialResetControl() {
21
21
  return { request: NO_REQUEST, overflow: "idle" };
22
22
  }
23
23
  function requestForWindow(request, windowId) {
24
- return request.phase === "stop-pending" || (request.phase !== "none" && request.windowId === windowId) ? request : NO_REQUEST;
24
+ return request.phase === "pending" && request.windowId === windowId ? request : NO_REQUEST;
25
25
  }
26
- function commandContinues(request) {
27
- return request.command?.continueAfterReset === true || (request.command?.inputs?.length ?? 0) > 0;
26
+ const spendsOverflow = (boundary) => boundary === "command-overflow" || boundary === "overflow-recovery";
27
+ function boundaryIntent(request, windowId, boundary) {
28
+ const tool = request.phase === "none" ? undefined : request.tool;
29
+ const continueAfterReset = request.phase === "pending" ? request.command?.continueAfterReset ?? true : true;
30
+ return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal" };
28
31
  }
29
- function commandCommit(request, overflow = false) {
30
- return {
31
- state: { request: NO_REQUEST, overflow: overflow ? "spent" : "idle" },
32
- effect: commandContinues(request) ? "commit-boundary" : "commit-boundary-stop",
33
- ...requestDetails(request),
34
- ...(overflow ? { origin: "forced" } : {}),
32
+ /** Resolve once, after a successful current build. No delivery policy is left to the adapter. */
33
+ export function finalizeResetBoundary(intent, request, passiveInputs = []) {
34
+ const inputs = request.phase === "pending" && request.command ? request.command.inputs ?? []
35
+ : intent.boundary === "overflow-recovery" ? passiveInputs : [];
36
+ const resumeModel = intent.continueAfterReset || inputs.length > 0;
37
+ const state = {
38
+ request: NO_REQUEST,
39
+ ...(intent.boundary === "turn-end" && !resumeModel ? { stopAfterReset: intent } : {}),
40
+ overflow: spendsOverflow(intent.boundary) ? "spent" : "idle",
35
41
  };
42
+ return { state, inputs, resumeModel };
36
43
  }
37
- /** The tool request itself is the origin fact; the stop latch retains it for construction retry. */
38
- function requestDetails(request) {
39
- const tool = request.phase === "none" ? undefined : request.tool;
40
- return { origin: tool ? "normal" : "forced", ...tool };
41
- }
42
- /** Pure transitions: command policy schedules a reset without disguising actual tool calls. */
43
44
  export function reduceResetControl(state, event) {
44
45
  switch (event.type) {
45
46
  case "input": {
@@ -50,9 +51,9 @@ export function reduceResetControl(state, event) {
50
51
  }
51
52
  case "command":
52
53
  case "tool_request": {
53
- const current = requestForWindow(state.request, event.windowId);
54
- if (current.phase === "stop-pending")
54
+ if (state.stopAfterReset)
55
55
  return { state, effect: "already-pending" };
56
+ const current = requestForWindow(state.request, event.windowId);
56
57
  const request = current.phase === "pending" ? current : { phase: "pending", windowId: event.windowId };
57
58
  if (event.type === "command") {
58
59
  if (request.command)
@@ -70,8 +71,8 @@ export function reduceResetControl(state, event) {
70
71
  const request = requestForWindow(state.request, facts.windowId);
71
72
  if (facts.aborted)
72
73
  return { state: initialResetControl(), effect: "none" };
73
- if (request.phase === "stop-pending")
74
- return { state: { request, overflow: "idle" }, effect: "none" };
74
+ if (state.stopAfterReset)
75
+ return { state: { ...state, overflow: "idle" }, effect: "none" };
75
76
  const manual = request.phase === "pending" && request.command !== undefined;
76
77
  if (facts.overflow) {
77
78
  const pending = manual ? facts.enabled : !facts.queued && facts.enabled && facts.automaticResetEnabled;
@@ -89,11 +90,7 @@ export function reduceResetControl(state, event) {
89
90
  // A direct tool request commits after the whole tool batch. The budget cutoff is
90
91
  // a separate hard-reserve safety path; ordinary close-out waits for settlement.
91
92
  if ((request.phase === "pending" && request.tool && !manual) || facts.hardReserveDue) {
92
- if (manual && commandContinues(request))
93
- return commandCommit(request);
94
- if (manual)
95
- return { state: { request: { phase: "stop-pending", windowId: facts.windowId, ...(request.tool ? { tool: request.tool } : {}) }, overflow: "idle" }, effect: "commit-boundary-stop", ...requestDetails(request) };
96
- return { state: { request: NO_REQUEST, overflow: "idle" }, effect: "commit-boundary", ...requestDetails(request) };
93
+ return boundaryIntent(request, facts.windowId, "turn-end");
97
94
  }
98
95
  return { state: { request, overflow: "idle" }, effect: "none" };
99
96
  }
@@ -102,14 +99,15 @@ export function reduceResetControl(state, event) {
102
99
  if (facts.aborted)
103
100
  return { state: initialResetControl(), effect: "none" };
104
101
  const request = requestForWindow(state.request, facts.windowId);
105
- if (request.phase === "stop-pending") {
102
+ if (state.stopAfterReset) {
106
103
  if (facts.queued)
107
104
  return { state, effect: "none" };
108
- // Only retry construction if the safety boundary never committed. Otherwise
109
- // stop without a second wipe, even if a queued turn subsequently failed.
110
- if (request.windowId !== facts.windowId)
105
+ // A changed window confirms commit: stop without wiping twice. Otherwise retry.
106
+ if (state.stopAfterReset.windowId !== facts.windowId)
111
107
  return { state: initialResetControl(), effect: "stop" };
112
- return { state: initialResetControl(), effect: facts.failed || !facts.enabled ? "none" : "commit-boundary-stop", ...requestDetails(request) };
108
+ if (facts.failed || !facts.enabled)
109
+ return { state: initialResetControl(), effect: "none" };
110
+ return { ...state.stopAfterReset, boundary: "settle" };
113
111
  }
114
112
  const manual = request.phase === "pending" && request.command !== undefined;
115
113
  if (state.overflow === "pending" || state.overflow === "pending-spent") {
@@ -119,19 +117,21 @@ export function reduceResetControl(state, event) {
119
117
  // An explicit manual wipe is not an automatic recovery/retry. It must still
120
118
  // clear on overflow, including when automatic reset is disabled.
121
119
  if (manual && facts.enabled)
122
- return commandCommit(request, true);
120
+ return boundaryIntent(request, facts.windowId, "command-overflow");
123
121
  const spent = state.overflow === "pending-spent";
124
122
  if (!facts.enabled || !facts.automaticResetEnabled) {
125
123
  return { state: { request: facts.failed ? NO_REQUEST : request, overflow: spent ? "spent" : "idle" }, effect: "none" };
126
124
  }
127
- return { state: { request: NO_REQUEST, overflow: "spent" }, effect: spent ? "none" : "recover-overflow", ...requestDetails(request) };
125
+ if (spent)
126
+ return { state: { request: NO_REQUEST, overflow: "spent" }, effect: "none" };
127
+ return boundaryIntent(request, facts.windowId, "overflow-recovery");
128
128
  }
129
129
  if (facts.failed || !facts.enabled || !manual) {
130
130
  return { state: { ...state, request: NO_REQUEST }, effect: "none" };
131
131
  }
132
132
  if (facts.queued)
133
133
  return { state: { ...state, request }, effect: "none" };
134
- return commandCommit(request);
134
+ return boundaryIntent(request, facts.windowId, "settle");
135
135
  }
136
136
  }
137
137
  }
@@ -160,17 +160,16 @@ export function registerResetLifecycle(pi, options) {
160
160
  runInputs.push(...inputs);
161
161
  };
162
162
  const clear = (preserveInputs = true) => {
163
+ lifecycleGeneration++;
163
164
  if (preserveInputs)
164
165
  restoreCommandInputs();
165
166
  control = initialResetControl();
166
167
  runInputs = [];
167
168
  commandId = undefined;
168
169
  };
169
- const resetBoundaryResult = async (entries, ctx, decision) => {
170
+ const resetBoundaryResult = async (entries, ctx, intent) => {
170
171
  // Keep command state live while notes load: input arriving during this await must
171
172
  // join this very boundary even if its steer cannot reach the closing model.
172
- const passiveInputs = decision.effect === "recover-overflow" ? runInputs : [];
173
- const origin = decision.origin ?? "forced";
174
173
  const generation = lifecycleGeneration;
175
174
  const outerGeneration = options.getLifecycleGeneration?.();
176
175
  const sessionId = ctx.sessionManager.getSessionId();
@@ -182,7 +181,7 @@ export function registerResetLifecycle(pi, options) {
182
181
  const firstSeq = nextHistorySeq(ctx, entries) + 1;
183
182
  let resetDrafts;
184
183
  try {
185
- resetDrafts = await options.buildReset(ctx, isCurrent, decision.lastWord, firstSeq, origin);
184
+ resetDrafts = await options.buildReset(ctx, isCurrent, intent.tool?.lastWord, firstSeq, intent.origin);
186
185
  }
187
186
  catch (error) {
188
187
  if (isCurrent())
@@ -191,14 +190,11 @@ export function registerResetLifecycle(pi, options) {
191
190
  }
192
191
  if (!isCurrent())
193
192
  return entries.length > 0 ? { entries } : undefined;
194
- const request = control.request;
195
- const inputs = request.phase === "pending" && request.command ? request.command.inputs ?? [] : passiveInputs;
196
- control = decision.state;
197
- if (inputs.length > 0 && control.request.phase === "stop-pending")
198
- control = { ...control, request: NO_REQUEST };
193
+ const finalized = finalizeResetBoundary(intent, control.request, runInputs);
194
+ control = finalized.state;
199
195
  runInputs = [];
200
196
  options.onResetReady?.(ctx, resetDrafts);
201
- return { entries: [...entries, ...resetDrafts, ...carriedInputDrafts(inputs)], continue: inputs.length > 0 || decision.effect !== "commit-boundary-stop" };
197
+ return { entries: [...entries, ...resetDrafts, ...carriedInputDrafts(finalized.inputs)], continue: finalized.resumeModel };
202
198
  };
203
199
  // Pi may start multiple low-level loops while draining follow-ups/recovering.
204
200
  // Keep the logical run's inputs until settlement or a successful boundary.
@@ -237,10 +233,11 @@ export function registerResetLifecycle(pi, options) {
237
233
  request.windowId === currentWindowId(ctx) && details?.windowId === request.windowId && commandId !== undefined && details?.commandId === commandId;
238
234
  });
239
235
  const filtered = messages.length === event.messages.length ? undefined : { messages };
240
- if (!sessionActive || request.phase !== "stop-pending" || ctx.hasPendingMessages())
236
+ const stop = control.stopAfterReset;
237
+ if (!sessionActive || !stop || ctx.hasPendingMessages())
241
238
  return filtered;
242
239
  const marker = currentReset(ctx);
243
- if (!marker || marker.data.windowId === request.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId))
240
+ if (!marker || marker.data.windowId === stop.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId))
244
241
  return filtered;
245
242
  const branch = ctx.sessionManager.getBranch();
246
243
  const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
@@ -270,7 +267,7 @@ export function registerResetLifecycle(pi, options) {
270
267
  get hardReserveDue() { return options.budget.hardReserveDue(ctx); },
271
268
  },
272
269
  });
273
- if (decision.effect === "commit-boundary" || decision.effect === "commit-boundary-stop")
270
+ if (decision.effect === "build-boundary")
274
271
  return await resetBoundaryResult(entries, ctx, decision);
275
272
  if (aborted || (event.outcome === "error" && decision.state.request.phase === "none"))
276
273
  restoreCommandInputs();
@@ -291,7 +288,7 @@ export function registerResetLifecycle(pi, options) {
291
288
  failed: event.outcome === "error",
292
289
  },
293
290
  });
294
- if (decision.effect === "commit-boundary" || decision.effect === "commit-boundary-stop" || decision.effect === "recover-overflow")
291
+ if (decision.effect === "build-boundary")
295
292
  return await resetBoundaryResult(event.entries, ctx, decision);
296
293
  if (decision.state.request.phase === "none")
297
294
  restoreCommandInputs();
@@ -321,9 +318,9 @@ export function registerResetLifecycle(pi, options) {
321
318
  pi.on("agent_settled", () => {
322
319
  clear();
323
320
  });
324
- pi.on("session_start", () => { lifecycleGeneration++; clear(false); sessionActive = true; });
325
- pi.on("session_tree", () => { lifecycleGeneration++; clear(false); });
326
- pi.on("session_shutdown", () => { lifecycleGeneration++; clear(false); options.budget.clear(); sessionActive = false; });
321
+ pi.on("session_start", () => { clear(false); sessionActive = true; });
322
+ pi.on("session_tree", () => { clear(false); });
323
+ pi.on("session_shutdown", () => { clear(false); options.budget.clear(); sessionActive = false; });
327
324
  return {
328
325
  command(windowId, continueAfterReset, input) {
329
326
  const decision = reduceResetControl(control, { type: "command", windowId, continueAfterReset, ...(input !== undefined ? { input } : {}) });
@@ -14,7 +14,7 @@ import { LAST_WORD_HINT, commandWarningContent } from "../plugins/pi/text.js";
14
14
  import { historyFromSession, nextHistorySeq } from "../plugins/pi/history.js";
15
15
  import { buildResetDrafts, inspectResetTail, LAST_WORD_PREFIX, MAX_LAST_WORD_CHARS, repairResetTail, sanitizeLastWord } from "../plugins/pi/reset/artifacts.js";
16
16
  import { resetBoundaryCommitted } from "../plugins/pi/reset/committed.js";
17
- import { initialResetControl, reduceResetControl, registerResetLifecycle, } from "../plugins/pi/reset/lifecycle.js";
17
+ import { finalizeResetBoundary, initialResetControl, reduceResetControl, registerResetLifecycle, } from "../plugins/pi/reset/lifecycle.js";
18
18
  const previousNotesHome = process.env.PI_NOTES_HOME;
19
19
  const testNotesHome = mkdtempSync(join(tmpdir(), "notesoup-lifecycle-notes-"));
20
20
  process.env.PI_NOTES_HOME = testNotesHome;
@@ -122,6 +122,14 @@ function appendDrafts(sessionManager, entries) {
122
122
  }
123
123
  }
124
124
  }
125
+ function boundaryIntent(decision) {
126
+ assert.ok(decision.effect === "build-boundary", "expected construction intent, not a state transition");
127
+ return decision;
128
+ }
129
+ function controlState(decision) {
130
+ assert.ok(decision.effect !== "build-boundary", "expected a state transition, not construction intent");
131
+ return decision.state;
132
+ }
125
133
  function turnEndFacts(overrides = {}) {
126
134
  return {
127
135
  windowId: "pcw:test:window",
@@ -320,6 +328,48 @@ test("input arriving during reset construction survives even when the hidden ste
320
328
  assert.equal(inspectResetTail(ctx, partialMarker, "partial"), undefined, "repair cannot append a continuation after human content");
321
329
  assert.equal(resetBoundaryCommitted(ctx, partialMarker, "partial"), false);
322
330
  });
331
+ test("overflow construction reads live run inputs and clear invalidates an unfinished build", async () => {
332
+ const sessionManager = Manager.inMemory("/private/tmp/notesoup-live-passive-input-test");
333
+ const handlers = new Map();
334
+ const api = { on(name, handler) { handlers.set(name, handler); } };
335
+ const ctx = { sessionManager, model: undefined, hasPendingMessages: () => false, ui: { notify() { } } };
336
+ let release;
337
+ let readyCount = 0;
338
+ const lifecycle = registerResetLifecycle(api, {
339
+ isEnabled: () => true,
340
+ budget: { automaticResetEnabled: () => true, hardReserveDue: () => false, consumeTurnEnd: () => [], clear() { } },
341
+ buildReset: () => new Promise((resolve) => { release = resolve; }),
342
+ onResetReady: () => { readyCount++; },
343
+ });
344
+ const user = (content) => handlers.get("message_end")({ message: { role: "user", content } }, ctx);
345
+ const failed = { ...fakeBoundaryEvent(), outcome: "error", message: { role: "assistant", stopReason: "error", errorMessage: "Prompt too long: context exceeds maximum context length" } };
346
+ const recover = async () => {
347
+ await handlers.get("turn_end")(failed, ctx);
348
+ return handlers.get("agent_before_settle")({ ...failed, type: "agent_before_settle" }, ctx);
349
+ };
350
+ await user("starting input");
351
+ const building = recover();
352
+ await Promise.resolve();
353
+ await user("delivered during construction");
354
+ release([]);
355
+ const result = resultEntries([await building]);
356
+ assert.equal(result.continue, true);
357
+ assert.deepEqual(result.entries.map((entry) => entry.type === "custom_message" ? entry.content : null), ["starting input", "delivered during construction"]);
358
+ lifecycle.clear();
359
+ await user("old run");
360
+ const stale = recover();
361
+ await Promise.resolve();
362
+ lifecycle.clear();
363
+ await user("new run");
364
+ release([{ type: "custom_message", customType: BOOT_TYPE, content: "stale", display: false }]);
365
+ assert.equal(await stale, undefined, "clearing the run invalidates construction before it can consume new inputs");
366
+ assert.equal(readyCount, 1);
367
+ const current = recover();
368
+ await Promise.resolve();
369
+ release([]);
370
+ const fresh = resultEntries([await current]);
371
+ assert.deepEqual(fresh.entries.map((entry) => entry.type === "custom_message" ? entry.content : null), ["new run"]);
372
+ });
323
373
  test("abort during reset construction restores handled input at settlement, once", async () => {
324
374
  const sessionManager = Manager.inMemory("/private/tmp/notesoup-cancelled-build-test");
325
375
  const handlers = new Map();
@@ -540,12 +590,14 @@ test("reset-control: command policy deduplicates, spans turns, and retains a rea
540
590
  assert.equal(duplicate.effect, "already-pending");
541
591
  const noteTurn = reduceResetControl(first.state, { type: "turn_end", facts: turnEndFacts() });
542
592
  assert.equal(noteTurn.effect, "none");
543
- assert.deepEqual(noteTurn.state.request, first.state.request, "note/tool turns do not consume close-out");
544
- const tool = reduceResetControl(noteTurn.state, { type: "tool_request", windowId });
593
+ assert.deepEqual(controlState(noteTurn).request, first.state.request, "note/tool turns do not consume close-out");
594
+ const tool = reduceResetControl(controlState(noteTurn), { type: "tool_request", windowId });
545
595
  assert.equal(tool.effect, "close-out-armed", "the first tool call is recorded without changing settlement policy");
546
596
  assert.deepEqual(tool.state.request, { phase: "pending", windowId, command: { continueAfterReset: false }, tool: {} });
547
- const commit = reduceResetControl(tool.state, { type: "before_settle", facts: beforeSettleFacts() });
548
- assert.equal(commit.effect, "commit-boundary-stop", "a manual close-out commits at settlement and stops");
597
+ const decision = reduceResetControl(tool.state, { type: "before_settle", facts: beforeSettleFacts() });
598
+ assert.equal(decision.effect, "build-boundary", "construction intent has no final state to install");
599
+ const commit = finalizeResetBoundary(boundaryIntent(decision), tool.state.request);
600
+ assert.equal(commit.resumeModel, false, "a manual close-out commits at settlement and stops");
549
601
  assert.deepEqual(commit.state, initialResetControl());
550
602
  });
551
603
  test("reset-control: command settlement policy preserves a pending tool request", () => {
@@ -555,7 +607,8 @@ test("reset-control: command settlement policy preserves a pending tool request"
555
607
  assert.equal(manual.effect, "close-out-armed", "the user's stop intent outranks the pending rollover");
556
608
  assert.deepEqual(manual.state.request, { phase: "pending", windowId, command: { continueAfterReset: false }, tool: {} });
557
609
  assert.equal(reduceResetControl(manual.state, { type: "turn_end", facts: turnEndFacts() }).effect, "none", "the converted request no longer commits at turn end");
558
- assert.equal(reduceResetControl(manual.state, { type: "before_settle", facts: beforeSettleFacts() }).effect, "commit-boundary-stop");
610
+ const intent = boundaryIntent(reduceResetControl(manual.state, { type: "before_settle", facts: beforeSettleFacts() }));
611
+ assert.equal(finalizeResetBoundary(intent, manual.state.request).resumeModel, false);
559
612
  });
560
613
  test("reset-control: duplicate commands preserve policy and both call orders retain the tool's last word", () => {
561
614
  const windowId = "pcw:test:window";
@@ -572,76 +625,112 @@ test("reset-control: duplicate commands preserve policy and both call orders ret
572
625
  assert.equal(repeated.effect, "already-pending");
573
626
  assert.deepEqual(repeated.state, commandThenTool.state);
574
627
  assert.equal(reduceResetControl(repeated.state, { type: "turn_end", facts: turnEndFacts() }).effect, "none");
575
- const commit = reduceResetControl(repeated.state, { type: "before_settle", facts: beforeSettleFacts() });
576
- assert.equal(commit.effect, "commit-boundary");
577
- assert.equal(commit.lastWord, "pick up here");
628
+ const intent = boundaryIntent(reduceResetControl(repeated.state, { type: "before_settle", facts: beforeSettleFacts() }));
629
+ assert.equal(intent.tool?.lastWord, "pick up here");
630
+ const commit = finalizeResetBoundary(intent, repeated.state.request);
631
+ assert.equal(commit.resumeModel, true, "explicit continue policy does not require delivery contents");
632
+ assert.deepEqual(commit.inputs, []);
578
633
  });
579
634
  test("reset-control: a tool request needs no prior budget warning", () => {
580
635
  const windowId = "pcw:test:window";
581
636
  const requested = reduceResetControl(initialResetControl(), { type: "tool_request", windowId });
582
637
  assert.equal(requested.effect, "close-out-armed");
583
638
  assert.deepEqual(requested.state.request, { phase: "pending", windowId, tool: {} });
584
- assert.equal(reduceResetControl(requested.state, { type: "turn_end", facts: turnEndFacts() }).effect, "commit-boundary");
639
+ const intent = boundaryIntent(reduceResetControl(requested.state, { type: "turn_end", facts: turnEndFacts() }));
640
+ assert.equal(finalizeResetBoundary(intent, requested.state.request).resumeModel, true);
585
641
  });
586
642
  test("reset-control: fallback is normal-stop only; hard reserve remains safety", () => {
587
643
  const windowId = "pcw:test:window";
588
644
  const manual = reduceResetControl(initialResetControl(), { type: "command", windowId, continueAfterReset: false }).state;
589
- const fallback = reduceResetControl(manual, { type: "before_settle", facts: beforeSettleFacts() });
590
- assert.equal(fallback.effect, "commit-boundary-stop", "manual close-out stops after the reset is committed");
645
+ const intent = boundaryIntent(reduceResetControl(manual, { type: "before_settle", facts: beforeSettleFacts() }));
646
+ const fallback = finalizeResetBoundary(intent, manual.request);
647
+ assert.equal(fallback.resumeModel, false, "manual close-out stops after the reset is committed");
591
648
  assert.deepEqual(fallback.state, initialResetControl());
592
649
  const automatic = initialResetControl();
593
650
  const normalStop = reduceResetControl(automatic, { type: "before_settle", facts: beforeSettleFacts() });
594
651
  assert.equal(normalStop.effect, "none", "ignoring a budget warning and answering normally must not wipe memory");
595
- assert.deepEqual(normalStop.state, initialResetControl());
652
+ assert.deepEqual(controlState(normalStop), initialResetControl());
596
653
  const disabledAuto = reduceResetControl(automatic, { type: "before_settle", facts: beforeSettleFacts({ automaticResetEnabled: false }) });
597
654
  assert.equal(disabledAuto.effect, "none");
598
- assert.deepEqual(disabledAuto.state, initialResetControl());
655
+ assert.deepEqual(controlState(disabledAuto), initialResetControl());
599
656
  const safety = reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ hardReserveDue: true }) });
600
- assert.equal(safety.effect, "commit-boundary");
657
+ assert.equal(finalizeResetBoundary(boundaryIntent(safety), automatic.request).resumeModel, true);
601
658
  for (const outcome of [{ failed: true }, { aborted: true }]) {
602
659
  const notNormalStop = reduceResetControl(manual, { type: "before_settle", facts: beforeSettleFacts(outcome) });
603
660
  assert.equal(notNormalStop.effect, "none");
604
- assert.deepEqual(notNormalStop.state, initialResetControl());
661
+ assert.deepEqual(controlState(notNormalStop), initialResetControl());
605
662
  }
606
663
  });
607
664
  test("reset-control: manual stop survives a hard-reserve reset across windows without a second wipe", () => {
608
665
  const windowId = "pcw:test:window";
609
666
  const manual = reduceResetControl(initialResetControl(), { type: "command", windowId, continueAfterReset: false }).state;
610
- const safety = reduceResetControl(manual, { type: "turn_end", facts: turnEndFacts({ hardReserveDue: true }) });
611
- assert.equal(safety.effect, "commit-boundary-stop");
612
- assert.deepEqual(safety.state.request, { phase: "stop-pending", windowId });
667
+ const decision = reduceResetControl(manual, { type: "turn_end", facts: turnEndFacts({ hardReserveDue: true }) });
668
+ assert.equal(decision.effect, "build-boundary", "construction does not install the stop latch");
669
+ const safety = finalizeResetBoundary(boundaryIntent(decision), manual.request);
670
+ assert.equal(safety.resumeModel, false);
671
+ assert.deepEqual(safety.state.request, { phase: "none" });
672
+ assert.deepEqual(safety.state.stopAfterReset, decision);
613
673
  const freshWindowId = "pcw:test:fresh";
614
674
  assert.equal(reduceResetControl(safety.state, { type: "tool_request", windowId: freshWindowId }).effect, "already-pending");
615
675
  assert.equal(reduceResetControl(safety.state, { type: "command", windowId: freshWindowId, continueAfterReset: false }).effect, "already-pending");
616
676
  const queued = reduceResetControl(safety.state, { type: "before_settle", facts: beforeSettleFacts({ windowId: freshWindowId, queued: true }) });
617
- assert.deepEqual(queued.state, safety.state);
618
- const freshTurn = reduceResetControl(queued.state, { type: "turn_end", facts: turnEndFacts({ windowId: freshWindowId, hardReserveDue: true }) });
677
+ assert.deepEqual(controlState(queued), safety.state);
678
+ const freshTurn = reduceResetControl(controlState(queued), { type: "turn_end", facts: turnEndFacts({ windowId: freshWindowId, hardReserveDue: true }) });
619
679
  assert.equal(freshTurn.effect, "none");
620
- const stop = reduceResetControl(freshTurn.state, { type: "before_settle", facts: beforeSettleFacts({ windowId: freshWindowId }) });
680
+ const stop = reduceResetControl(controlState(freshTurn), { type: "before_settle", facts: beforeSettleFacts({ windowId: freshWindowId }) });
621
681
  assert.equal(stop.effect, "stop", "the safety boundary already wiped; settlement must only stop");
622
- assert.deepEqual(stop.state, initialResetControl());
623
- assert.equal(reduceResetControl(safety.state, { type: "before_settle", facts: beforeSettleFacts() }).effect, "commit-boundary-stop", "a failed safety construction may be retried before settlement");
624
- assert.deepEqual(reduceResetControl(safety.state, { type: "before_settle", facts: beforeSettleFacts({ windowId: freshWindowId, aborted: true }) }).state, initialResetControl());
682
+ assert.deepEqual(controlState(stop), initialResetControl());
683
+ const uncommitted = boundaryIntent(reduceResetControl(safety.state, { type: "before_settle", facts: beforeSettleFacts() }));
684
+ assert.equal(uncommitted.continueAfterReset, false, "same-window retry retains the stop policy");
685
+ const retried = finalizeResetBoundary(uncommitted, safety.state.request);
686
+ assert.equal(retried.resumeModel, false);
687
+ assert.deepEqual(retried.state, initialResetControl(), "settle retry consumes the stop latch");
688
+ const retry = boundaryIntent(reduceResetControl(manual, { type: "before_settle", facts: beforeSettleFacts() }));
689
+ assert.equal(finalizeResetBoundary(retry, manual.request).resumeModel, false, "a failed safety construction leaves the command available for settlement retry");
690
+ assert.deepEqual(controlState(reduceResetControl(safety.state, { type: "before_settle", facts: beforeSettleFacts({ windowId: freshWindowId, aborted: true }) })), initialResetControl());
691
+ });
692
+ test("reset-control: one safety intent finalizes stop or continuation from live command originals", () => {
693
+ const windowId = "pcw:test:window";
694
+ const pending = reduceResetControl(initialResetControl(), { type: "command", windowId, continueAfterReset: false }).state;
695
+ const intent = boundaryIntent(reduceResetControl(pending, { type: "turn_end", facts: turnEndFacts({ hardReserveDue: true }) }));
696
+ assert.deepEqual(pending.request, { phase: "pending", windowId, command: { continueAfterReset: false } });
697
+ const stopped = finalizeResetBoundary(intent, pending.request, ["passive run input"]);
698
+ assert.equal(stopped.resumeModel, false);
699
+ assert.deepEqual(stopped.inputs, [], "a command boundary never replays passive run input");
700
+ assert.deepEqual(stopped.state.stopAfterReset, intent);
701
+ const live = reduceResetControl(pending, { type: "input", windowId, input: "late original" }).state;
702
+ const continued = finalizeResetBoundary(intent, live.request, ["passive run input"]);
703
+ assert.equal(continued.resumeModel, true);
704
+ assert.deepEqual(continued.inputs, ["late original"]);
705
+ assert.deepEqual(continued.state, initialResetControl(), "late originals prevent installing the stop latch");
706
+ assert.equal(intent.continueAfterReset, false, "delivery does not rewrite explicit command policy");
707
+ assert.deepEqual(live.request, { phase: "pending", windowId, command: { continueAfterReset: false, inputs: ["late original"] } }, "finalization is pure");
625
708
  });
626
709
  test("reset-control: manual overflow keeps stop intent while queued work supersedes the failure", () => {
627
710
  const windowId = "pcw:test:window";
628
711
  const manual = reduceResetControl(initialResetControl(), { type: "command", windowId, continueAfterReset: false }).state;
629
- const overflow = reduceResetControl(manual, { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true, queued: true, automaticResetEnabled: false }) });
630
- assert.deepEqual(overflow.state.request, manual.request);
631
- const deferred = reduceResetControl(overflow.state, { type: "before_settle", facts: beforeSettleFacts({ failed: true, queued: true, automaticResetEnabled: false }) });
632
- assert.deepEqual(deferred.state, overflow.state);
633
- assert.equal(reduceResetControl(overflow.state, { type: "before_settle", facts: beforeSettleFacts({ failed: true, automaticResetEnabled: false }) }).effect, "commit-boundary-stop", "manual overflow resets but does not retry the model");
634
- const success = reduceResetControl(deferred.state, { type: "turn_end", facts: turnEndFacts() });
635
- assert.deepEqual(success.state.request, manual.request, "a successful queued turn clears only the overflow, not the manual wipe");
636
- assert.equal(success.state.overflow, "idle");
637
- assert.equal(reduceResetControl(success.state, { type: "before_settle", facts: beforeSettleFacts() }).effect, "commit-boundary-stop");
712
+ const overflow = controlState(reduceResetControl(manual, { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true, queued: true, automaticResetEnabled: false }) }));
713
+ assert.deepEqual(overflow.request, manual.request);
714
+ const deferred = controlState(reduceResetControl(overflow, { type: "before_settle", facts: beforeSettleFacts({ failed: true, queued: true, automaticResetEnabled: false }) }));
715
+ assert.deepEqual(deferred, overflow);
716
+ const stopIntent = boundaryIntent(reduceResetControl(overflow, { type: "before_settle", facts: beforeSettleFacts({ failed: true, automaticResetEnabled: false }) }));
717
+ assert.equal(finalizeResetBoundary(stopIntent, overflow.request).resumeModel, false, "manual overflow resets but does not retry the model");
718
+ const success = controlState(reduceResetControl(deferred, { type: "turn_end", facts: turnEndFacts() }));
719
+ assert.deepEqual(success.request, manual.request, "a successful queued turn clears only the overflow, not the manual wipe");
720
+ assert.equal(success.overflow, "idle");
721
+ const successIntent = boundaryIntent(reduceResetControl(success, { type: "before_settle", facts: beforeSettleFacts() }));
722
+ assert.equal(finalizeResetBoundary(successIntent, success.request).resumeModel, false);
638
723
  const prompted = reduceResetControl(manual, { type: "input", windowId, input: "answer after reset" }).state;
639
724
  const called = reduceResetControl(prompted, { type: "tool_request", windowId, lastWord: "saved" }).state;
640
- const failed = reduceResetControl(called, { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true, automaticResetEnabled: false }) }).state;
641
- const retry = reduceResetControl(failed, { type: "before_settle", facts: beforeSettleFacts({ failed: true, automaticResetEnabled: false }) });
642
- assert.equal(retry.effect, "commit-boundary", "manual input continues even when automatic reset is disabled");
643
- assert.equal(retry.origin, "forced", "an overflowing close-out is forced even after a tool request");
644
- assert.equal(retry.lastWord, "saved");
725
+ const failed = controlState(reduceResetControl(called, { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true, automaticResetEnabled: false }) }));
726
+ const decision = reduceResetControl(failed, { type: "before_settle", facts: beforeSettleFacts({ failed: true, automaticResetEnabled: false }) });
727
+ assert.equal(failed.overflow, "pending", "construction alone does not spend overflow recovery");
728
+ const retryIntent = boundaryIntent(decision);
729
+ assert.equal(retryIntent.origin, "forced", "an overflowing close-out is forced even after a tool request");
730
+ assert.equal(retryIntent.tool?.lastWord, "saved");
731
+ const retry = finalizeResetBoundary(retryIntent, failed.request, ["passive input is not command-owned"]);
732
+ assert.equal(retry.resumeModel, true, "manual input continues even when automatic reset is disabled");
733
+ assert.deepEqual(retry.inputs, ["answer after reset"]);
645
734
  assert.equal(retry.state.overflow, "spent", "manual recovery spends the same bounded attempt");
646
735
  });
647
736
  test("reset-control: explicit abort clears a pending request at turn end or settlement", () => {
@@ -649,42 +738,46 @@ test("reset-control: explicit abort clears a pending request at turn end or sett
649
738
  const pending = reduceResetControl(initialResetControl(), { type: "command", windowId, continueAfterReset: false }).state;
650
739
  const aborted = reduceResetControl(pending, { type: "turn_end", facts: turnEndFacts({ aborted: true }) });
651
740
  assert.equal(aborted.effect, "none");
652
- assert.deepEqual(aborted.state, initialResetControl());
653
- assert.deepEqual(reduceResetControl(pending, { type: "before_settle", facts: beforeSettleFacts({ aborted: true }) }).state, initialResetControl());
741
+ assert.deepEqual(controlState(aborted), initialResetControl());
742
+ assert.deepEqual(controlState(reduceResetControl(pending, { type: "before_settle", facts: beforeSettleFacts({ aborted: true }) })), initialResetControl());
654
743
  });
655
744
  test("reset-control: overflow recovery is armed at turn_end and spent exactly once at settle", () => {
656
- const armed = reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true }) });
657
- assert.deepEqual(armed.state, { request: { phase: "none" }, overflow: "pending" });
658
- const recovered = reduceResetControl(armed.state, { type: "before_settle", facts: beforeSettleFacts() });
659
- assert.equal(recovered.effect, "recover-overflow", "the first settle commits the bounded recovery");
745
+ const armed = controlState(reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true }) }));
746
+ assert.deepEqual(armed, { request: { phase: "none" }, overflow: "pending" });
747
+ const intent = boundaryIntent(reduceResetControl(armed, { type: "before_settle", facts: beforeSettleFacts() }));
748
+ assert.equal(armed.overflow, "pending", "failed construction would leave recovery unspent");
749
+ assert.equal(intent.boundary, "overflow-recovery");
750
+ const recovered = finalizeResetBoundary(intent, armed.request, ["failed run's user input"]);
751
+ assert.equal(recovered.resumeModel, true);
752
+ assert.deepEqual(recovered.inputs, ["failed run's user input"]);
660
753
  assert.deepEqual(recovered.state, { request: { phase: "none" }, overflow: "spent" });
661
754
  const repeated = reduceResetControl(recovered.state, { type: "before_settle", facts: beforeSettleFacts() });
662
755
  assert.equal(repeated.effect, "none", "a spent recovery is never retried");
663
- const rearmed = reduceResetControl(recovered.state, { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true }) });
664
- assert.deepEqual(rearmed.state, { request: { phase: "none" }, overflow: "pending-spent" });
665
- const bounded = reduceResetControl(rearmed.state, { type: "before_settle", facts: beforeSettleFacts() });
756
+ const rearmed = controlState(reduceResetControl(recovered.state, { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true }) }));
757
+ assert.deepEqual(rearmed, { request: { phase: "none" }, overflow: "pending-spent" });
758
+ const bounded = reduceResetControl(rearmed, { type: "before_settle", facts: beforeSettleFacts() });
666
759
  assert.equal(bounded.effect, "none", "a second failure chain stays bounded to the spent attempt");
667
- assert.deepEqual(bounded.state, { request: { phase: "none" }, overflow: "spent" });
760
+ assert.deepEqual(controlState(bounded), { request: { phase: "none" }, overflow: "spent" });
668
761
  });
669
762
  test("reset-control: a queued turn defers recovery and its success supersedes the failure", () => {
670
- const armed = reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true }) }).state;
763
+ const armed = controlState(reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true }) }));
671
764
  const deferred = reduceResetControl(armed, { type: "before_settle", facts: beforeSettleFacts({ queued: true }) });
672
765
  assert.equal(deferred.effect, "none");
673
- assert.deepEqual(deferred.state, armed, "a queued message leaves the overflow chain armed");
766
+ assert.deepEqual(controlState(deferred), armed, "a queued message leaves the overflow chain armed");
674
767
  const success = reduceResetControl(armed, { type: "turn_end", facts: turnEndFacts() });
675
- assert.deepEqual(success.state, initialResetControl(), "a successful queued turn clears the stale failure");
768
+ assert.deepEqual(controlState(success), initialResetControl(), "a successful queued turn clears the stale failure");
676
769
  });
677
770
  test("reset-control: disabled mode and explicit aborts disarm overflow without a recovery", () => {
678
- const armed = reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true }) }).state;
771
+ const armed = controlState(reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true }) }));
679
772
  const disabled = reduceResetControl(armed, { type: "before_settle", facts: beforeSettleFacts({ enabled: false }) });
680
773
  assert.equal(disabled.effect, "none");
681
- assert.deepEqual(disabled.state, { request: { phase: "none" }, overflow: "idle" });
774
+ assert.deepEqual(controlState(disabled), { request: { phase: "none" }, overflow: "idle" });
682
775
  const automaticOff = reduceResetControl(armed, { type: "before_settle", facts: beforeSettleFacts({ automaticResetEnabled: false }) });
683
776
  assert.equal(automaticOff.effect, "none");
684
- assert.deepEqual(automaticOff.state, { request: { phase: "none" }, overflow: "idle" });
777
+ assert.deepEqual(controlState(automaticOff), { request: { phase: "none" }, overflow: "idle" });
685
778
  const aborted = reduceResetControl(armed, { type: "before_settle", facts: beforeSettleFacts({ aborted: true }) });
686
779
  assert.equal(aborted.effect, "none");
687
- assert.deepEqual(aborted.state, { request: { phase: "none" }, overflow: "idle" });
780
+ assert.deepEqual(controlState(aborted), { request: { phase: "none" }, overflow: "idle" });
688
781
  });
689
782
  test("reset-control: lazy guards preserve overflow policy ordering", () => {
690
783
  const calls = { queued: 0, automatic: 0, hardReserve: 0 };
@@ -709,7 +802,7 @@ test("reset-control: lazy guards preserve overflow policy ordering", () => {
709
802
  aborted: false,
710
803
  failed: false,
711
804
  };
712
- const pendingOverflow = reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true }) }).state;
805
+ const pendingOverflow = controlState(reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true }) }));
713
806
  reduceResetControl(pendingOverflow, { type: "before_settle", facts: settleFacts });
714
807
  assert.deepEqual(settleCalls, { queued: 1, enabled: 0, automatic: 0 }, "queued settle checks no further overflow policy");
715
808
  });
@@ -834,9 +927,9 @@ test("reset-control: a tool request carries its last word to the turn-end commit
834
927
  const armed = reduceResetControl(initialResetControl(), { type: "tool_request", windowId, lastWord: "the shoes were loyal" });
835
928
  assert.equal(armed.effect, "close-out-armed");
836
929
  assert.deepEqual(armed.state.request, { phase: "pending", windowId, tool: { lastWord: "the shoes were loyal" } });
837
- const commit = reduceResetControl(armed.state, { type: "turn_end", facts: turnEndFacts() });
838
- assert.equal(commit.effect, "commit-boundary");
839
- assert.equal(commit.lastWord, "the shoes were loyal");
930
+ const intent = boundaryIntent(reduceResetControl(armed.state, { type: "turn_end", facts: turnEndFacts() }));
931
+ assert.equal(intent.tool?.lastWord, "the shoes were loyal");
932
+ assert.equal(finalizeResetBoundary(intent, armed.state.request).resumeModel, true);
840
933
  });
841
934
  test("reset-control: a call and a command keep their facts in either order", () => {
842
935
  const windowId = "pcw:test:window";
@@ -845,35 +938,36 @@ test("reset-control: a call and a command keep their facts in either order", ()
845
938
  const converted = reduceResetControl(toolFirst.state, { type: "command", windowId, continueAfterReset: false });
846
939
  assert.equal(converted.effect, "close-out-armed");
847
940
  assert.deepEqual(converted.state.request, { phase: "pending", windowId, command: { continueAfterReset: false }, tool: { lastWord: "the shoes were loyal" } });
848
- const stop = reduceResetControl(converted.state, { type: "before_settle", facts: beforeSettleFacts() });
849
- assert.equal(stop.effect, "commit-boundary-stop");
941
+ const stop = boundaryIntent(reduceResetControl(converted.state, { type: "before_settle", facts: beforeSettleFacts() }));
942
+ assert.equal(finalizeResetBoundary(stop, converted.state.request).resumeModel, false);
850
943
  assert.equal(stop.origin, "normal", "a command arriving after a model wipe does not rewrite it as forced");
851
- assert.equal(stop.lastWord, "the shoes were loyal", "the call's parting line survives the conversion");
944
+ assert.equal(stop.tool?.lastWord, "the shoes were loyal", "the call's parting line survives the conversion");
852
945
  // The command first, then the call: the acknowledgement records the call and keeps stopping.
853
946
  const commandFirst = reduceResetControl(initialResetControl(), { type: "command", windowId, continueAfterReset: false });
854
947
  const acknowledged = reduceResetControl(commandFirst.state, { type: "tool_request", windowId, lastWord: "tell them I was funny" });
855
948
  assert.equal(acknowledged.effect, "close-out-armed");
856
949
  assert.deepEqual(acknowledged.state.request, { phase: "pending", windowId, command: { continueAfterReset: false }, tool: { lastWord: "tell them I was funny" } });
857
- const settled = reduceResetControl(acknowledged.state, { type: "before_settle", facts: beforeSettleFacts() });
858
- assert.equal(settled.effect, "commit-boundary-stop");
950
+ const settled = boundaryIntent(reduceResetControl(acknowledged.state, { type: "before_settle", facts: beforeSettleFacts() }));
951
+ assert.equal(finalizeResetBoundary(settled, acknowledged.state.request).resumeModel, false);
859
952
  assert.equal(settled.origin, "normal", "the command-first order records the same origin");
860
- assert.equal(settled.lastWord, "tell them I was funny");
953
+ assert.equal(settled.tool?.lastWord, "tell them I was funny");
861
954
  });
862
955
  test("reset-control: the origin is the empty_brain call, independent of command policy", () => {
863
956
  const windowId = "pcw:test:window";
864
957
  const tool = reduceResetControl(initialResetControl(), { type: "tool_request", windowId });
865
- assert.equal(reduceResetControl(tool.state, { type: "turn_end", facts: turnEndFacts() }).origin, "normal", "the model's own call is a normal reset");
958
+ assert.equal(boundaryIntent(reduceResetControl(tool.state, { type: "turn_end", facts: turnEndFacts() })).origin, "normal", "the model's own call is a normal reset");
866
959
  const manual = reduceResetControl(initialResetControl(), { type: "command", windowId, continueAfterReset: false }).state;
867
- assert.equal(reduceResetControl(manual, { type: "before_settle", facts: beforeSettleFacts() }).origin, "forced", "a command close-out with no call is a system reset");
960
+ assert.equal(boundaryIntent(reduceResetControl(manual, { type: "before_settle", facts: beforeSettleFacts() })).origin, "forced", "a command close-out with no call is a system reset");
868
961
  const acknowledged = reduceResetControl(manual, { type: "tool_request", windowId }).state;
869
- assert.equal(reduceResetControl(acknowledged, { type: "before_settle", facts: beforeSettleFacts() }).origin, "normal", "a manual close-out the model actually wipes is normal but still stops");
870
- assert.equal(reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ hardReserveDue: true }) }).origin, "forced", "the hard cutoff happens without a call");
871
- const safety = reduceResetControl(acknowledged, { type: "turn_end", facts: turnEndFacts({ hardReserveDue: true }) });
872
- assert.equal(safety.origin, "normal", "an acknowledged call survives the hard cutoff it was armed against");
873
- assert.deepEqual(safety.state.request, { phase: "stop-pending", windowId, tool: {} }, "the recorded call survives into the run-scoped stop latch");
874
- assert.equal(reduceResetControl(safety.state, { type: "before_settle", facts: beforeSettleFacts() }).origin, "normal", "a retried safety construction keeps the recorded origin");
875
- const overflow = reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true }) }).state;
876
- assert.equal(reduceResetControl(overflow, { type: "before_settle", facts: beforeSettleFacts() }).origin, "forced", "overflow recovery has no call behind it");
962
+ assert.equal(boundaryIntent(reduceResetControl(acknowledged, { type: "before_settle", facts: beforeSettleFacts() })).origin, "normal", "a manual close-out the model actually wipes is normal but still stops");
963
+ assert.equal(boundaryIntent(reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ hardReserveDue: true }) })).origin, "forced", "the hard cutoff happens without a call");
964
+ const intent = boundaryIntent(reduceResetControl(acknowledged, { type: "turn_end", facts: turnEndFacts({ hardReserveDue: true }) }));
965
+ assert.equal(intent.origin, "normal", "an acknowledged call survives the hard cutoff it was armed against");
966
+ const safety = finalizeResetBoundary(intent, acknowledged.request);
967
+ assert.deepEqual(safety.state.stopAfterReset?.tool, {}, "the recorded call survives into the run-scoped stop latch");
968
+ assert.equal(boundaryIntent(reduceResetControl(safety.state, { type: "before_settle", facts: beforeSettleFacts() })).origin, "normal", "a retried safety construction keeps the recorded origin");
969
+ const overflow = controlState(reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ overflow: true, failed: true }) }));
970
+ assert.equal(boundaryIntent(reduceResetControl(overflow, { type: "before_settle", facts: beforeSettleFacts() })).origin, "forced", "overflow recovery has no call behind it");
877
971
  });
878
972
  test("a committed reset records its origin and draws that pool exactly once", async () => {
879
973
  const random = Math.random;
@@ -916,7 +1010,7 @@ test("reset-control: a command retains tool calls with or without a last word an
916
1010
  assert.deepEqual(ack.state.request, { phase: "pending", windowId, command: { continueAfterReset: false }, tool: { lastWord: "tell them I was funny" } });
917
1011
  const silentAck = reduceResetControl(reduceResetControl(initialResetControl(), { type: "command", windowId, continueAfterReset: false }).state, { type: "tool_request", windowId });
918
1012
  assert.deepEqual(silentAck.state.request, { phase: "pending", windowId, command: { continueAfterReset: false }, tool: {} }, "a call with no last word is still a real tool request");
919
- const commit = reduceResetControl(ack.state, { type: "before_settle", facts: beforeSettleFacts() });
920
- assert.equal(commit.effect, "commit-boundary-stop");
921
- assert.equal(commit.lastWord, "tell them I was funny");
1013
+ const intent = boundaryIntent(reduceResetControl(ack.state, { type: "before_settle", facts: beforeSettleFacts() }));
1014
+ assert.equal(finalizeResetBoundary(intent, ack.state.request).resumeModel, false);
1015
+ assert.equal(intent.tool?.lastWord, "tell them I was funny");
922
1016
  });
@@ -46,7 +46,7 @@ The runtime in `plugins/pi/runtime.ts` performs final context projection by sele
46
46
 
47
47
  Boot and reminder deduplication inspect the current branch-local window. Reloading JSONL therefore does not duplicate messages, while navigation to a sibling branch cannot inherit another branch's window state. A fork/clone receives a new session ID while copying its selected path, so startup must also verify that a root boot's `details.windowId` matches the new `rootWindowId(sessionId)` before treating it as present.
48
48
 
49
- Manual `/fresh-window` stores command settlement policy and sends a hidden warning: idle commands start a model turn, running commands steer it. Tool requests are recorded independently and retained under that policy. A bare command settles and stops; a command with text settles and continues, with its text supplied only to the closing window. Budget warnings create no reset state: only an explicit tool request, hard reserve or bounded overflow recovery triggers a reset. Abort and ordinary errors do not count as successful settlement. Hard reserve preserves a bare command's stop in a run-scoped latch; `context_with_system` cancels only an empty tool-batch follow-up after confirming the committed boundary. Queued user input is answered before stopping. See [reset lifecycle](reset-lifecycle.md) for the state and recovery rules.
49
+ Manual `/fresh-window` stores command settlement policy and sends a hidden warning: idle commands start a model turn, running commands steer it. Tool requests are recorded independently and retained under that policy. A bare command settles and stops unless later human input arrives; a command with text settles and continues, with its text supplied to the closing window and carried verbatim into the fresh window. Budget warnings create no reset state: only an explicit tool request, hard reserve or bounded overflow recovery triggers a reset. Abort and ordinary errors do not count as successful settlement. Hard reserve preserves a bare command's stop in a run-scoped latch; `context_with_system` cancels only an empty tool-batch follow-up after confirming the committed boundary. Queued user input is answered before stopping. See [reset lifecycle](reset-lifecycle.md) for the state and recovery rules.
50
50
 
51
51
  Boot is a fixed snapshot for its window, stored as an extension custom message and converted by Pi to a user-role model message. History internally distinguishes native system summaries and extension-authored custom messages; its public `context` event groups both without implying provider instruction priority. A system-role projection is technically possible through `context_with_system`, but would change the authority of the mixed protocol/MAP content and provider-specific prompt/cache behavior; it is not a prerequisite for persistence. Boot injection is silent, including startup, reload, and boot repair. Only an actual context reset produces a brain-cleared notice through `ctx.ui.notify`, after the verified checkpoint, marker, boot, and continuation are present in the session. Committed resets are checked at the next turn start or final settlement. `plugins/pi/reset/committed.ts` confirms an ordered hidden boot/continuation after a checkpoint-backed marker even when later conversation exists. That is distinct from `inspectResetTail`, which refuses suffix repair after real work or malformed ordering. Uncommitted reset drafts never announce success. Boot and continuation messages retain `display: false`.
52
52
 
@@ -1,6 +1,6 @@
1
1
  # Reset lifecycle
2
2
 
3
- Pi reset control lives in `plugins/pi/reset/lifecycle.ts`: the pure `reduceResetControl` selects effects; `registerResetLifecycle` adapts public Pi events and constructs boundaries. `budget.ts` stages reminders and checks settings; `reset/artifacts.ts` builds and repairs ordered artifacts; `reset/committed.ts` confirms durable boundaries. `window.ts` owns identities and provider projection; `runtime.ts` wires commands and tools. No Pi source patches, native summarization requests, or second commit database are used.
3
+ Pi reset control lives in `plugins/pi/reset/lifecycle.ts`: the pure `reduceResetControl` selects state transitions or boundary intents; after asynchronous construction, `finalizeResetBoundary` owns final state, carried inputs and continuation. `registerResetLifecycle` adapts public Pi events, constructs boundaries and applies the finalizer's result unchanged. `budget.ts` stages reminders and checks settings; `reset/artifacts.ts` builds and repairs ordered artifacts; `reset/committed.ts` confirms durable boundaries. `window.ts` owns identities and provider projection; `runtime.ts` wires commands and tools. No Pi source patches, native summarization requests, or second commit database are used.
4
4
 
5
5
  ## Lifecycle at a glance
6
6
 
@@ -40,19 +40,20 @@ Raw session history remains available. The retain-none checkpoint excludes old c
40
40
 
41
41
  ## Reducer and run state
42
42
 
43
- `ResetControlState` combines a request and a bounded overflow phase:
43
+ `ResetControlState` combines a request, a bounded overflow phase, and an optional run-scoped `stopAfterReset` latch:
44
44
 
45
45
  | Request | Meaning |
46
46
  | --- | --- |
47
47
  | `none` | No command or tool request. |
48
48
  | `pending` | Current `windowId`, optional `tool: { lastWord? }`, and optional `command: { continueAfterReset, inputs? }`. Command inputs retain originals, not prompt-block wrappers. Duplicate commands retain the first policy/text; tool calls do not overwrite command policy. |
49
- | `stop-pending` | A bare-command hard-reserve reset's stop intent survives the window change. It retains the tool request for construction retry, but stops without a second wipe after commit. |
50
49
 
51
- Overflow phases are `idle`, `pending`, `spent`, and `pending-spent`. `turn_end` arms enabled recovery; `agent_before_settle` waits for queued work and spends at most one attempt. A successful queued turn supersedes the failure. Command overflow also spends the attempt before continuing. Abort, final settlement, session start/tree/shutdown and `/notesoup off` clear transient state.
50
+ `stopAfterReset` is separate from the request. It retains the safety boundary's intent after construction, while `request` becomes `none`. Settlement waits for queued work; if the window changed, it stops without a second wipe. If the window did not change, the boundary never committed, so settlement retries the retained intent with its stop policy and tool origin intact. A successful settle retry consumes the latch.
51
+
52
+ Overflow phases are `idle`, `pending`, `spent`, and `pending-spent`. `turn_end` arms enabled recovery; `agent_before_settle` waits for queued work and selects recovery intent. Only successful, current construction reaches finalization and spends the attempt. A successful queued turn supersedes the failure. Command overflow spends the same bounded attempt before continuing. Abort, final settlement, session start/tree/shutdown and `/notesoup off` clear transient state.
52
53
 
53
54
  The adapter collects actual user `message_end` content until settlement or a successful reset boundary. Low-level `agent_start` events do not clear it: Pi can start additional loops while draining follow-ups/recovering. Custom boot/warning/continuation messages are never mistaken for human input. Successful boundary construction clears this run collection, so an automatic continuation does not replay old input.
54
55
 
55
- Command state remains live during asynchronous notes acquisition. Inputs arriving during construction join that same boundary and override a proposed stop. Hidden steers carry window/command identity; provider projection excludes them once that command ends, including steers Pi delivers only after the reset. Originals remain available exactly once as carried input. Construction captures session/window generations and rechecks identity, enabled state and abort status before returning drafts. Stale work preserves incoming/budget entries but discards reset drafts; construction failures notify only while current and do not claim continuation. If close-out cannot commit, stashed originals are restored with public `sendMessage(..., { triggerTurn: false })`, including cancellation during construction; clearing command state must not erase input already reported as handled.
56
+ Command state remains live during asynchronous notes acquisition. Boundary intent captures the trigger, explicit `continueAfterReset` policy, tool fact and origin, but contains no final state or continuation decision. After construction passes the currentness guard, the pure finalizer selects live command-owned originals, or the current run's inputs only for passive recovery, and resolves `resumeModel` and the next control state together. `resumeModel` is true when the policy requests continuation or carried input needs an answer; the adapter maps it to Pi's `continue` field. Late originals therefore join the same boundary and prevent a stop latch from being installed; delivery contents never replace explicit command policy. Hidden steers carry window/command identity; provider projection excludes them once that command ends, including steers Pi delivers only after the reset. Originals remain available exactly once as carried input. Construction captures session/window generations and rechecks identity, enabled state and abort status before returning drafts. Clearing the run invalidates any unfinished construction before resetting its input collection. Stale work preserves incoming/budget entries but discards reset drafts; construction failures notify only while current and do not claim continuation. If close-out cannot commit, stashed originals are restored with public `sendMessage(..., { triggerTurn: false })`, including cancellation during construction; clearing command state must not erase input already reported as handled.
56
57
 
57
58
  After a manual safety reset, `context_with_system` checks the committed boundary before using public `ctx.abort()` to cancel an unavoidable empty tool follow-up with system-only context. Pending messages, ordinary user entries or carried inputs after the marker bypass cancellation. Later user prompts are not affected by the run-scoped stop latch.
58
59
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.51.2",
3
+ "version": "0.51.3",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.51.2",
3
+ "version": "0.51.3",
4
4
  "description": "Durable notes and a host-scoped notes boot section for Claude Code.",
5
5
  "author": {
6
6
  "name": "AstroSheep"
@@ -38,8 +38,6 @@ function isOverflowLike(message: AgentMessage, ctx: ExtensionContext): boolean {
38
38
 
39
39
  export type ResetRequest =
40
40
  | { readonly phase: "none" }
41
- // A hard-reserve reset may precede the end of Pi's tool-batch continuation.
42
- | { readonly phase: "stop-pending"; readonly windowId: string; readonly tool?: { readonly lastWord?: string } }
43
41
  | { readonly phase: "pending"; readonly windowId: string;
44
42
  readonly command?: { readonly continueAfterReset: boolean; readonly inputs?: readonly CarriedInput[] };
45
43
  readonly tool?: { readonly lastWord?: string } };
@@ -47,6 +45,8 @@ export type ResetOverflowPhase = "idle" | "pending" | "pending-spent" | "spent";
47
45
 
48
46
  export interface ResetControlState {
49
47
  readonly request: ResetRequest;
48
+ /** Await settlement after a safety reset; retain its intent to retry if it never committed. */
49
+ readonly stopAfterReset?: ResetBoundaryIntent;
50
50
  readonly overflow: ResetOverflowPhase;
51
51
  }
52
52
 
@@ -85,47 +85,48 @@ export type ResetControlEvent =
85
85
  | { readonly type: "turn_end"; readonly facts: ResetTurnEndFacts }
86
86
  | { readonly type: "before_settle"; readonly facts: ResetBeforeSettleFacts };
87
87
 
88
- export type ResetControlEffect =
89
- | "none"
90
- | "close-out-armed"
91
- | "already-pending"
92
- | "commit-boundary"
93
- | "commit-boundary-stop"
94
- | "stop"
95
- | "recover-overflow";
96
-
97
- export interface ResetControlResult {
98
- readonly state: ResetControlState;
99
- readonly effect: ResetControlEffect;
100
- readonly lastWord?: string;
101
- /** The origin of the boundary this decision commits. Absent means no `empty_brain` call was recorded, so forced. */
102
- readonly origin?: ResetOrigin;
88
+ /** Construction intent, not final state: handled inputs can still arrive while notes load. Only `turn-end`
89
+ * may latch a stop; overflow kinds spend recovery; only `overflow-recovery` carries passive run inputs. */
90
+ export interface ResetBoundaryIntent {
91
+ readonly effect: "build-boundary";
92
+ readonly boundary: "turn-end" | "settle" | "command-overflow" | "overflow-recovery";
93
+ readonly windowId: string;
94
+ readonly continueAfterReset: boolean;
95
+ readonly origin: ResetOrigin;
96
+ readonly tool?: { readonly lastWord?: string };
103
97
  }
104
98
 
99
+ export type ResetControlResult = ResetBoundaryIntent |
100
+ { readonly state: ResetControlState; readonly effect: "none" | "close-out-armed" | "already-pending" | "stop" };
101
+
105
102
  function requestForWindow(request: ResetRequest, windowId: string): ResetRequest {
106
- return request.phase === "stop-pending" || (request.phase !== "none" && request.windowId === windowId) ? request : NO_REQUEST;
103
+ return request.phase === "pending" && request.windowId === windowId ? request : NO_REQUEST;
107
104
  }
108
105
 
109
- function commandContinues(request: Extract<ResetRequest, { phase: "pending" }>): boolean {
110
- return request.command?.continueAfterReset === true || (request.command?.inputs?.length ?? 0) > 0;
111
- }
106
+ const spendsOverflow = (boundary: ResetBoundaryIntent["boundary"]) => boundary === "command-overflow" || boundary === "overflow-recovery";
112
107
 
113
- function commandCommit(request: Extract<ResetRequest, { phase: "pending" }>, overflow = false): ResetControlResult {
114
- return {
115
- state: { request: NO_REQUEST, overflow: overflow ? "spent" : "idle" },
116
- effect: commandContinues(request) ? "commit-boundary" : "commit-boundary-stop",
117
- ...requestDetails(request),
118
- ...(overflow ? { origin: "forced" as const } : {}),
119
- };
108
+ function boundaryIntent(request: ResetRequest, windowId: string, boundary: ResetBoundaryIntent["boundary"]): ResetBoundaryIntent {
109
+ const tool = request.phase === "none" ? undefined : request.tool;
110
+ const continueAfterReset = request.phase === "pending" ? request.command?.continueAfterReset ?? true : true;
111
+ return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal" };
120
112
  }
121
113
 
122
- /** The tool request itself is the origin fact; the stop latch retains it for construction retry. */
123
- function requestDetails(request: ResetRequest): { origin: ResetOrigin; lastWord?: string } {
124
- const tool = request.phase === "none" ? undefined : request.tool;
125
- return { origin: tool ? "normal" : "forced", ...tool };
114
+ /** Resolve once, after a successful current build. No delivery policy is left to the adapter. */
115
+ export function finalizeResetBoundary(intent: ResetBoundaryIntent, request: ResetRequest, passiveInputs: readonly CarriedInput[] = []) {
116
+ const inputs = request.phase === "pending" && request.command ? request.command.inputs ?? []
117
+ : intent.boundary === "overflow-recovery" ? passiveInputs : [];
118
+ const resumeModel = intent.continueAfterReset || inputs.length > 0;
119
+ const state: ResetControlState = {
120
+ request: NO_REQUEST,
121
+ ...(intent.boundary === "turn-end" && !resumeModel ? { stopAfterReset: intent } : {}),
122
+ overflow: spendsOverflow(intent.boundary) ? "spent" : "idle",
123
+ };
124
+ return { state, inputs, resumeModel };
126
125
  }
127
126
 
128
127
  /** Pure transitions: command policy schedules a reset without disguising actual tool calls. */
128
+ export function reduceResetControl(state: ResetControlState, event: Extract<ResetControlEvent, { type: "input" | "command" | "tool_request" }>): Extract<ResetControlResult, { state: ResetControlState }>;
129
+ export function reduceResetControl(state: ResetControlState, event: ResetControlEvent): ResetControlResult;
129
130
  export function reduceResetControl(state: ResetControlState, event: ResetControlEvent): ResetControlResult {
130
131
  switch (event.type) {
131
132
  case "input": {
@@ -135,8 +136,8 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
135
136
  }
136
137
  case "command":
137
138
  case "tool_request": {
139
+ if (state.stopAfterReset) return { state, effect: "already-pending" };
138
140
  const current = requestForWindow(state.request, event.windowId);
139
- if (current.phase === "stop-pending") return { state, effect: "already-pending" };
140
141
  const request = current.phase === "pending" ? current : { phase: "pending" as const, windowId: event.windowId };
141
142
  if (event.type === "command") {
142
143
  if (request.command) return { state, effect: "already-pending" };
@@ -152,7 +153,7 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
152
153
  const facts = event.facts;
153
154
  const request = requestForWindow(state.request, facts.windowId);
154
155
  if (facts.aborted) return { state: initialResetControl(), effect: "none" };
155
- if (request.phase === "stop-pending") return { state: { request, overflow: "idle" }, effect: "none" };
156
+ if (state.stopAfterReset) return { state: { ...state, overflow: "idle" }, effect: "none" };
156
157
  const manual = request.phase === "pending" && request.command !== undefined;
157
158
  if (facts.overflow) {
158
159
  const pending = manual ? facts.enabled : !facts.queued && facts.enabled && facts.automaticResetEnabled;
@@ -169,9 +170,7 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
169
170
  // A direct tool request commits after the whole tool batch. The budget cutoff is
170
171
  // a separate hard-reserve safety path; ordinary close-out waits for settlement.
171
172
  if ((request.phase === "pending" && request.tool && !manual) || facts.hardReserveDue) {
172
- if (manual && commandContinues(request)) return commandCommit(request);
173
- if (manual) return { state: { request: { phase: "stop-pending", windowId: facts.windowId, ...(request.tool ? { tool: request.tool } : {}) }, overflow: "idle" }, effect: "commit-boundary-stop", ...requestDetails(request) };
174
- return { state: { request: NO_REQUEST, overflow: "idle" }, effect: "commit-boundary", ...requestDetails(request) };
173
+ return boundaryIntent(request, facts.windowId, "turn-end");
175
174
  }
176
175
  return { state: { request, overflow: "idle" }, effect: "none" };
177
176
  }
@@ -179,12 +178,12 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
179
178
  const facts = event.facts;
180
179
  if (facts.aborted) return { state: initialResetControl(), effect: "none" };
181
180
  const request = requestForWindow(state.request, facts.windowId);
182
- if (request.phase === "stop-pending") {
181
+ if (state.stopAfterReset) {
183
182
  if (facts.queued) return { state, effect: "none" };
184
- // Only retry construction if the safety boundary never committed. Otherwise
185
- // stop without a second wipe, even if a queued turn subsequently failed.
186
- if (request.windowId !== facts.windowId) return { state: initialResetControl(), effect: "stop" };
187
- return { state: initialResetControl(), effect: facts.failed || !facts.enabled ? "none" : "commit-boundary-stop", ...requestDetails(request) };
183
+ // A changed window confirms commit: stop without wiping twice. Otherwise retry.
184
+ if (state.stopAfterReset.windowId !== facts.windowId) return { state: initialResetControl(), effect: "stop" };
185
+ if (facts.failed || !facts.enabled) return { state: initialResetControl(), effect: "none" };
186
+ return { ...state.stopAfterReset, boundary: "settle" };
188
187
  }
189
188
  const manual = request.phase === "pending" && request.command !== undefined;
190
189
  if (state.overflow === "pending" || state.overflow === "pending-spent") {
@@ -193,18 +192,19 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
193
192
  }
194
193
  // An explicit manual wipe is not an automatic recovery/retry. It must still
195
194
  // clear on overflow, including when automatic reset is disabled.
196
- if (manual && facts.enabled) return commandCommit(request, true);
195
+ if (manual && facts.enabled) return boundaryIntent(request, facts.windowId, "command-overflow");
197
196
  const spent = state.overflow === "pending-spent";
198
197
  if (!facts.enabled || !facts.automaticResetEnabled) {
199
198
  return { state: { request: facts.failed ? NO_REQUEST : request, overflow: spent ? "spent" : "idle" }, effect: "none" };
200
199
  }
201
- return { state: { request: NO_REQUEST, overflow: "spent" }, effect: spent ? "none" : "recover-overflow", ...requestDetails(request) };
200
+ if (spent) return { state: { request: NO_REQUEST, overflow: "spent" }, effect: "none" };
201
+ return boundaryIntent(request, facts.windowId, "overflow-recovery");
202
202
  }
203
203
  if (facts.failed || !facts.enabled || !manual) {
204
204
  return { state: { ...state, request: NO_REQUEST }, effect: "none" };
205
205
  }
206
206
  if (facts.queued) return { state: { ...state, request }, effect: "none" };
207
- return commandCommit(request);
207
+ return boundaryIntent(request, facts.windowId, "settle");
208
208
  }
209
209
  }
210
210
  }
@@ -234,16 +234,15 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
234
234
  runInputs.push(...inputs);
235
235
  };
236
236
  const clear = (preserveInputs = true) => {
237
+ lifecycleGeneration++;
237
238
  if (preserveInputs) restoreCommandInputs();
238
239
  control = initialResetControl();
239
240
  runInputs = [];
240
241
  commandId = undefined;
241
242
  };
242
- const resetBoundaryResult = async (entries: SessionBoundaryDraft[], ctx: ExtensionContext, decision: ResetControlResult) => {
243
+ const resetBoundaryResult = async (entries: SessionBoundaryDraft[], ctx: ExtensionContext, intent: ResetBoundaryIntent) => {
243
244
  // Keep command state live while notes load: input arriving during this await must
244
245
  // join this very boundary even if its steer cannot reach the closing model.
245
- const passiveInputs = decision.effect === "recover-overflow" ? runInputs : [];
246
- const origin = decision.origin ?? "forced";
247
246
  const generation = lifecycleGeneration;
248
247
  const outerGeneration = options.getLifecycleGeneration?.();
249
248
  const sessionId = ctx.sessionManager.getSessionId();
@@ -255,19 +254,17 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
255
254
  const firstSeq = nextHistorySeq(ctx, entries) + 1;
256
255
  let resetDrafts: SessionBoundaryDraft[];
257
256
  try {
258
- resetDrafts = await options.buildReset(ctx, isCurrent, decision.lastWord, firstSeq, origin);
257
+ resetDrafts = await options.buildReset(ctx, isCurrent, intent.tool?.lastWord, firstSeq, intent.origin);
259
258
  } catch (error) {
260
259
  if (isCurrent()) ctx.ui.notify(`🥣 Brain still full: ${errorMessage(error)}`, "warning");
261
260
  return entries.length > 0 ? { entries } : undefined;
262
261
  }
263
262
  if (!isCurrent()) return entries.length > 0 ? { entries } : undefined;
264
- const request = control.request;
265
- const inputs = request.phase === "pending" && request.command ? request.command.inputs ?? [] : passiveInputs;
266
- control = decision.state;
267
- if (inputs.length > 0 && control.request.phase === "stop-pending") control = { ...control, request: NO_REQUEST };
263
+ const finalized = finalizeResetBoundary(intent, control.request, runInputs);
264
+ control = finalized.state;
268
265
  runInputs = [];
269
266
  options.onResetReady?.(ctx, resetDrafts);
270
- return { entries: [...entries, ...resetDrafts, ...carriedInputDrafts(inputs)], continue: inputs.length > 0 || decision.effect !== "commit-boundary-stop" };
267
+ return { entries: [...entries, ...resetDrafts, ...carriedInputDrafts(finalized.inputs)], continue: finalized.resumeModel };
271
268
  };
272
269
 
273
270
  // Pi may start multiple low-level loops while draining follow-ups/recovering.
@@ -304,9 +301,10 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
304
301
  request.windowId === currentWindowId(ctx) && details?.windowId === request.windowId && commandId !== undefined && details?.commandId === commandId;
305
302
  });
306
303
  const filtered = messages.length === event.messages.length ? undefined : { messages };
307
- if (!sessionActive || request.phase !== "stop-pending" || ctx.hasPendingMessages()) return filtered;
304
+ const stop = control.stopAfterReset;
305
+ if (!sessionActive || !stop || ctx.hasPendingMessages()) return filtered;
308
306
  const marker = currentReset(ctx);
309
- if (!marker || marker.data.windowId === request.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId)) return filtered;
307
+ if (!marker || marker.data.windowId === stop.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId)) return filtered;
310
308
  const branch = ctx.sessionManager.getBranch();
311
309
  const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
312
310
  if (branch.slice(markerIndex + 1).some((entry) => (entry.type === "message" && entry.message.role === "user") || isCarriedInputEntry(entry))) return filtered;
@@ -334,7 +332,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
334
332
  get hardReserveDue() { return options.budget.hardReserveDue(ctx); },
335
333
  },
336
334
  });
337
- if (decision.effect === "commit-boundary" || decision.effect === "commit-boundary-stop") return await resetBoundaryResult(entries, ctx, decision);
335
+ if (decision.effect === "build-boundary") return await resetBoundaryResult(entries, ctx, decision);
338
336
  if (aborted || (event.outcome === "error" && decision.state.request.phase === "none")) restoreCommandInputs();
339
337
  control = decision.state;
340
338
  return entries.length > 0 ? { entries } : undefined;
@@ -353,7 +351,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
353
351
  failed: event.outcome === "error",
354
352
  },
355
353
  });
356
- if (decision.effect === "commit-boundary" || decision.effect === "commit-boundary-stop" || decision.effect === "recover-overflow") return await resetBoundaryResult(event.entries, ctx, decision);
354
+ if (decision.effect === "build-boundary") return await resetBoundaryResult(event.entries, ctx, decision);
357
355
  if (decision.state.request.phase === "none") restoreCommandInputs();
358
356
  control = decision.state;
359
357
  if (decision.effect === "stop") return { entries: event.entries, continue: false };
@@ -379,9 +377,9 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
379
377
  pi.on("agent_settled", () => {
380
378
  clear();
381
379
  });
382
- pi.on("session_start", () => { lifecycleGeneration++; clear(false); sessionActive = true; });
383
- pi.on("session_tree", () => { lifecycleGeneration++; clear(false); });
384
- pi.on("session_shutdown", () => { lifecycleGeneration++; clear(false); options.budget.clear(); sessionActive = false; });
380
+ pi.on("session_start", () => { clear(false); sessionActive = true; });
381
+ pi.on("session_tree", () => { clear(false); });
382
+ pi.on("session_shutdown", () => { clear(false); options.budget.clear(); sessionActive = false; });
385
383
 
386
384
  return {
387
385
  command(windowId: string, continueAfterReset: boolean, input?: CarriedInput) {