notesoup 0.58.1 → 0.58.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.
Files changed (49) hide show
  1. package/README.md +1 -1
  2. package/dist/src/boot/text.d.ts +1 -1
  3. package/dist/src/boot/text.js +5 -4
  4. package/dist/src/notes/policy.d.ts +1 -1
  5. package/dist/src/notes/policy.js +4 -3
  6. package/dist/src/tools/notes.js +1 -1
  7. package/dist/test/agent-loop.test.js +13 -39
  8. package/dist/test/boot.integration.test.js +20 -18
  9. package/dist/test/budget-settings.integration.test.js +18 -13
  10. package/dist/test/claude-history.test.js +1 -2
  11. package/dist/test/claude-mod.test.js +417 -87
  12. package/dist/test/codex-history.test.js +9 -6
  13. package/dist/test/codex-plugin.test.js +4 -8
  14. package/dist/test/dream-skill.test.js +6 -10
  15. package/dist/test/dsh-cli.test.js +2 -3
  16. package/dist/test/dsh.test.js +1 -7
  17. package/dist/test/helpers/extension.js +3 -1
  18. package/dist/test/history-corpus.test.js +2 -3
  19. package/dist/test/history-prefilter.test.js +33 -40
  20. package/dist/test/history-summary-cache.test.js +1 -1
  21. package/dist/test/history.integration.test.js +11 -37
  22. package/dist/test/host-neutral.test.js +2 -2
  23. package/dist/test/marker.test.js +1 -2
  24. package/dist/test/model-facing-text.test.js +20 -187
  25. package/dist/test/note-policy.test.js +40 -22
  26. package/dist/test/notes-library.test.js +2 -2
  27. package/dist/test/notes.integration.test.js +36 -149
  28. package/dist/test/notes.test.js +13 -61
  29. package/dist/test/pi-render.test.js +23 -62
  30. package/dist/test/reset-lifecycle.test.js +4 -9
  31. package/docs/architecture.md +1 -1
  32. package/docs/claude-code-mod.md +15 -3
  33. package/docs/dsh.md +1 -1
  34. package/docs/notes-library.md +1 -1
  35. package/docs/tool-results.md +1 -1
  36. package/package.json +1 -1
  37. package/playbook.md +1 -1
  38. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  39. package/plugins/claude/dist/claude/helper.js +10 -8
  40. package/plugins/claude/hooks/register.ts +198 -130
  41. package/plugins/claude/playbook.md +1 -1
  42. package/plugins/claude/skills/dream/SKILL.md +1 -1
  43. package/plugins/claude/skills/memory/SKILL.md +1 -1
  44. package/plugins/codex/dist/codex/notesoup.js +10 -8
  45. package/skills/dream/SKILL.md +1 -1
  46. package/skills/memory/SKILL.md +1 -1
  47. package/src/boot/text.ts +5 -4
  48. package/src/notes/policy.ts +4 -3
  49. package/src/tools/notes.ts +1 -1
@@ -8,7 +8,7 @@ const OUTPUT_LIMIT = 1024 * 1024
8
8
  type Identity = { home: string; sessionId: string; cwd: string; agent: string; model: string }
9
9
  type SchemaRow = { name: string; description: string; inputSchema: Record<string, unknown> }
10
10
  type HistorySource = { sessionId: string; transcriptPath: string; headUuid?: string }
11
- type Engine = Pick<EngineInterface, "process" | "session" | "ui" | "clock" | "prompt" | "env" | "settings" | "command">
11
+ type Engine = Pick<EngineInterface, "process" | "session" | "ui" | "prompt" | "env" | "settings" | "command">
12
12
  /** The measured context, as much of it as the engine reported. */
13
13
  type ContextUsage = { tokens?: number; window?: number; percent?: number }
14
14
  /** Shared reset prose, fetched once per session so Pi and Claude cannot drift apart. */
@@ -17,14 +17,78 @@ type ClaudeLimits = {
17
17
  source: string; autoCompact: boolean; unit: "tokens" | "percent"
18
18
  native: number; reset: number; warn: number; resetMargin: number; warningRunway: number
19
19
  }
20
+ type ResetRequest = { tool?: { lastWord?: string }; resume: boolean }
21
+ /** Request: until consumed/cancelled. Cutoff: one turn, even after auto consumes the request.
22
+ * Commit lives separately in ResetState: one native command attempt, proved by kept rows. */
23
+ class ResetFlow {
24
+ request?: ResetRequest
25
+ cutoffTurnId?: string
26
+ turnId?: string
27
+ pendingInputTurnId?: string
28
+ running = false
29
+
30
+ requestReset(tool?: { lastWord?: string; terminate: boolean }): boolean {
31
+ const first = tool ? this.request?.tool === undefined : this.request === undefined
32
+ const request = this.request ??= { resume: true }
33
+ if (tool) {
34
+ if (first) {
35
+ request.tool = { lastWord: tool.lastWord }
36
+ request.resume &&= !tool.terminate
37
+ }
38
+ this.cutoffTurnId = this.turnId
39
+ } else request.resume = false
40
+ return first
41
+ }
42
+ input(turnId?: string) {
43
+ if (turnId !== undefined) this.pendingInputTurnId = turnId
44
+ if (this.request?.tool) this.request.resume = false
45
+ }
46
+ start(turnId: string) {
47
+ if (this.request?.tool) this.request.resume = false
48
+ this.turnId = turnId
49
+ this.running = true
50
+ }
51
+ cutoff(turnId: string): boolean {
52
+ // Input may predate the tool latch. Release the whole workflow, not just one request.
53
+ if (this.pendingInputTurnId !== undefined && this.pendingInputTurnId === turnId) {
54
+ this.pendingInputTurnId = undefined
55
+ this.cutoffTurnId = undefined
56
+ if (this.request) this.request.resume = false
57
+ return false
58
+ }
59
+ return turnId === this.cutoffTurnId
60
+ }
61
+ complete(reason: string): boolean {
62
+ this.running = false
63
+ const cancelled = reason !== "answer" && this.request !== undefined
64
+ if (cancelled || !this.request) this.cancel()
65
+ return cancelled
66
+ }
67
+ get ready(): boolean {
68
+ return !!this.request && !this.running && !(this.pendingInputTurnId !== undefined && this.pendingInputTurnId === this.turnId)
69
+ }
70
+ consume(auto = false): boolean {
71
+ const request = this.request
72
+ // Another auto reset must not disarm an already consumed request's cutoff.
73
+ if (auto && !request) return false
74
+ this.cutoffTurnId = auto && request && !request.resume ? this.cutoffTurnId ?? (!request.tool ? this.turnId : undefined) : undefined
75
+ this.request = undefined
76
+ return request?.tool !== undefined && request.resume
77
+ }
78
+ cancel() {
79
+ this.request = undefined
80
+ this.cutoffTurnId = undefined
81
+ }
82
+ }
20
83
  type ResetState = {
21
- identity?: Identity; history?: HistorySource; historyWindowHead?: string; generation: number; window: number; disabled: boolean; turnRunning: boolean; resetting: boolean
22
- manualPending: boolean; headless: boolean; usageFailureLogged: boolean; preparedBoot?: string; retainedBoot?: string
23
- toolResetRequested?: boolean; lastWord?: string; manualCompacting?: boolean
24
- continuation?: string; continuationWindow?: number
84
+ identity?: Identity; history?: HistorySource; historyWindowHead?: string; generation: number; window: number; disabled: boolean; flow: ResetFlow
85
+ headless: boolean; usageFailureLogged: boolean; commit?: { instructions: string; boot?: string; boundary: boolean; resolve: (kept: boolean) => void }; retainedBoot?: string
86
+ continuation?: { window: number; text: string }
25
87
  compactDisabled: boolean; limitsFailureLogged: boolean; limitsAttempts: number; limitsKey?: string
26
88
  limits?: ClaudeLimits; warnedWindow?: number; warningPending?: number; texts?: SharedTexts; settingsFailureLogged: boolean
27
89
  }
90
+ type ResetWork = { kind: "closeout" | "reset"; generation: number }
91
+ type ResetSignal = { wake?: (work: ResetWork) => void }
28
92
  const COMPACT_DISABLED = "Brain can't be emptied with DISABLE_COMPACT"
29
93
  const NOTESOUP_DISABLED = "Notesoup is off with NOTESOUP_DISABLED"
30
94
  const THRESHOLDS_UNAVAILABLE = "Brain size unknown · no budget warning"
@@ -61,7 +125,7 @@ async function resetMessages($: Engine, state: ResetState, identity: Identity):
61
125
  return { boot: text, messages: [
62
126
  { role: "user", text, toolUses: [] },
63
127
  { role: "user", text: continuation, toolUses: [] },
64
- ...(state.lastWord ? [{ role: "user" as const, text: `*You peel a sticky note off your forehead.*\n${state.lastWord}`, toolUses: [] as [] }] : []),
128
+ ...(state.flow.request?.tool?.lastWord ? [{ role: "user" as const, text: `*You peel a sticky note off your forehead.*\n${state.flow.request.tool.lastWord}`, toolUses: [] as [] }] : []),
65
129
  ] }
66
130
  }
67
131
  function numberOf(value: unknown): number | undefined {
@@ -185,15 +249,14 @@ async function loadTexts($: Engine, state: ResetState): Promise<SharedTexts | un
185
249
  }
186
250
  /** One draw per reset artifact, reused on retry; only a real tool request is voluntary. */
187
251
  async function continuationFor($: Engine, state: ResetState): Promise<string | undefined> {
188
- if (state.continuation !== undefined && state.continuationWindow === state.window) return state.continuation
252
+ if (state.continuation?.window === state.window) return state.continuation.text
189
253
  const generation = state.generation
190
- const response = await run($, { op: "continuation", origin: state.toolResetRequested ? "normal" : "forced" })
254
+ const response = await run($, { op: "continuation", origin: state.flow.request?.tool ? "normal" : "forced" })
191
255
  if (generation !== state.generation) return undefined
192
256
  const result = response.ok ? response.result : undefined
193
257
  const text = typeof result === "object" && result !== null ? (result as { text?: unknown }).text : undefined
194
258
  if (typeof text !== "string" || text.length === 0) return undefined
195
- state.continuation = text
196
- state.continuationWindow = state.window
259
+ state.continuation = { window: state.window, text }
197
260
  return text
198
261
  }
199
262
  function log($: Engine, text: string) {
@@ -230,23 +293,19 @@ async function run($: { process: { run: (argv: readonly string[], init?: { cwd?:
230
293
  // reason (`timed out after …`), which a bare phrase would throw away.
231
294
  catch (error) { return { ok: false as const, error: `helper execution failed: ${describeFailure(error)}` } }
232
295
  }
233
- function clearManualRequest(state: ResetState): void {
234
- state.manualPending = false
235
- state.toolResetRequested = state.lastWord = undefined
236
- }
237
296
  /** Session start does not fire on /clear, /resume or /branch. Forget the old window on end. */
238
297
  function forgetSession(state: ResetState) {
239
298
  state.generation++
240
299
  state.identity = undefined
241
300
  state.historyWindowHead = undefined
242
301
  state.window = 0
243
- state.turnRunning = state.resetting = state.usageFailureLogged = false
244
- clearManualRequest(state)
245
- state.manualCompacting = false
246
- state.preparedBoot = state.retainedBoot = undefined
302
+ state.flow = new ResetFlow()
303
+ state.usageFailureLogged = false
304
+ state.commit?.resolve(false)
305
+ state.commit = undefined
306
+ state.retainedBoot = undefined
247
307
  state.texts = state.limits = undefined
248
308
  state.continuation = undefined
249
- state.continuationWindow = undefined
250
309
  state.limitsAttempts = 0
251
310
  state.limitsKey = undefined
252
311
  state.settingsFailureLogged = state.limitsFailureLogged = false
@@ -269,7 +328,7 @@ async function refreshIdentity($: Engine, state: ResetState): Promise<Identity |
269
328
  if (state.identity?.sessionId === sessionId) {
270
329
  state.identity = { ...state.identity, cwd, model }
271
330
  await syncHistoryWindow($, state)
272
- return state.identity
331
+ return generation === state.generation ? state.identity : undefined
273
332
  }
274
333
  const home = await $.env.get("NOTESOUP_HOME") ?? `${await $.env.get("HOME") ?? await $.env.get("USERPROFILE") ?? ""}/.agents/notes`
275
334
  if (generation !== state.generation) return undefined
@@ -288,7 +347,7 @@ async function refreshIdentity($: Engine, state: ResetState): Promise<Identity |
288
347
 
289
348
  /** A committed append is the head evidence; the persisted file may trail it briefly. */
290
349
  async function syncHistoryWindow($: Engine, state: ResetState) {
291
- if (!state.identity || !state.history?.headUuid || state.history.sessionId !== state.identity.sessionId || state.resetting || state.historyWindowHead === state.history.headUuid) return
350
+ if (!state.identity || !state.history?.headUuid || state.history.sessionId !== state.identity.sessionId || state.commit || state.historyWindowHead === state.history.headUuid) return
292
351
  const generation = state.generation, head = state.history.headUuid
293
352
  const response = await run($, { op: "history_state", identity: state.identity, history: state.history })
294
353
  if (generation !== state.generation || state.history?.headUuid !== head || !response.ok || typeof response.result !== "object" || response.result === null) return
@@ -299,8 +358,8 @@ async function syncHistoryWindow($: Engine, state: ResetState) {
299
358
  }
300
359
 
301
360
  export function register(on: On) {
302
- const manualSignal: { wake?: () => void } = {}
303
- const state: ResetState = { generation: 0, window: 0, disabled: false, turnRunning: false, resetting: false, manualPending: false, headless: false, usageFailureLogged: false, compactDisabled: false, limitsFailureLogged: false, limitsAttempts: 0, settingsFailureLogged: false }
361
+ const resetSignal: ResetSignal = {}
362
+ const state: ResetState = { generation: 0, window: 0, disabled: false, flow: new ResetFlow(), headless: false, usageFailureLogged: false, compactDisabled: false, limitsFailureLogged: false, limitsAttempts: 0, settingsFailureLogged: false }
304
363
  const registered = new Set<string>()
305
364
  let keepMemory = false
306
365
  // Classic SessionStart precedes typed session.start and startup appends. Keep this binding
@@ -313,11 +372,26 @@ export function register(on: On) {
313
372
  return next(e)
314
373
  })
315
374
  on("session.append", async ($, e, next) => {
375
+ const generation = state.generation, commit = state.commit
316
376
  const sessionId = await $.session.id(), source = state.history
317
377
  const result = await next(e)
318
- if (e.agentId === undefined && result.uuid !== undefined && state.history === source && source?.sessionId === sessionId) {
319
- source.headUuid = result.uuid
320
- state.historyWindowHead = undefined
378
+ if (e.agentId === undefined && result.uuid !== undefined && generation === state.generation) {
379
+ if (state.history === source && source?.sessionId === sessionId) {
380
+ source.headUuid = result.uuid
381
+ state.historyWindowHead = undefined
382
+ }
383
+ // A native command resolves before its compaction rows finish appending;
384
+ // session.messages() still exposes the last request's snapshot. Observe
385
+ // the host's kept boundary and first plugin row, including rewrites.
386
+ if (commit && commit === state.commit && state.identity?.sessionId === sessionId) {
387
+ if (e.door === "compaction" && result.message.name === "compact_boundary") commit.boundary = true
388
+ if (e.origin.kind === "plugin" && "name" in e.origin && e.origin.name === "notesoup") {
389
+ if (commit.boundary && e.door === "prompt") {
390
+ const blocks = result.message.content
391
+ commit.resolve(result.message.type === "user" && blocks.length === 1 && blocks[0]?.type === "text" && blocks[0].text === commit.boot)
392
+ } else if (e.door === "command") commit.resolve(false)
393
+ }
394
+ }
321
395
  }
322
396
  return result
323
397
  })
@@ -337,13 +411,13 @@ export function register(on: On) {
337
411
  if (state.compactDisabled) log($, COMPACT_DISABLED)
338
412
  registered.clear()
339
413
  await loadTexts($, state)
340
- armManual($, state, manualSignal)
414
+ armReset($, state, resetSignal)
341
415
  await $.command.register({ name: "empty", description: "Reset context to a fresh notes-only window", immediate: true })
342
416
  await $.command.register({ name: "fresh-window", description: "Reset context to a fresh notes-only window", immediate: true })
343
417
  const wipe = await $.tool.register({
344
418
  name: "empty_brain",
345
419
  description: "Clear your in-context memory and start a fresh context window. Your session, notes, and history survive. Pass `last_word` to stick a tiny note on your forehead for after the wipe.",
346
- inputSchema: { type: "object", properties: { last_word: { type: "string", description: "A tiny sticky note, at most 300 characters. After the wipe it is slapped on your forehead; longer notes are refused." } }, additionalProperties: false },
420
+ inputSchema: { type: "object", properties: { last_word: { type: "string", description: "A tiny sticky note, at most 300 characters. After the wipe it is slapped on your forehead; longer notes are refused." }, terminate: { type: "boolean", description: "Stop after the wipe. Default: false.", default: false } }, additionalProperties: false },
347
421
  isDeferred: false,
348
422
  } satisfies ToolSpec)
349
423
  registered.add(wipe.tool)
@@ -367,70 +441,73 @@ export function register(on: On) {
367
441
  if (e.agentId !== undefined || result.deny !== undefined || generation !== state.generation) return result
368
442
  return withWarning($, state, (warning) => warning === undefined ? result : { ...result, context: [...(result.context ?? []), warning] })
369
443
  })
370
- on("prompt.submit", ($, e, next) => withWarning($, state, (warning) =>
371
- next(warning === undefined ? e : { ...e, context: [...(e.context ?? []), warning] })))
444
+ on("prompt.submit", async ($, e, next) => {
445
+ const generation = state.generation
446
+ const result = await withWarning($, state, (warning) =>
447
+ next(warning === undefined ? e : { ...e, context: [...(e.context ?? []), warning] }))
448
+ // Our own submissions skip this hook; accepted input owns the continuation.
449
+ if (generation === state.generation && result.drop === undefined) state.flow.input(e.turnId)
450
+ return result
451
+ })
372
452
  on("turn.start", async ($, e, next) => {
373
453
  // The documented turn.start is main-loop only. Guard tagged host events too:
374
454
  // only a main-agent turn.complete clears this latch.
375
455
  if (state.disabled) return next(e)
376
456
  if ("agentId" in e && e.agentId !== undefined) return next(e)
377
457
  if (!await refreshIdentity($, state)) return next(e)
378
- state.turnRunning = true
458
+ state.flow.start(e.turnId)
379
459
  return next(e)
380
460
  })
461
+ on("turn.step", async function* ($, e, next) {
462
+ if (state.disabled || e.agentId !== undefined) return yield* next(e)
463
+ if (!state.flow.cutoff(e.turnId)) return yield* next(e)
464
+ // This boundary follows the entire tool batch. A synthetic streamed stop
465
+ // ends the main turn without aborting siblings or making an old-window request.
466
+ yield { kind: "stop", stopReason: "end_turn", usage: null }
467
+ return { turnId: e.turnId, index: e.index, answer: "", toolUses: [], stopReason: "end_turn", usage: null }
468
+ })
381
469
  on("turn.complete", async ($, e, next) => {
470
+ const generation = state.generation
382
471
  const result = await next(e)
383
- if (e.agentId !== undefined) return result
384
- state.turnRunning = false
472
+ if (e.agentId !== undefined || generation !== state.generation) return result
473
+ const cancelled = state.flow.complete(e.reason)
385
474
  if (state.disabled) return result
386
- // A failed turn proves nothing about whether its notes were saved. Cancel
387
- // the request instead of compacting now or springing it on a later turn.
388
- if (e.reason !== "answer" && state.manualPending) cancelManualReset($, state, e.reason)
475
+ // A failed turn proves nothing about whether its notes were saved.
476
+ if (cancelled) log($, `Brain emptying cancelled · turn ended ${e.reason}; ask /fresh-window again`)
389
477
  if (!await refreshIdentity($, state)) return result
390
- if (e.reason === "answer" && state.manualPending) await reset($, state)
478
+ if (e.reason === "answer" && state.flow.request) resetSignal.wake?.({ kind: "reset", generation: state.generation })
391
479
  return result
392
480
  })
393
481
  on("command.run", async ($, e, next) => {
394
482
  if (state.disabled) return next(e)
395
- // Only our queued native command admits manual compaction. A user's /compact
396
- // still reaches the veto, even while a reset is pending.
397
- if (e.command === "compact" && state.resetting && state.headless && e.origin.kind === "plugin" && e.origin.name === "notesoup") {
398
- state.manualCompacting = true
399
- try { return await next(e) } finally { state.manualCompacting = false }
400
- }
401
483
  if (e.command !== "empty" && e.command !== "fresh-window") return next(e)
402
484
  if (!await refreshIdentity($, state)) return { text: "🥣 Different brain now · try /fresh-window again" }
403
485
  if (state.compactDisabled) return { text: `🥣 ${COMPACT_DISABLED}` }
404
- if (state.resetting || state.manualPending) return { text: "🥣 Brain already being emptied" }
405
- if (state.turnRunning) {
406
- state.manualPending = true
407
- return { text: "🥣 Dumping Brain" }
408
- }
409
- // command.run holds a turn even when idle. Start one hidden close-out
410
- // turn after it returns; turn.complete is the verified self-hook path.
411
- state.manualPending = true
412
- manualSignal.wake?.()
486
+ const first = state.flow.requestReset()
487
+ if (state.commit || !first) return { text: "🥣 Brain already being emptied" }
488
+ // command.run holds a turn even when idle; close out from the non-held waiter.
489
+ if (!state.flow.running) resetSignal.wake?.({ kind: "closeout", generation: state.generation })
413
490
  return { text: "🥣 Dumping Brain" }
414
491
  })
415
492
  on("session.compact", async ($, e, next) => {
416
493
  // Disabled means fully transparent: native compaction runs exactly as if the mod were absent.
417
494
  if (state.disabled) return next(e)
418
495
  if (e.agentId !== undefined) return next(e)
419
- const identity = await refreshIdentity($, state)
420
496
  const generation = state.generation
497
+ const identity = await refreshIdentity($, state)
421
498
  // Every pass-through keeps the current boot unless the engine's own summary replaced it.
422
499
  const passThrough = async () => {
423
500
  const result = await next(e)
424
501
  // Precompute installs nothing; a veto or subagent compact cannot remove our boot.
425
502
  if (generation === state.generation && e.trigger !== "precompute" && result.skip === undefined) {
426
503
  state.retainedBoot = result.messages.some((message) => message.text === state.retainedBoot) ? state.retainedBoot : undefined
427
- state.preparedBoot = undefined
504
+ if (state.commit) state.commit.boot = undefined
428
505
  }
429
506
  return result
430
507
  }
431
508
  // Native compaction never runs the summarizer while notesoup is on: user
432
509
  // manual and precompute are vetoed; auto becomes the notes-only reset.
433
- const own = state.resetting && identity !== undefined && (e.trigger === "plugin" || (e.trigger === "manual" && state.manualCompacting === true))
510
+ const own = state.commit !== undefined && identity !== undefined && e.trigger === "manual" && e.instructions === state.commit.instructions
434
511
  if (e.trigger === "manual" && !own) return { skip: "No compacting brains here · use /fresh-window" }
435
512
  if (e.trigger === "precompute") return { skip: "No precomputing brains here" }
436
513
  if (!own && e.trigger !== "auto") return passThrough()
@@ -442,16 +519,8 @@ export function register(on: On) {
442
519
  log($, `Notes didn't load (${built.skip}) · Claude compacted natively`)
443
520
  return passThrough()
444
521
  }
445
- if (own) {
446
- state.preparedBoot = built.boot
447
- } else {
448
- // The auto hijack keeps the books a successful plugin reset does.
449
- state.retainedBoot = built.boot
450
- state.preparedBoot = undefined
451
- state.window++
452
- clearManualRequest(state)
453
- log($, "Brain emptied")
454
- }
522
+ if (state.commit) state.commit.boot = own ? built.boot : undefined
523
+ if (!own) retainReset($, state, built.boot, true)
455
524
  return { messages: built.messages }
456
525
  })
457
526
  // notesoup replaces Claude's summarization and auto-memory guidance; memory can be kept on request.
@@ -495,17 +564,12 @@ async function callNotesTool($: Engine, state: ResetState, e: ToolCallInput): Pr
495
564
  if (agentId !== undefined) return errorResult("only the main agent can empty this brain")
496
565
  if (state.compactDisabled) return errorResult(COMPACT_DISABLED)
497
566
  if (params.last_word !== undefined && typeof params.last_word !== "string") return errorResult("last_word must be a string")
567
+ if (params.terminate !== undefined && typeof params.terminate !== "boolean") return errorResult("terminate must be a boolean")
498
568
  const lastWord = typeof params.last_word === "string" ? params.last_word.trim() || undefined : undefined
499
569
  const length = lastWord ? Array.from(lastWord).length : 0
500
570
  if (length > 500) return errorResult(`last_word is ${length} characters; the sticky note holds 500. Shorten it and call again.`)
501
- if (!state.toolResetRequested) {
502
- state.toolResetRequested = true
503
- state.lastWord = lastWord
504
- state.continuation = undefined
505
- state.continuationWindow = undefined
506
- }
507
- state.manualPending = true
508
- return { result: "Brain will be emptied after this turn. End your turn now; do not call more tools or explain things to the human before the reset." }
571
+ if (state.flow.requestReset({ lastWord, terminate: params.terminate === true })) state.continuation = undefined
572
+ return { result: `Brain reset requested. This tool batch will finish, then the turn stops before its next model request unless it has new user input to handle. Your notes and sticky note survive the reset.${state.flow.request!.resume ? " You will continue in a fresh window after the reset." : " No automatic continuation will be submitted."}` }
509
573
  }
510
574
  if (name.startsWith("history_") && agentId !== undefined) return errorResult("history is unavailable for subagents; main-session history is not their transcript")
511
575
  const result = await run($, { op: "tool", tool: name, params, identity, history: state.history })
@@ -568,88 +632,92 @@ function restoreWindow(state: ResetState, messages: readonly { role: string; tex
568
632
  }
569
633
  }
570
634
 
571
- // The waiter is created in session.start, so its Promise continuation keeps
572
- // that non-held host context. Timers started inside command.run inherit its
573
- // held dispatch even after the command returns. No polling timer is needed.
574
- function armManual($: Engine, state: ResetState, signal: { wake?: () => void }) {
575
- const requested = new Promise<void>((resolve) => { signal.wake = resolve })
576
- void requested.then(() => {
577
- signal.wake = undefined
578
- const generation = state.generation
579
- $.clock.after(0, () => finishManual($, state, signal, generation))
635
+ // Create and re-arm this waiter in session.start's non-held context. Timers
636
+ // created in a held hook inherit that dispatch even after the hook returns.
637
+ function armReset($: Engine, state: ResetState, signal: ResetSignal) {
638
+ let wake!: (work: ResetWork) => void
639
+ const requested = new Promise<ResetWork>((resolve) => { signal.wake = wake = resolve })
640
+ void requested.then((work) => {
641
+ if (signal.wake !== wake) return
642
+ // A close-out submission resolves when its turn starts, so arm the next
643
+ // waiter before submitting: that turn's completion must not lose its wake.
644
+ armReset($, state, signal)
645
+ return runResetWork($, state, work)
580
646
  })
581
647
  }
582
- async function finishManual($: Engine, state: ResetState, signal: { wake?: () => void }, generation: number) {
648
+ async function runResetWork($: Engine, state: ResetState, work: ResetWork) {
649
+ const { generation, kind } = work
650
+ if (generation !== state.generation || !state.flow.ready) return
583
651
  try {
584
- if (generation !== state.generation) return
585
- if (state.manualPending && !state.turnRunning) {
652
+ let text: string
653
+ if (kind === "reset") {
654
+ const turnId = state.flow.turnId
655
+ if (!await reset($, state) || generation !== state.generation || turnId !== state.flow.turnId || state.flow.request?.resume === false) return
656
+ // The retained handoff is already present; this prompt only starts the next turn.
657
+ text = "Continue from your notes in this fresh context window."
658
+ } else {
586
659
  const texts = await loadTexts($, state)
587
660
  if (generation !== state.generation) return
588
661
  if (texts?.warning === undefined) {
589
- clearManualRequest(state)
662
+ state.flow.cancel()
590
663
  log($, "Brain still full: the close-out prompt didn't load")
591
664
  return
592
665
  }
593
- const result = await $.prompt.submit({ text: texts.warning })
594
- if (generation === state.generation && result.drop !== undefined) {
595
- clearManualRequest(state)
596
- log($, "Brain still full: the close-out turn didn't start")
597
- }
666
+ text = texts.warning
598
667
  }
599
- } catch {
600
- if (generation === state.generation) {
601
- clearManualRequest(state)
602
- log($, "Brain still full: the close-out turn didn't start")
603
- }
604
- } finally { armManual($, state, signal) }
668
+ const result = await $.prompt.submit({ text })
669
+ if (result.drop !== undefined) throw result.drop
670
+ } catch (error) {
671
+ if (generation !== state.generation) return
672
+ if (kind === "closeout") state.flow.cancel()
673
+ log($, kind === "closeout" ? "Brain still full: the close-out turn didn't start" : `Brain emptied, but continuation didn't start · ${describeFailure(error)}`)
674
+ }
605
675
  }
606
676
 
607
- /** A non-answer ends the request, never the context; the user can explicitly ask again. */
608
- function cancelManualReset($: Engine, state: ResetState, reason: "aborted" | "refusal" | "error"): void {
609
- clearManualRequest(state)
610
- log($, `Brain emptying cancelled · turn ended ${reason}; ask /fresh-window again`)
677
+ function retainReset($: Engine, state: ResetState, boot: string, auto = false): boolean {
678
+ state.retainedBoot = boot
679
+ state.window++
680
+ const resume = state.flow.consume(auto)
681
+ log($, "Brain emptied")
682
+ return resume
611
683
  }
612
684
 
613
685
  // The sandbox permits $ forwarding only to file-top-level helpers.
614
- async function reset($: Engine, state: ResetState): Promise<void> {
615
- if (!state.identity || state.compactDisabled || state.resetting) return
686
+ async function reset($: Engine, state: ResetState): Promise<boolean> {
687
+ if (!state.identity || state.compactDisabled || state.commit) return false
616
688
  const generation = state.generation
617
- state.resetting = true
618
- state.preparedBoot = undefined
689
+ let resolveCommit!: (kept: boolean) => void
690
+ const committed = new Promise<boolean>((resolve) => { resolveCommit = resolve })
691
+ const commit = state.commit = { instructions: `${RESET_INSTRUCTIONS} ${crypto.randomUUID()}`, boot: undefined as string | undefined, boundary: false, resolve: resolveCommit }
619
692
  try {
620
- let failure: string | undefined
621
- if (state.headless) {
622
- const receipt = await $.command.run({ command: "compact" })
623
- if (generation !== state.generation) return
624
- // A command receipt is not SessionCompacted. Our admitted hook must have
625
- // prepared the boot; session.messages() here still reads the completed
626
- // turn's snapshot, not the next request's newly compacted context.
627
- if (state.preparedBoot === undefined) failure = receipt.text ?? "notes boot was not retained"
628
- } else {
629
- const result = await $.session.compact({ instructions: RESET_INSTRUCTIONS })
630
- failure = result.skip
693
+ // Both modes need the native command; direct compact skips our hook or is unavailable.
694
+ const receipt = await $.command.run({ command: "compact", args: commit.instructions })
695
+ if (generation !== state.generation) return false
696
+ let failure = commit.boot === undefined ? receipt.text ?? "notes boot was not retained" : undefined
697
+ if (failure === undefined) {
698
+ // Interactive command completion exposes the newly installed rows here;
699
+ // headless completion still sees the old request and appends afterwards.
700
+ const messages = await $.session.messages()
701
+ if (generation !== state.generation) return false
702
+ if (messages.some((message) => message.role === "user" && message.text === commit.boot)) commit.resolve(true)
703
+ else if (!state.headless) commit.resolve(false)
704
+ if (!await committed) failure = "notes boot was not committed"
631
705
  }
632
- if (generation !== state.generation) return
633
- if (failure !== undefined || state.preparedBoot === undefined) {
634
- state.manualPending = true
706
+ if (generation !== state.generation) return false
707
+ if (failure !== undefined || commit.boot === undefined) {
635
708
  log($, `Brain not emptied · ${failure ?? "notes boot was not retained"}`)
636
- return
709
+ return false
637
710
  }
638
- state.retainedBoot = state.preparedBoot
639
- state.window++
640
- clearManualRequest(state)
641
- log($, "Brain emptied")
711
+ return retainReset($, state, commit.boot)
642
712
  } catch (error) {
643
- if (generation !== state.generation) return
713
+ if (generation !== state.generation) return false
644
714
  const text = String(error)
645
- state.manualPending = true
646
715
  if (!/a turn is (running|in flight)/.test(text)) {
647
716
  log($, `Brain still full: ${text.replace(/[\r\n].*$/s, "")}`)
648
717
  }
718
+ return false
649
719
  } finally {
650
- if (generation === state.generation) {
651
- state.preparedBoot = undefined
652
- state.resetting = false
653
- }
720
+ commit.resolve(false)
721
+ if (state.commit === commit) state.commit = undefined
654
722
  }
655
723
  }
@@ -27,7 +27,7 @@ Durable notes hold decisions, constraints, and lessons that stay true after the
27
27
  5. **Relocate misfiled notes.** When a standing ruling or the note's own MAP already names its proper notebook, move it there, preserving its metadata, and update both notebooks' maps. Do it, don't propose it. Propose only when the destination notebook itself is unclear.
28
28
  6. **Preserve meaning and provenance.** Keep facts, conditions, exceptions, uncertainty, authorship, and sources. When promoting a finding, cite its source. Do not relabel agent-authored material as human-authored. If its destination or authority is unclear, propose the promotion instead.
29
29
  7. **Keep notes manageable.** Aim below about 200 lines / 8KB per note. Split oversized notes by topic with one-line cross-links.
30
- 8. **Keep wake-up pages useful.** Each writable notebook's `CHEATSHEET.md` holds standing reminders, kept to five lines. Its `MAP.md` holds only the note index: durable notes' addresses and short gists. Both default to pinned and load every window when live unless explicitly unpinned; do not create empty pages. Each notebook allows five live pins. Every page defaults to a 2048-code-point advisory budget, adjustable per note; overflow warns without truncating a pinned body. Preserve standing rules, add promoted notes to the map, and drop entries that no longer hold. Maps follow the same size budget.
30
+ 8. **Keep wake-up pages useful.** Each writable notebook's `CHEATSHEET.md` holds standing reminders, kept to five lines. Its `MAP.md` holds only the note index: durable notes' addresses and short gists. Both default to pinned and load every window when live unless explicitly unpinned; do not create empty pages. Each notebook allows five live pins. Ordinary pages default to a 4096-code-point advisory budget (2048 for root `CHEATSHEET.md` and `MAP.md`), adjustable per note; overflow warns without truncating a pinned body. Preserve standing rules, add promoted notes to the map, and drop entries that no longer hold.
31
31
 
32
32
  ## Deleting
33
33
 
@@ -5,7 +5,7 @@ description: Review and consolidate durable notes using notesoup's shared dream
5
5
 
6
6
  # Dream
7
7
 
8
- Read `../../playbook.md` completely, resolving the path from this skill's directory. It is the shared guide to reviewing and organizing notes. Standing reminders belong in a separate `CHEATSHEET.md` (five lines); `MAP.md` holds only the note index. Both default to pinned and load every window when live unless explicitly unpinned. Every note defaults to a 2048-code-point advisory budget, adjustable per note; pinned bodies load whole with overflow warnings. Respect soft readonly locks; explicitly unlock with `readonly:false` before changing a locked note.
8
+ Read `../../playbook.md` completely, resolving the path from this skill's directory. It is the shared guide to reviewing and organizing notes. Standing reminders belong in a separate `CHEATSHEET.md` (five lines); `MAP.md` holds only the note index. Both default to pinned and load every window when live unless explicitly unpinned. Ordinary notes default to a 4096-code-point advisory budget (2048 for root `CHEATSHEET.md` and `MAP.md`), adjustable per note; pinned bodies load whole with overflow warnings. Respect soft readonly locks; explicitly unlock with `readonly:false` before changing a locked note.
9
9
 
10
10
  Dream in this agent's current session. Do not start another agent or model unless the human asks.
11
11
 
@@ -32,7 +32,7 @@ Any other `@` prefix is refused. A path is relative and `/`-separated, with no e
32
32
 
33
33
  `@` addresses are not file paths: never pass them to file tools like `read`, `write`, `edit`, or `bash`. That creates a stray directory instead of a note.
34
34
 
35
- `CHEATSHEET.md` and `MAP.md` at each notebook's root are separate default-pinned pages you wake up with; absent or crumpled pages are skipped. Set `pinned`, `budget`, and `readonly` through `notes_write`/`notes_update` or frontmatter. Explicit `pinned:false` unpins even a default page. Each notebook allows five live pins; every page defaults to a 2048-code-point advisory budget, adjustable per note. Overflow warns but saves, and pinned bodies load whole. `readonly:true` is a soft lock, not security; explicitly set `readonly:false` to unlock, alone or alongside your changes. Keep standing reminders in `CHEATSHEET.md`, to five lines. `MAP.md` holds only the note index: each durable note's address and gist, for lookup. Update it whenever you add, move or crumple a durable note. Do not create empty pages.
35
+ `CHEATSHEET.md` and `MAP.md` at each notebook's root are separate default-pinned pages you wake up with; absent or crumpled pages are skipped. Set `pinned`, `budget`, and `readonly` through `notes_write`/`notes_update` or frontmatter. Explicit `pinned:false` unpins even a default page. Each notebook allows five live pins; ordinary pages default to a 4096-code-point advisory budget (2048 for root `CHEATSHEET.md` and `MAP.md`), adjustable per note. Overflow warns but saves, and pinned bodies load whole. `readonly:true` is a soft lock, not security; explicitly set `readonly:false` to unlock, alone or alongside your changes. Keep standing reminders in `CHEATSHEET.md`, to five lines. `MAP.md` holds only the note index: each durable note's address and gist, for lookup. Update it whenever you add, move or crumple a durable note. Do not create empty pages.
36
36
 
37
37
  Keep notes focused on what is true now; if a piece of past context still matters (such as why an approach was ruled out), keep only a brief summary rather than a blow-by-blow log. Crumple notes that are no longer true; a stale note is worse than none.
38
38
 
@@ -25140,7 +25140,7 @@ function addressFor(identity, scope, path, who) {
25140
25140
  }
25141
25141
 
25142
25142
  // src/notes/policy.ts
25143
- var DEFAULT_NOTE_BUDGET = 2048;
25143
+ var DEFAULT_NOTE_BUDGET = 4096;
25144
25144
  var MAX_PINNED_NOTES = 5;
25145
25145
  var DEFAULT_PINNED_PAGES = ["CHEATSHEET.md", "MAP.md"];
25146
25146
  function validateNotePolicy(fields) {
@@ -25153,9 +25153,10 @@ function validateNotePolicy(fields) {
25153
25153
  }
25154
25154
  function effectiveNotePolicy(fields, path) {
25155
25155
  validateNotePolicy(fields);
25156
+ const defaultPage = DEFAULT_PINNED_PAGES.some((page) => page === path);
25156
25157
  return {
25157
- pinned: fields.pinned ?? DEFAULT_PINNED_PAGES.some((page) => page === path),
25158
- budget: fields.budget ?? DEFAULT_NOTE_BUDGET,
25158
+ pinned: fields.pinned ?? defaultPage,
25159
+ budget: fields.budget ?? (defaultPage ? 2048 : DEFAULT_NOTE_BUDGET),
25159
25160
  readonly: fields.readonly ?? false
25160
25161
  };
25161
25162
  }
@@ -26141,7 +26142,7 @@ var ORIGIN = typebox_exports.Optional(typebox_exports.Union([...ORIGIN_VALUES],
26141
26142
  }));
26142
26143
  var POLICY_PARAMETERS = {
26143
26144
  pinned: typebox_exports.Optional(typebox_exports.Boolean({ description: "Inject the full body at boot. At most 5 live pins per notebook; root CHEATSHEET.md/MAP.md default true, all others false. Explicit false overrides the default." })),
26144
- budget: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "Body budget in Unicode code points (default 2048 for every note). Over budget warns but saves; boot does not truncate." })),
26145
+ budget: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "Body budget in Unicode code points (default 4096; root CHEATSHEET.md and MAP.md default 2048). Over budget warns but saves; boot does not truncate." })),
26145
26146
  readonly: typebox_exports.Optional(typebox_exports.Boolean({ description: "Soft lock, not a security boundary. true locks changes; explicitly pass false to unlock, including in the same call as edits or overwrite." }))
26146
26147
  };
26147
26148
  var PolicySchema = {
@@ -28284,10 +28285,11 @@ Pinned pages get jammed straight into your brain the moment you wake up. Whoever
28284
28285
  reads them, and next is you. So keep them short, and keep them true.
28285
28286
 
28286
28287
  Set \`pinned\`, \`budget\`, and \`readonly\` with the note tools or frontmatter. Each notebook allows five
28287
- live pins, including the defaults; \`pinned:false\` unpins even a default page. Every page's budget
28288
- starts at 2048 Unicode code points; set a positive integer to change it. Going over warns but saves,
28289
- and pinned bodies arrive whole, not cut short. \`readonly:true\` is a soft lock, not security;
28290
- explicitly set \`readonly:false\` to unlock, on its own or with your changes.
28288
+ live pins, including the defaults; \`pinned:false\` unpins even a default page. Budgets start at 4096
28289
+ Unicode code points, or 2048 for root \`CHEATSHEET.md\` and \`MAP.md\`; set a positive integer to
28290
+ change one. Going over warns but saves, and pinned bodies arrive whole, not cut short.
28291
+ \`readonly:true\` is a soft lock, not security; explicitly set \`readonly:false\` to unlock,
28292
+ on its own or with your changes.
28291
28293
 
28292
28294
  - **\`CHEATSHEET.md\`** holds what you'll want next time \u2014 a rule, a warning, a grudge, a name,
28293
28295
  a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
@@ -5,7 +5,7 @@ description: Review and consolidate durable notes using notesoup's shared dream
5
5
 
6
6
  # Dream
7
7
 
8
- Read `../../playbook.md` completely, resolving the path from this skill's directory. It is the shared guide to reviewing and organizing notes. Standing reminders belong in a separate `CHEATSHEET.md` (five lines); `MAP.md` holds only the note index. Both default to pinned and load every window when live unless explicitly unpinned. Every note defaults to a 2048-code-point advisory budget, adjustable per note; pinned bodies load whole with overflow warnings. Respect soft readonly locks; explicitly unlock with `readonly:false` before changing a locked note.
8
+ Read `../../playbook.md` completely, resolving the path from this skill's directory. It is the shared guide to reviewing and organizing notes. Standing reminders belong in a separate `CHEATSHEET.md` (five lines); `MAP.md` holds only the note index. Both default to pinned and load every window when live unless explicitly unpinned. Ordinary notes default to a 4096-code-point advisory budget (2048 for root `CHEATSHEET.md` and `MAP.md`), adjustable per note; pinned bodies load whole with overflow warnings. Respect soft readonly locks; explicitly unlock with `readonly:false` before changing a locked note.
9
9
 
10
10
  Dream in this agent's current session. Do not start another agent or model unless the human asks.
11
11
 
@@ -32,7 +32,7 @@ Any other `@` prefix is refused. A path is relative and `/`-separated, with no e
32
32
 
33
33
  `@` addresses are not file paths: never pass them to file tools like `read`, `write`, `edit`, or `bash`. That creates a stray directory instead of a note.
34
34
 
35
- `CHEATSHEET.md` and `MAP.md` at each notebook's root are separate default-pinned pages you wake up with; absent or crumpled pages are skipped. Set `pinned`, `budget`, and `readonly` through `notes_write`/`notes_update` or frontmatter. Explicit `pinned:false` unpins even a default page. Each notebook allows five live pins; every page defaults to a 2048-code-point advisory budget, adjustable per note. Overflow warns but saves, and pinned bodies load whole. `readonly:true` is a soft lock, not security; explicitly set `readonly:false` to unlock, alone or alongside your changes. Keep standing reminders in `CHEATSHEET.md`, to five lines. `MAP.md` holds only the note index: each durable note's address and gist, for lookup. Update it whenever you add, move or crumple a durable note. Do not create empty pages.
35
+ `CHEATSHEET.md` and `MAP.md` at each notebook's root are separate default-pinned pages you wake up with; absent or crumpled pages are skipped. Set `pinned`, `budget`, and `readonly` through `notes_write`/`notes_update` or frontmatter. Explicit `pinned:false` unpins even a default page. Each notebook allows five live pins; ordinary pages default to a 4096-code-point advisory budget (2048 for root `CHEATSHEET.md` and `MAP.md`), adjustable per note. Overflow warns but saves, and pinned bodies load whole. `readonly:true` is a soft lock, not security; explicitly set `readonly:false` to unlock, alone or alongside your changes. Keep standing reminders in `CHEATSHEET.md`, to five lines. `MAP.md` holds only the note index: each durable note's address and gist, for lookup. Update it whenever you add, move or crumple a durable note. Do not create empty pages.
36
36
 
37
37
  Keep notes focused on what is true now; if a piece of past context still matters (such as why an approach was ruled out), keep only a brief summary rather than a blow-by-blow log. Crumple notes that are no longer true; a stale note is worse than none.
38
38