notesoup 0.41.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/dist/src/boot/render.js +11 -20
  2. package/dist/src/boot/snapshot.js +1 -6
  3. package/dist/src/boot/text.d.ts +12 -0
  4. package/dist/src/boot/text.js +15 -3
  5. package/dist/src/budget/parse.d.ts +14 -0
  6. package/dist/src/budget/parse.js +36 -0
  7. package/dist/src/budget/policy.js +2 -7
  8. package/dist/src/budget/text.d.ts +14 -0
  9. package/dist/src/budget/text.js +14 -0
  10. package/dist/src/claude/helper.js +24 -4
  11. package/dist/src/claude/thresholds.d.ts +39 -0
  12. package/dist/src/claude/thresholds.js +128 -0
  13. package/dist/src/dream/doctor.js +1 -1
  14. package/dist/src/dream/jail.js +10 -10
  15. package/dist/src/dream/lock.js +6 -13
  16. package/dist/src/dream/report.js +5 -15
  17. package/dist/src/history/history.js +5 -3
  18. package/dist/src/history/query.js +14 -26
  19. package/dist/src/notes/address.d.ts +1 -2
  20. package/dist/src/notes/address.js +14 -26
  21. package/dist/src/notes/errors.d.ts +2 -0
  22. package/dist/src/notes/errors.js +5 -0
  23. package/dist/src/notes/frontmatter.js +16 -2
  24. package/dist/src/notes/identity.js +0 -3
  25. package/dist/src/notes/paths.d.ts +11 -1
  26. package/dist/src/notes/paths.js +28 -7
  27. package/dist/src/notes/store.d.ts +1 -0
  28. package/dist/src/notes/store.js +54 -49
  29. package/dist/src/pi/boot.js +1 -5
  30. package/dist/src/pi/budget.d.ts +3 -3
  31. package/dist/src/pi/budget.js +11 -11
  32. package/dist/src/pi/dream/cli.js +43 -11
  33. package/dist/src/pi/estimate.d.ts +1 -5
  34. package/dist/src/pi/estimate.js +4 -4
  35. package/dist/src/pi/history.js +1 -4
  36. package/dist/src/pi/notes/adapter.d.ts +1 -1
  37. package/dist/src/pi/notes/adapter.js +2 -2
  38. package/dist/src/pi/reset/artifacts.d.ts +0 -2
  39. package/dist/src/pi/reset/artifacts.js +4 -4
  40. package/dist/src/pi/reset/committed.js +2 -2
  41. package/dist/src/pi/runtime.js +9 -6
  42. package/dist/src/pi/thresholds.js +5 -9
  43. package/dist/src/pi/tool-result.d.ts +1 -4
  44. package/dist/src/pi/tool-result.js +3 -3
  45. package/dist/src/pi/window.d.ts +5 -0
  46. package/dist/src/pi/window.js +7 -0
  47. package/dist/src/settings.d.ts +10 -0
  48. package/dist/src/settings.js +10 -4
  49. package/dist/src/tools/history.js +15 -18
  50. package/dist/src/tools/notes.d.ts +3 -7
  51. package/dist/src/tools/notes.js +18 -27
  52. package/dist/src/tools/output.d.ts +2 -3
  53. package/dist/src/tools/output.js +3 -9
  54. package/dist/src/tools/result.d.ts +1 -0
  55. package/dist/src/tools/result.js +15 -21
  56. package/dist/src/tools/schema.d.ts +0 -1
  57. package/dist/src/tools/schema.js +3 -4
  58. package/dist/test/agent-loop.test.js +1 -2
  59. package/dist/test/boot.integration.test.js +1 -1
  60. package/dist/test/claude-mod.test.js +425 -23
  61. package/dist/test/claude-validation.test.d.ts +1 -0
  62. package/dist/test/claude-validation.test.js +73 -0
  63. package/dist/test/dream-skill.test.js +2 -4
  64. package/dist/test/dream.test.js +17 -3
  65. package/dist/test/helpers/extension.js +1 -1
  66. package/dist/test/history.integration.test.js +9 -9
  67. package/dist/test/host-neutral.test.js +16 -1
  68. package/dist/test/notes-library.test.js +31 -2
  69. package/dist/test/notes.integration.test.js +11 -11
  70. package/dist/test/notes.test.js +40 -21
  71. package/dist/test/reset-lifecycle.test.js +1 -1
  72. package/docs/claude-code-mod.md +13 -3
  73. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  74. package/mods/notesoup/dist/claude/helper.js +285 -152
  75. package/mods/notesoup/hooks/register.ts +308 -51
  76. package/mods/notesoup/playbook.md +1 -1
  77. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  78. package/mods/notesoup/skills/memory/SKILL.md +61 -0
  79. package/mods/pi-context/dist/claude/helper.js +9324 -0
  80. package/package.json +5 -3
  81. package/playbook.md +1 -1
  82. package/skills/dream/SKILL.md +1 -1
  83. package/skills/memory/SKILL.md +1 -1
  84. package/src/boot/render.ts +11 -21
  85. package/src/boot/snapshot.ts +2 -7
  86. package/src/boot/text.ts +21 -3
  87. package/src/budget/parse.ts +39 -0
  88. package/src/budget/policy.ts +2 -6
  89. package/src/budget/text.ts +20 -0
  90. package/src/claude/helper.ts +22 -5
  91. package/src/claude/thresholds.ts +153 -0
  92. package/src/dream/doctor.ts +1 -1
  93. package/src/dream/jail.ts +10 -10
  94. package/src/dream/lock.ts +3 -9
  95. package/src/dream/report.ts +5 -10
  96. package/src/history/history.ts +5 -3
  97. package/src/history/query.ts +14 -27
  98. package/src/notes/address.ts +13 -25
  99. package/src/notes/errors.ts +6 -0
  100. package/src/notes/frontmatter.ts +12 -2
  101. package/src/notes/identity.ts +0 -2
  102. package/src/notes/paths.ts +23 -5
  103. package/src/notes/store.ts +50 -48
  104. package/src/pi/boot.ts +1 -13
  105. package/src/pi/budget.ts +10 -11
  106. package/src/pi/dream/cli.ts +35 -10
  107. package/src/pi/estimate.ts +4 -4
  108. package/src/pi/history.ts +1 -5
  109. package/src/pi/notes/adapter.ts +2 -2
  110. package/src/pi/reset/artifacts.ts +4 -4
  111. package/src/pi/reset/committed.ts +2 -2
  112. package/src/pi/runtime.ts +8 -7
  113. package/src/pi/thresholds.ts +5 -11
  114. package/src/pi/tool-result.ts +3 -3
  115. package/src/pi/window.ts +8 -0
  116. package/src/settings.ts +22 -5
  117. package/src/tools/history.ts +15 -19
  118. package/src/tools/notes.ts +21 -32
  119. package/src/tools/output.ts +3 -12
  120. package/src/tools/result.ts +14 -19
  121. package/src/tools/schema.ts +3 -4
  122. package/dist/src/dream/playbook.d.ts +0 -1
  123. package/dist/src/dream/playbook.js +0 -2
  124. package/dist/src/pi/reset/text.d.ts +0 -5
  125. package/dist/src/pi/reset/text.js +0 -6
  126. package/src/dream/playbook.ts +0 -3
  127. package/src/pi/reset/text.ts +0 -10
@@ -2,19 +2,33 @@ import type { EngineInterface, On, ProcessRunResult, ToolCallResult, ToolSpec }
2
2
 
3
3
  const PREFIX = "mcp__notesoup__"
4
4
  const TOOL_NAMES = ["notes_write", "notes_update", "notes_read", "notes_list", "notes_search"] as const
5
- // @ts-expect-error Claude's hook sandbox supplies import.meta.dir; Node's typings do not.
6
5
  const HELPER = `${import.meta.dir}/../dist/claude/helper.js`
7
6
  const TIMEOUT_MS = 10_000
8
7
  const OUTPUT_LIMIT = 1024 * 1024
9
8
 
10
9
  type Identity = { home: string; sessionId: string; cwd: string; agent: string; model: string }
11
10
  type SchemaRow = { name: string; description: string; inputSchema: Record<string, unknown> }
12
- type Engine = Pick<EngineInterface, "process" | "session" | "ui" | "clock" | "prompt">
11
+ type Engine = Pick<EngineInterface, "process" | "session" | "ui" | "clock" | "prompt" | "env" | "settings">
12
+ /** The measured context, as much of it as the engine reported. */
13
+ type ContextUsage = { tokens?: number; window?: number; percent?: number }
14
+ /** Shared reset prose, fetched once per session so Pi and Claude cannot drift apart. */
15
+ type SharedTexts = { warning?: string; continuation?: string; wipeSentence?: string }
16
+ type ClaudeLimits = {
17
+ source: string; autoCompact: boolean; unit: "tokens" | "percent"
18
+ native: number; reset: number; warn: number; resetMargin: number; warningRunway: number
19
+ }
13
20
  type ResetState = {
14
- identity?: Identity; window: number; turnRunning: boolean; resetting: boolean
21
+ identity?: Identity; generation: number; window: number; turnRunning: boolean; resetting: boolean
15
22
  manualPending: boolean; headless: boolean; usageFailureLogged: boolean; preparedBoot?: string; retainedBoot?: string
23
+ compactDisabled: boolean; limitsFailureLogged: boolean; limitsAttempts: number; limitsWindow: number
24
+ limits?: ClaudeLimits; warnedWindow?: number; texts?: SharedTexts; settingsFailureLogged: boolean
16
25
  }
17
26
  const HEADLESS = "Clear-memory is off in headless (-p / SDK) sessions"
27
+ const COMPACT_DISABLED = "Clear-memory can't run: compaction is off in this session (DISABLE_COMPACT)"
28
+ const THRESHOLDS_UNAVAILABLE = "Context thresholds unavailable · automatic clear-memory skipped"
29
+ const SETTINGS_UNAVAILABLE = "Notesoup settings unreadable · using the default clear-memory margins"
30
+ /** Bounded retries: a transient helper failure must not disable thresholds for a whole window. */
31
+ const MAX_LIMITS_ATTEMPTS = 3
18
32
  const RESET_INSTRUCTIONS = "notesoup: reset to a fresh notes-only context window."
19
33
  const BOOT_TOOLS = {
20
34
  notes: `${PREFIX}notes_*`, notesList: `${PREFIX}notes_list`,
@@ -22,8 +36,142 @@ const BOOT_TOOLS = {
22
36
  remaining: "get_context_remaining (unavailable in Claude)", wipe: "/clear-memory (user command; no model reset tool in Claude)",
23
37
  }
24
38
 
25
- async function buildBoot($: Engine, identity: Identity, window: number) {
26
- return run($, { op: "boot", identity, window, tools: BOOT_TOOLS }, identity.cwd)
39
+ /** The boot names the host's own wipe path, so the protocol block speaks about `/clear-memory`. */
40
+ async function buildBoot($: Engine, identity: Identity, window: number, texts?: SharedTexts) {
41
+ const tools = texts?.wipeSentence === undefined ? BOOT_TOOLS : { ...BOOT_TOOLS, wipeSentence: texts.wipeSentence }
42
+ return run($, { op: "boot", identity, window, tools }, identity.cwd)
43
+ }
44
+ function numberOf(value: unknown): number | undefined {
45
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined
46
+ }
47
+ function sharedTextsOf(value: unknown): SharedTexts | undefined {
48
+ if (typeof value !== "object" || value === null) return undefined
49
+ const row = value as Record<string, unknown>
50
+ const texts: SharedTexts = {}
51
+ if (typeof row.warning === "string" && row.warning.length > 0) texts.warning = row.warning
52
+ if (typeof row.continuation === "string" && row.continuation.length > 0) texts.continuation = row.continuation
53
+ if (typeof row.wipeSentence === "string" && row.wipeSentence.length > 0) texts.wipeSentence = row.wipeSentence
54
+ return Object.keys(texts).length > 0 ? texts : undefined
55
+ }
56
+ /** The helper's resolved points, accepted only when every number is a real number. */
57
+ function limitsShape(value: unknown): ClaudeLimits | undefined {
58
+ if (typeof value !== "object" || value === null) return undefined
59
+ const row = value as Record<string, unknown>
60
+ const unit = row.unit === "tokens" || row.unit === "percent" ? row.unit : undefined
61
+ const native = numberOf(row.native), reset = numberOf(row.reset), warn = numberOf(row.warn)
62
+ const resetMargin = numberOf(row.resetMargin), warningRunway = numberOf(row.warningRunway)
63
+ if (unit === undefined || native === undefined || reset === undefined || warn === undefined || resetMargin === undefined || warningRunway === undefined) return undefined
64
+ return { source: typeof row.source === "string" ? row.source : "unknown", autoCompact: row.autoCompact !== false, unit, native, reset, warn, resetMargin, warningRunway }
65
+ }
66
+ /** Each environment read names its capability literally for Claude's loader scanner. */
67
+ async function envPctOverride($: Engine) {
68
+ try { return await $.env.get("CLAUDE_AUTOCOMPACT_PCT_OVERRIDE") } catch { return undefined }
69
+ }
70
+ async function envAutoCompactWindow($: Engine) {
71
+ try { return await $.env.get("CLAUDE_CODE_AUTO_COMPACT_WINDOW") } catch { return undefined }
72
+ }
73
+ async function envDisableAutoCompact($: Engine) {
74
+ try { return await $.env.get("DISABLE_AUTO_COMPACT") } catch { return undefined }
75
+ }
76
+ /** Presence-style environment flags: any value but an explicit no counts as on. */
77
+ async function compactDisabled($: Engine): Promise<boolean> {
78
+ let value: string | undefined
79
+ try { value = await $.env.get("DISABLE_COMPACT") } catch { return false }
80
+ if (value === undefined) return false
81
+ const text = value.trim().toLowerCase()
82
+ // The same presence convention as the helper's flag parsing: "off"/"no" mean not disabled.
83
+ return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off"
84
+ }
85
+ async function readSettings($: Engine, state: ResetState): Promise<unknown> {
86
+ try { return await $.settings.read() } catch {
87
+ // A silent fallback would hide a broken settings read behind default margins.
88
+ if (!state.settingsFailureLogged) {
89
+ state.settingsFailureLogged = true
90
+ log($, SETTINGS_UNAVAILABLE)
91
+ }
92
+ return undefined
93
+ }
94
+ }
95
+ /** The measured context, or undefined when the engine cannot report it. The failure logs once. */
96
+ async function contextUsage($: Engine, state: ResetState): Promise<ContextUsage | undefined> {
97
+ try {
98
+ const context = (await $.session.usage()).context
99
+ if (typeof context !== "object" || context === null) return {}
100
+ const row = context as Record<string, unknown>
101
+ return { tokens: numberOf(row.tokens), window: numberOf(row.window), percent: numberOf(row.percent) }
102
+ } catch {
103
+ if (!state.usageFailureLogged) {
104
+ state.usageFailureLogged = true
105
+ log($, "Context usage unavailable · automatic clear-memory skipped")
106
+ }
107
+ return undefined
108
+ }
109
+ }
110
+ async function breakdownContext($: Engine): Promise<Record<string, unknown> | undefined> {
111
+ try {
112
+ const context = (await $.session.usage({ breakdown: "summary" })).context
113
+ return typeof context === "object" && context !== null ? context as Record<string, unknown> : undefined
114
+ } catch { return undefined }
115
+ }
116
+ /** Everything the resolver may read: measured usage plus the raw settings and environment. */
117
+ async function limitFacts($: Engine, state: ResetState, usage: ContextUsage): Promise<Record<string, unknown>> {
118
+ return {
119
+ usage,
120
+ breakdown: await breakdownContext($),
121
+ settings: await readSettings($, state),
122
+ env: {
123
+ pctOverride: await envPctOverride($),
124
+ autoCompactWindow: await envAutoCompactWindow($),
125
+ disableAutoCompact: await envDisableAutoCompact($),
126
+ },
127
+ }
128
+ }
129
+ /**
130
+ * The points the current window is measured against, resolved by the helper's shared
131
+ * derivation. One resolved result per reported window value: an unknown window resolves the
132
+ * percent fallback, and a later real window re-resolves against it. A failed round trip is
133
+ * retried a bounded number of times instead of disabling thresholds for the whole window.
134
+ */
135
+ async function limitsOf($: Engine, state: ResetState, usage: ContextUsage): Promise<ClaudeLimits | undefined> {
136
+ const window = usage.window !== undefined && usage.window > 0 ? usage.window : 0
137
+ const sameWindow = state.limitsWindow === window
138
+ if (sameWindow && state.limits !== undefined) return state.limits
139
+ if (sameWindow && state.limitsAttempts >= MAX_LIMITS_ATTEMPTS) return undefined
140
+ const generation = state.generation
141
+ const facts = await limitFacts($, state, usage)
142
+ if (generation !== state.generation) return undefined
143
+ const response = await run($, { op: "limits", facts }, state.identity?.cwd ?? ".")
144
+ if (generation !== state.generation) return undefined
145
+ const limits = response.ok ? limitsShape(response.result) : undefined
146
+ state.limitsWindow = window
147
+ if (limits) {
148
+ state.limits = limits
149
+ state.limitsAttempts = 0
150
+ return limits
151
+ }
152
+ state.limitsAttempts = sameWindow ? state.limitsAttempts + 1 : 1
153
+ if (!state.limitsFailureLogged) {
154
+ state.limitsFailureLogged = true
155
+ log($, THRESHOLDS_UNAVAILABLE)
156
+ }
157
+ return undefined
158
+ }
159
+ /** The measured value the points are expressed in; tokens win, percent × window stands in. */
160
+ function measuredValue(limits: ClaudeLimits, usage: ContextUsage): number | undefined {
161
+ if (limits.unit === "percent") return usage.percent
162
+ if (usage.tokens !== undefined) return usage.tokens
163
+ return usage.percent !== undefined && usage.window !== undefined && usage.window > 0 ? (usage.percent / 100) * usage.window : undefined
164
+ }
165
+ /** The shared reset prose: one helper round trip per session, retried until it lands. */
166
+ async function loadTexts($: Engine, state: ResetState): Promise<SharedTexts | undefined> {
167
+ if (state.texts) return state.texts
168
+ if (!state.identity) return undefined
169
+ const generation = state.generation
170
+ const response = await run($, { op: "texts" }, state.identity.cwd)
171
+ if (generation !== state.generation) return undefined
172
+ const texts = response.ok ? sharedTextsOf(response.result) : undefined
173
+ if (texts) state.texts = texts
174
+ return texts
27
175
  }
28
176
  function log($: Engine, text: string) {
29
177
  try { $.ui.log(`🥣 ${text}`) } catch { /* UI must not break a turn or reset. */ }
@@ -52,28 +200,63 @@ async function run($: { process: { run: (argv: readonly string[], init?: { cwd?:
52
200
  try { return decode(await $.process.run(["node", HELPER], { cwd, stdin: `${JSON.stringify(request)}\n`, timeoutMs: TIMEOUT_MS })) }
53
201
  catch { return { ok: false as const, error: "helper execution failed" } }
54
202
  }
55
- function identityOf(e: { cwd: string }, sessionId: string, home: string, model: string): Identity {
56
- return { home, sessionId, cwd: e.cwd, agent: "claude", model: model.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "claude" }
203
+ /** Session start does not fire on /clear, /resume or /branch. Forget the old window on end. */
204
+ function forgetSession(state: ResetState) {
205
+ state.generation++
206
+ state.identity = undefined
207
+ state.window = 0
208
+ state.turnRunning = state.resetting = state.manualPending = state.usageFailureLogged = false
209
+ state.preparedBoot = state.retainedBoot = undefined
210
+ state.texts = state.limits = undefined
211
+ state.limitsAttempts = state.limitsWindow = 0
212
+ state.settingsFailureLogged = state.limitsFailureLogged = false
213
+ state.warnedWindow = undefined
214
+ }
215
+ async function modelOf($: Engine): Promise<string> {
216
+ // session.model() is the documented main-loop model API. Match the notes library's slug.
217
+ try {
218
+ const model = await $.session.model()
219
+ return model.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "claude"
220
+ } catch { return "claude" }
221
+ }
222
+ /** Re-key lazily even if a host switches sessions without another session.start. */
223
+ async function refreshIdentity($: Engine, state: ResetState): Promise<Identity | undefined> {
224
+ const generation = state.generation
225
+ const sessionId = await $.session.id()
226
+ const cwd = await $.session.cwd()
227
+ const model = await modelOf($)
228
+ if (generation !== state.generation) return undefined
229
+ if (state.identity?.sessionId === sessionId) {
230
+ state.identity = { ...state.identity, cwd, model }
231
+ return state.identity
232
+ }
233
+ const home = await $.env.get("PI_NOTES_HOME") ?? `${await $.env.get("HOME") ?? await $.env.get("USERPROFILE") ?? ""}/.agents/notes`
234
+ if (generation !== state.generation) return undefined
235
+ forgetSession(state)
236
+ state.identity = { home, sessionId, cwd, agent: "claude", model }
237
+ const freshGeneration = state.generation
238
+ // History is not inference context; recover a retained boot only for this session id.
239
+ try {
240
+ const messages = await $.session.messages()
241
+ if (freshGeneration === state.generation) restoreWindow(state, messages)
242
+ } catch { /* A fresh session starts at zero. */ }
243
+ return freshGeneration === state.generation ? state.identity : undefined
57
244
  }
58
245
 
59
246
  export function register(on: On) {
60
- let identity: Identity | undefined
61
247
  const manualSignal: { wake?: () => void } = {}
62
- const state: ResetState = { window: 0, turnRunning: false, resetting: false, manualPending: false, headless: false, usageFailureLogged: false }
248
+ const state: ResetState = { generation: 0, window: 0, turnRunning: false, resetting: false, manualPending: false, headless: false, usageFailureLogged: false, compactDisabled: false, limitsFailureLogged: false, limitsAttempts: 0, limitsWindow: 0, settingsFailureLogged: false }
63
249
  const registered = new Set<string>()
64
250
  on("session.start", async ($, e, next) => {
65
- const home = await $.env.get("PI_NOTES_HOME") ?? `${await $.env.get("HOME") ?? await $.env.get("USERPROFILE") ?? ""}/.agents/notes`
66
- identity = identityOf(e, await $.session.id(), home, "claude")
67
- state.identity = identity
68
- state.window = 0
69
- state.turnRunning = state.resetting = state.manualPending = state.usageFailureLogged = false
251
+ forgetSession(state)
252
+ await refreshIdentity($, state)
70
253
  state.headless = !e.isInteractive
71
254
  if (state.headless) log($, HEADLESS)
72
- state.preparedBoot = state.retainedBoot = undefined
73
- // The engine's history view includes retained boots on resume/reload.
74
- // Recover their ordinal without treating that view as inference context.
75
- try { restoreWindow(state, await $.session.messages()) } catch { /* A fresh session starts at zero. */ }
255
+ // Compaction is the capability the reset is built on; without it, automatic resets stop here.
256
+ state.compactDisabled = await compactDisabled($)
257
+ if (state.compactDisabled) log($, COMPACT_DISABLED)
76
258
  registered.clear()
259
+ await loadTexts($, state)
77
260
  armManual($, state, manualSignal)
78
261
  await $.command.register({ name: "clear-memory", description: "Reset context to a fresh notes-only window", immediate: true })
79
262
  const schemas = await run($, { op: "schemas" }, e.cwd)
@@ -85,8 +268,14 @@ export function register(on: On) {
85
268
  }
86
269
  return next(e)
87
270
  })
271
+ on("session.end", async ($, e, next) => {
272
+ forgetSession(state)
273
+ return next(e)
274
+ })
88
275
  on("tool.call", async ($, e, next) => {
89
- if (!registered.has(e.tool) || e.agentId !== undefined || !identity) return next(e)
276
+ if (!registered.has(e.tool)) return next(e)
277
+ const identity = await refreshIdentity($, state)
278
+ if (!identity) return errorResult("session changed during identity lookup")
90
279
  const { tool, tool_use_id: _toolUseId, agentId: _agentId, ...params } = e
91
280
  const result = await run($, { op: "tool", tool: tool.slice(PREFIX.length), params, identity }, identity.cwd)
92
281
  if (!result.ok) return errorResult(result.error)
@@ -96,24 +285,31 @@ export function register(on: On) {
96
285
  return outcome.ok ? { result: outcome.text } : { result: outcome.text, isError: true }
97
286
  })
98
287
  on("turn.start", async ($, e, next) => {
288
+ // The documented turn.start is main-loop only. Guard tagged host events too:
289
+ // only a main-agent turn.complete clears this latch.
290
+ if ("agentId" in e && e.agentId !== undefined) return next(e)
291
+ if (!await refreshIdentity($, state)) return next(e)
99
292
  state.turnRunning = true
100
293
  return next(e)
101
294
  })
102
295
  on("turn.complete", async ($, e, next) => {
103
296
  const result = await next(e)
104
297
  if (e.agentId !== undefined) return result
298
+ if (!await refreshIdentity($, state)) return result
105
299
  state.turnRunning = false
106
300
  await maybeReset($, state, true)
107
301
  return result
108
302
  })
109
303
  on("session.measure", async ($, e, next) => {
110
304
  const result = await next(e)
111
- await maybeReset($, state, false)
305
+ if (await refreshIdentity($, state)) await maybeReset($, state, false)
112
306
  return result
113
307
  })
114
308
  on("command.run", async ($, e, next) => {
115
309
  if (e.command !== "clear-memory") return next(e)
310
+ if (!await refreshIdentity($, state)) return { text: "🥣 Session changed · try clear-memory again" }
116
311
  if (state.headless) return { text: `🥣 ${HEADLESS}` }
312
+ if (state.compactDisabled) return { text: `🥣 ${COMPACT_DISABLED}` }
117
313
  if (state.resetting || state.manualPending) return { text: "🥣 Clear-memory already queued" }
118
314
  if (state.turnRunning) {
119
315
  state.manualPending = true
@@ -126,37 +322,81 @@ export function register(on: On) {
126
322
  return { text: "🥣 Clearing memory · notes first, then it stops" }
127
323
  })
128
324
  on("session.compact", async ($, e, next) => {
325
+ if (e.agentId !== undefined) return next(e)
326
+ const identity = await refreshIdentity($, state)
129
327
  // Do not take over native /compact or another plugin's compaction.
130
- if (!state.resetting || e.trigger !== "plugin" || e.agentId !== undefined || !identity) return next(e)
131
- const boot = await buildBoot($, identity, state.window + 1)
328
+ if (!state.resetting || e.trigger !== "plugin" || !identity) {
329
+ const generation = state.generation
330
+ const result = await next(e)
331
+ // Precompute installs nothing; a veto or subagent compact cannot remove our boot.
332
+ if (generation === state.generation && e.trigger !== "precompute" && result.skip === undefined) {
333
+ state.retainedBoot = result.messages.some((message) => message.text === state.retainedBoot) ? state.retainedBoot : undefined
334
+ state.preparedBoot = undefined
335
+ }
336
+ return result
337
+ }
338
+ const generation = state.generation
339
+ const texts = await loadTexts($, state)
340
+ if (texts?.continuation === undefined) return { skip: "reset text didn't load" }
341
+ const boot = await buildBoot($, identity, state.window + 1, texts)
342
+ if (generation !== state.generation) return { skip: "session changed while building the notes boot" }
132
343
  if (!boot.ok) return { skip: `notes didn't load: ${boot.error}` }
133
344
  state.preparedBoot = String(boot.result)
134
- return { messages: [{ role: "user", text: state.preparedBoot, toolUses: [] }] }
345
+ // The same closed reset shape as Pi: notes boot first, then the one reset message.
346
+ return { messages: [
347
+ { role: "user", text: state.preparedBoot, toolUses: [] },
348
+ { role: "user", text: texts.continuation, toolUses: [] },
349
+ ] }
135
350
  })
136
351
  on("prompt.context", async ($, e, next) => {
137
352
  const result = await next(e)
353
+ const identity = await refreshIdentity($, state)
354
+ const generation = state.generation
138
355
  // The reset already retained its boot as the sole conversation message.
139
356
  // Prompt context still recomputes, but must not inject a duplicate snapshot.
140
- if (state.retainedBoot !== undefined) return { ...result, blocks: result.blocks.filter((block) => block.name !== "notesoup:boot") }
141
- if (result.blocks.some((block) => block.name === "notesoup:boot")) return result
142
- if (!identity) return result
143
- const boot = await buildBoot($, identity, state.window)
144
- if (!boot.ok) {
145
- try {
146
- await $.ui.notify("🥣 Notes didn't load")
147
- } catch { /* Notification failure must not suppress the fallback block. */ }
357
+ const retained = state.retainedBoot !== undefined
358
+ let blocks = retained ? result.blocks.filter((block) => block.name !== "notesoup:boot") : [...result.blocks]
359
+ if (!retained && !blocks.some((block) => block.name === "notesoup:boot") && identity) {
360
+ const texts = await loadTexts($, state)
361
+ const boot = await buildBoot($, identity, state.window, texts)
362
+ if (generation !== state.generation) return result
363
+ if (!boot.ok) {
364
+ try {
365
+ await $.ui.toast("🥣 Notes didn't load")
366
+ } catch { /* Notification failure must not suppress the fallback block. */ }
367
+ }
368
+ blocks = [...blocks, { name: "notesoup:boot", text: boot.ok ? String(boot.result) : `# notesoup\nYour notes didn't load this time (${boot.error}). Try \`${PREFIX}notes_list\`; if it fails too, tell the human.` }]
148
369
  }
149
- const block = { name: "notesoup:boot", text: boot.ok ? String(boot.result) : `# notesoup\n${boot.error}` }
150
- return { ...result, blocks: [...result.blocks, block] }
370
+ const warning = await warningBlock($, state)
371
+ return { ...result, blocks: warning === undefined ? blocks : [...blocks, warning] }
151
372
  })
152
373
 
153
374
  }
154
375
 
376
+ /**
377
+ * The one warning per window: injected only once the measured context crosses the resolved
378
+ * warn point, and only until the window changes. The reset decision runs independently.
379
+ */
380
+ async function warningBlock($: Engine, state: ResetState): Promise<{ name: string; text: string } | undefined> {
381
+ if (state.headless || state.compactDisabled || !state.identity || state.warnedWindow === state.window) return undefined
382
+ const generation = state.generation
383
+ const usage = await contextUsage($, state)
384
+ if (generation !== state.generation || usage === undefined) return undefined
385
+ const limits = await limitsOf($, state, usage)
386
+ if (limits === undefined) return undefined
387
+ const measured = measuredValue(limits, usage)
388
+ if (measured === undefined || measured < limits.warn) return undefined
389
+ const texts = await loadTexts($, state)
390
+ if (generation !== state.generation || texts?.warning === undefined) return undefined
391
+ state.warnedWindow = state.window
392
+ return { name: "notesoup:warning", text: texts.warning }
393
+ }
394
+
155
395
  function restoreWindow(state: ResetState, messages: readonly { role: string; text: string }[]) {
156
396
  if (!state.identity) return
157
397
  const prefix = `Current context window id: claude:${state.identity.sessionId}:`
158
398
  for (const message of messages) {
159
- if (message.role !== "user" || !message.text.startsWith("<context_window>\nAgent name: claude ")) continue
399
+ if (message.role !== "user" || !message.text.includes("<context_window>\nAgent name: claude ")) continue
160
400
  const line = message.text.split("\n").find((value) => value.startsWith(prefix))
161
401
  if (!line) continue
162
402
  const suffix = line.slice(prefix.length)
@@ -174,43 +414,57 @@ function armManual($: Engine, state: ResetState, signal: { wake?: () => void })
174
414
  const requested = new Promise<void>((resolve) => { signal.wake = resolve })
175
415
  void requested.then(() => {
176
416
  signal.wake = undefined
177
- $.clock.after(0, () => finishManual($, state, signal))
417
+ const generation = state.generation
418
+ $.clock.after(0, () => finishManual($, state, signal, generation))
178
419
  })
179
420
  }
180
- async function finishManual($: Engine, state: ResetState, signal: { wake?: () => void }) {
421
+ async function finishManual($: Engine, state: ResetState, signal: { wake?: () => void }, generation: number) {
181
422
  try {
423
+ if (generation !== state.generation) return
182
424
  if (state.manualPending && !state.turnRunning) {
183
- await $.prompt.submit({ text: "A context reset was requested. Save any essential checkpoint to session notes now, then end this turn. notesoup will reset to a fresh notes-only window after the turn completes." })
425
+ const texts = await loadTexts($, state)
426
+ if (generation !== state.generation) return
427
+ if (texts?.warning === undefined) {
428
+ state.manualPending = false
429
+ log($, "Couldn't clear memory: the close-out prompt didn't load")
430
+ return
431
+ }
432
+ await $.prompt.submit({ text: texts.warning })
184
433
  }
185
434
  } catch {
186
- state.manualPending = false
187
- log($, "Couldn't clear memory: the close-out turn didn't start")
435
+ if (generation === state.generation) {
436
+ state.manualPending = false
437
+ log($, "Couldn't clear memory: the close-out turn didn't start")
438
+ }
188
439
  } finally { armManual($, state, signal) }
189
440
  }
190
441
 
191
442
  // The sandbox permits $ forwarding only to file-top-level helpers.
192
443
  async function maybeReset($: Engine, state: ResetState, complete: boolean) {
193
- if (!state.identity || state.resetting || state.headless) return
194
- let percent: number | undefined
195
- try { percent = (await $.session.usage()).context?.percent }
196
- catch {
197
- if (!state.usageFailureLogged) {
198
- state.usageFailureLogged = true
199
- log($, "Context usage unavailable · automatic clear-memory skipped")
200
- }
444
+ if (!state.identity || state.resetting || state.headless || state.compactDisabled) return
445
+ const generation = state.generation
446
+ const usage = await contextUsage($, state)
447
+ if (generation !== state.generation || state.turnRunning) return
448
+ let due = complete && state.manualPending
449
+ if (!due && usage !== undefined) {
450
+ const limits = await limitsOf($, state, usage)
451
+ const measured = limits === undefined ? undefined : measuredValue(limits, usage)
452
+ // Missing measurements do not trigger a reset.
453
+ if (limits !== undefined && measured !== undefined && measured >= limits.reset) due = true
201
454
  }
202
- if (state.turnRunning) return
203
- if ((complete && state.manualPending) || (typeof percent === "number" && Number.isFinite(percent) && percent >= 85)) {
455
+ if (due && generation === state.generation) {
204
456
  state.manualPending = false
205
457
  await reset($, state)
206
458
  }
207
459
  }
208
460
  async function reset($: Engine, state: ResetState): Promise<void> {
209
461
  if (!state.identity || state.headless || state.resetting) return
462
+ const generation = state.generation
210
463
  state.resetting = true
211
464
  state.preparedBoot = undefined
212
465
  try {
213
466
  const result = await $.session.compact({ instructions: RESET_INSTRUCTIONS })
467
+ if (generation !== state.generation) return
214
468
  if (result.skip !== undefined || state.preparedBoot === undefined) {
215
469
  log($, `Memory not cleared · ${result.skip ?? "notes boot was not retained"}`)
216
470
  return
@@ -219,6 +473,7 @@ async function reset($: Engine, state: ResetState): Promise<void> {
219
473
  state.window++
220
474
  log($, "Memory cleared")
221
475
  } catch (error) {
476
+ if (generation !== state.generation) return
222
477
  const text = String(error)
223
478
  if (text.includes("headless (-p / SDK)")) {
224
479
  state.headless = true
@@ -229,7 +484,9 @@ async function reset($: Engine, state: ResetState): Promise<void> {
229
484
  log($, `Couldn't clear memory: ${text.replace(/[\r\n].*$/s, "")}`)
230
485
  }
231
486
  } finally {
232
- state.preparedBoot = undefined
233
- state.resetting = false
487
+ if (generation === state.generation) {
488
+ state.preparedBoot = undefined
489
+ state.resetting = false
490
+ }
234
491
  }
235
492
  }
@@ -24,7 +24,7 @@ The homes serve different readers:
24
24
  4. **Relocate misfiled notes.** When a standing ruling or the note's own MAP already names its proper home, migrate it: copy it there preserving frontmatter with a one-line provenance note, crumple the original, and update both homes' maps. Crumple keeps the original readable by address, so relocation is reversible: do it, don't propose it. Propose only when the destination home itself is unclear.
25
25
  5. **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.
26
26
  6. **Keep notes manageable.** Aim below about 200 lines / 8KB per note. Split oversized notes by topic with one-line cross-links. Checkpoints may exceed the budget: trim prose, never facts.
27
- 7. **Keep maps useful.** Each writable home's MAP.md lists its durable notes, one line per entry, with an unambiguous address and a short gist in your own words. Add promoted notes and drop entries that no longer hold. Maps follow the same size budget.
27
+ 7. **Keep maps useful.** Each writable home's MAP.md may include a Cheatsheet of rules that apply in every window; keep it short, about 5 lines. The rest stays the note index: durable notes' addresses and short gists, for lookup. Preserve standing rules, add promoted notes, and drop entries that no longer hold. Maps follow the same size budget.
28
28
  8. **Preserve the record.** Never physically delete a live note; after merging, crumple the absorbed note only if it is writable. The wastebasket is the one exception: physically delete a crumpled note when its home is writable and it has been crumpled and untouched for more than 7 days. With raw frontmatter, judge by `lastAccessed`, falling back to `crumpledAt`. With only `notes_*` tools, judge by `crumpled_at`. If no date is readable, keep the note and report it. Never read a raw note through `notes_read` to get the date: it refreshes `lastAccessed`. A venue that cannot delete files lists the doomed addresses in its report instead of blanking them. Preserve existing metadata and provenance.
29
29
 
30
30
  ## Report
@@ -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.
8
+ Read `../../playbook.md` completely, resolving the path from this skill's directory. It is the shared guide to reviewing and organizing notes. MAP may include a short Cheatsheet of rules that apply in every window (about 5 lines); the rest stays the note index, for lookup.
9
9
 
10
10
  Dream in this agent's current session. Do not start another agent or model unless the human asks.
11
11
 
@@ -0,0 +1,61 @@
1
+ ---
2
+ name: memory
3
+ description: How notesoup's `notes_*` and `history_*` tools fit together — note addresses and homes, finding things again, and saving recovery state. Use when the context-window protocol is missing or unclear, or when unsure where a note belongs or how to find something again.
4
+ ---
5
+
6
+ # Memory
7
+
8
+ Two stores outlive the context window. Anything in neither is lost when the window ends or is wiped.
9
+
10
+ - **Notes** (`notes_*`) — what you choose to keep. Plain markdown, written on purpose.
11
+ - **History** (`history_*`) — what happened in this session: messages, tool calls, summaries. Read-only.
12
+
13
+ Each tool's own description covers its parameters and paging. This guide covers what the descriptions cannot: where notes belong, and how the tools work together.
14
+
15
+ ## Addresses
16
+
17
+ The address decides who a note belongs to and how long it lasts.
18
+
19
+ | Address | Note | Keep there |
20
+ | --- | --- | --- |
21
+ | `<path>`, no `@` | session note | current task state and loose ends; gone with the session |
22
+ | `@project/<path>` | project note | decisions and constraints future work must respect |
23
+ | `@human/<path>` | human note | how to work with this human, across projects |
24
+ | `@self/<path>` | self note | your reminders; yours alone if you have a name, shared by everyone nameless |
25
+ | `@model/<path>` | model note | what applies to this model only |
26
+
27
+ When notes conflict, the one most relevant to what you're doing applies. If that doesn't settle it, judge the case.
28
+
29
+ Any other `@` prefix is refused. A path is relative and `/`-separated, with no empty, `.` or `..` segments.
30
+
31
+ `@` 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.
32
+
33
+ `MAP.md` at the root of each `@` home is a page you wake up with. It may include a Cheatsheet of rules that apply in every window; keep it short, about 5 lines. The rest is the note index: each durable note's address and gist, for lookup. Update it whenever you add, move or crumple a durable note.
34
+
35
+ Write only what git and history cannot give back. Crumple notes that are no longer true; a stale note is worse than none.
36
+
37
+ ## Finding things again
38
+
39
+ - **A note**: `notes_list` with a `glob` when you know roughly where it lives, `notes_search` when you know a phrase; then `notes_read` the address.
40
+ - **Something that happened**: `history_list` to browse or search this session's events; `history_read` the seq for the whole event.
41
+ - **An earlier window**: `history_windows` gives window ids; pass one as `window_id` to `history_list`.
42
+
43
+ Seqs are stable. Write the useful ones into a note so they need not be found twice.
44
+
45
+ ## Saving recovery state
46
+
47
+ Before a long or risky step, or when room runs low, keep session notes named for what they hold (not `current.md`) and rewrite them to the current state instead of starting new ones or appending a timeline. Record:
48
+
49
+ - the goal and the current step
50
+ - decisions made, and why
51
+ - blockers and the next action
52
+ - how the work was being done, and which skills are still needed
53
+ - where to dig: seqs, note addresses, files
54
+
55
+ `get_context_remaining` reports the room left. `clear_memory` starts a fresh window, so save the note first.
56
+
57
+ ## When a tool is missing or refuses
58
+
59
+ A refusal returns `{ error, code }`; read `error` before retrying.
60
+
61
+ If a `notes_*` or `history_*` tool is absent or fails at the host level, do not imitate it: no filesystem tools on `@` addresses, and no reading or editing note storage or session files directly. Use the tools that remain, tell the human which one is missing, and keep essential state in the reply.