notesoup 0.42.0 → 0.44.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 (126) hide show
  1. package/dist/src/boot/render.js +11 -20
  2. package/dist/src/boot/snapshot.d.ts +2 -0
  3. package/dist/src/boot/snapshot.js +4 -5
  4. package/dist/src/boot/text.js +4 -2
  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 +2 -0
  9. package/dist/src/budget/text.js +2 -0
  10. package/dist/src/claude/helper.js +3 -4
  11. package/dist/src/claude/thresholds.js +45 -66
  12. package/dist/src/dream/lock.js +6 -13
  13. package/dist/src/dream/report.js +5 -15
  14. package/dist/src/history/history.js +4 -2
  15. package/dist/src/history/query.js +10 -22
  16. package/dist/src/notes/address.d.ts +2 -3
  17. package/dist/src/notes/address.js +10 -22
  18. package/dist/src/notes/errors.d.ts +2 -0
  19. package/dist/src/notes/errors.js +5 -0
  20. package/dist/src/notes/frontmatter.js +16 -2
  21. package/dist/src/notes/identity.js +2 -4
  22. package/dist/src/notes/paths.d.ts +7 -2
  23. package/dist/src/notes/paths.js +18 -60
  24. package/dist/src/notes/project-home.d.ts +25 -0
  25. package/dist/src/notes/project-home.js +231 -0
  26. package/dist/src/notes/store.d.ts +4 -2
  27. package/dist/src/notes/store.js +52 -45
  28. package/dist/src/pi/boot.js +17 -9
  29. package/dist/src/pi/budget.d.ts +3 -3
  30. package/dist/src/pi/budget.js +11 -11
  31. package/dist/src/pi/dream/cli.js +43 -11
  32. package/dist/src/pi/estimate.d.ts +1 -5
  33. package/dist/src/pi/estimate.js +4 -4
  34. package/dist/src/pi/history.js +1 -4
  35. package/dist/src/pi/notes/adapter.d.ts +1 -1
  36. package/dist/src/pi/notes/adapter.js +3 -3
  37. package/dist/src/pi/reset/artifacts.d.ts +0 -2
  38. package/dist/src/pi/reset/artifacts.js +4 -4
  39. package/dist/src/pi/reset/committed.js +2 -2
  40. package/dist/src/pi/runtime.js +8 -5
  41. package/dist/src/pi/thresholds.js +5 -9
  42. package/dist/src/pi/tool-result.d.ts +1 -4
  43. package/dist/src/pi/tool-result.js +1 -1
  44. package/dist/src/pi/window.d.ts +5 -0
  45. package/dist/src/pi/window.js +7 -0
  46. package/dist/src/settings.d.ts +2 -0
  47. package/dist/src/settings.js +4 -3
  48. package/dist/src/tools/history.js +4 -7
  49. package/dist/src/tools/notes.d.ts +47 -21
  50. package/dist/src/tools/notes.js +20 -19
  51. package/dist/src/tools/output.d.ts +0 -3
  52. package/dist/src/tools/output.js +1 -9
  53. package/dist/src/tools/result.d.ts +1 -0
  54. package/dist/src/tools/result.js +14 -20
  55. package/dist/src/tools/schema.d.ts +0 -1
  56. package/dist/src/tools/schema.js +0 -1
  57. package/dist/test/agent-loop.test.js +1 -2
  58. package/dist/test/boot.integration.test.js +1 -1
  59. package/dist/test/claude-mod.test.js +253 -10
  60. package/dist/test/claude-validation.test.d.ts +1 -0
  61. package/dist/test/claude-validation.test.js +73 -0
  62. package/dist/test/dream-skill.test.js +2 -4
  63. package/dist/test/dream.test.js +14 -0
  64. package/dist/test/helpers/extension.js +1 -1
  65. package/dist/test/history.integration.test.js +2 -1
  66. package/dist/test/host-neutral.test.js +15 -0
  67. package/dist/test/notes-library.test.js +30 -1
  68. package/dist/test/notes.integration.test.js +7 -7
  69. package/dist/test/notes.test.js +36 -14
  70. package/dist/test/project-home.test.d.ts +1 -0
  71. package/dist/test/project-home.test.js +134 -0
  72. package/dist/test/reset-lifecycle.test.js +1 -1
  73. package/docs/claude-code-mod.md +5 -3
  74. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  75. package/mods/notesoup/dist/claude/helper.js +359 -218
  76. package/mods/notesoup/hooks/register.ts +158 -67
  77. package/mods/notesoup/playbook.md +1 -1
  78. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  79. package/mods/notesoup/skills/memory/SKILL.md +62 -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 +2 -1
  84. package/src/boot/render.ts +11 -21
  85. package/src/boot/snapshot.ts +5 -5
  86. package/src/boot/text.ts +4 -2
  87. package/src/budget/parse.ts +39 -0
  88. package/src/budget/policy.ts +2 -6
  89. package/src/budget/text.ts +3 -0
  90. package/src/claude/helper.ts +4 -4
  91. package/src/claude/thresholds.ts +45 -62
  92. package/src/dream/lock.ts +3 -9
  93. package/src/dream/report.ts +5 -10
  94. package/src/history/history.ts +4 -2
  95. package/src/history/query.ts +10 -23
  96. package/src/notes/address.ts +9 -21
  97. package/src/notes/errors.ts +6 -0
  98. package/src/notes/frontmatter.ts +12 -2
  99. package/src/notes/identity.ts +1 -3
  100. package/src/notes/paths.ts +14 -52
  101. package/src/notes/project-home.ts +197 -0
  102. package/src/notes/store.ts +46 -45
  103. package/src/pi/boot.ts +15 -17
  104. package/src/pi/budget.ts +10 -11
  105. package/src/pi/dream/cli.ts +35 -10
  106. package/src/pi/estimate.ts +4 -4
  107. package/src/pi/history.ts +1 -5
  108. package/src/pi/notes/adapter.ts +3 -3
  109. package/src/pi/reset/artifacts.ts +4 -4
  110. package/src/pi/reset/committed.ts +2 -2
  111. package/src/pi/runtime.ts +7 -6
  112. package/src/pi/thresholds.ts +5 -11
  113. package/src/pi/tool-result.ts +1 -1
  114. package/src/pi/window.ts +8 -0
  115. package/src/settings.ts +4 -3
  116. package/src/tools/history.ts +4 -8
  117. package/src/tools/notes.ts +22 -25
  118. package/src/tools/output.ts +1 -12
  119. package/src/tools/result.ts +14 -19
  120. package/src/tools/schema.ts +0 -1
  121. package/dist/src/dream/playbook.d.ts +0 -1
  122. package/dist/src/dream/playbook.js +0 -2
  123. package/dist/src/pi/reset/text.d.ts +0 -4
  124. package/dist/src/pi/reset/text.js +0 -7
  125. package/src/dream/playbook.ts +0 -3
  126. package/src/pi/reset/text.ts +0 -9
@@ -2,17 +2,13 @@ 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" | "env">
13
- type UsageSample = { context?: unknown }
14
- /** `usage({breakdown:true})` is wired in the engine but absent from the public typings. */
15
- type UsageReader = (options?: { breakdown?: boolean }) => Promise<UsageSample | undefined>
11
+ type Engine = Pick<EngineInterface, "process" | "session" | "ui" | "clock" | "prompt" | "env" | "settings">
16
12
  /** The measured context, as much of it as the engine reported. */
17
13
  type ContextUsage = { tokens?: number; window?: number; percent?: number }
18
14
  /** Shared reset prose, fetched once per session so Pi and Claude cannot drift apart. */
@@ -22,14 +18,17 @@ type ClaudeLimits = {
22
18
  native: number; reset: number; warn: number; resetMargin: number; warningRunway: number
23
19
  }
24
20
  type ResetState = {
25
- identity?: Identity; window: number; turnRunning: boolean; resetting: boolean
21
+ identity?: Identity; generation: number; window: number; turnRunning: boolean; resetting: boolean
26
22
  manualPending: boolean; headless: boolean; usageFailureLogged: boolean; preparedBoot?: string; retainedBoot?: string
27
- compactDisabled: boolean; limitsFailureLogged: boolean; limitsAttempted: boolean; limitsWindow: number
28
- limits?: ClaudeLimits; warnedWindow?: number; texts?: SharedTexts
23
+ compactDisabled: boolean; limitsFailureLogged: boolean; limitsAttempts: number; limitsWindow: number
24
+ limits?: ClaudeLimits; warnedWindow?: number; texts?: SharedTexts; settingsFailureLogged: boolean
29
25
  }
30
26
  const HEADLESS = "Clear-memory is off in headless (-p / SDK) sessions"
31
27
  const COMPACT_DISABLED = "Clear-memory can't run: compaction is off in this session (DISABLE_COMPACT)"
32
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
33
32
  const RESET_INSTRUCTIONS = "notesoup: reset to a fresh notes-only context window."
34
33
  const BOOT_TOOLS = {
35
34
  notes: `${PREFIX}notes_*`, notesList: `${PREFIX}notes_list`,
@@ -64,26 +63,39 @@ function limitsShape(value: unknown): ClaudeLimits | undefined {
64
63
  if (unit === undefined || native === undefined || reset === undefined || warn === undefined || resetMargin === undefined || warningRunway === undefined) return undefined
65
64
  return { source: typeof row.source === "string" ? row.source : "unknown", autoCompact: row.autoCompact !== false, unit, native, reset, warn, resetMargin, warningRunway }
66
65
  }
67
- async function envValue($: Engine, name: string): Promise<string | undefined> {
68
- try { const value = await $.env.get(name); return typeof value === "string" ? value : undefined } catch { return undefined }
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 }
69
75
  }
70
76
  /** Presence-style environment flags: any value but an explicit no counts as on. */
71
- async function envFlag($: Engine, name: string): Promise<boolean> {
72
- const value = await envValue($, name)
77
+ async function compactDisabled($: Engine): Promise<boolean> {
78
+ let value: string | undefined
79
+ try { value = await $.env.get("DISABLE_COMPACT") } catch { return false }
73
80
  if (value === undefined) return false
74
81
  const text = value.trim().toLowerCase()
75
- return text !== "" && text !== "0" && text !== "false"
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"
76
84
  }
77
- async function readSettings($: Engine): Promise<unknown> {
78
- const settings = ($ as { settings?: { read?: (options?: unknown) => Promise<unknown> } }).settings
79
- if (typeof settings?.read !== "function") return undefined
80
- try { return await settings.read() } catch { return undefined }
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
+ }
81
94
  }
82
95
  /** The measured context, or undefined when the engine cannot report it. The failure logs once. */
83
96
  async function contextUsage($: Engine, state: ResetState): Promise<ContextUsage | undefined> {
84
97
  try {
85
- const read = $.session.usage as unknown as UsageReader
86
- const context = (await read())?.context
98
+ const context = (await $.session.usage()).context
87
99
  if (typeof context !== "object" || context === null) return {}
88
100
  const row = context as Record<string, unknown>
89
101
  return { tokens: numberOf(row.tokens), window: numberOf(row.window), percent: numberOf(row.percent) }
@@ -97,42 +109,52 @@ async function contextUsage($: Engine, state: ResetState): Promise<ContextUsage
97
109
  }
98
110
  async function breakdownContext($: Engine): Promise<Record<string, unknown> | undefined> {
99
111
  try {
100
- const read = $.session.usage as unknown as UsageReader
101
- const context = (await read({ breakdown: true }))?.context
112
+ const context = (await $.session.usage({ breakdown: "summary" })).context
102
113
  return typeof context === "object" && context !== null ? context as Record<string, unknown> : undefined
103
114
  } catch { return undefined }
104
115
  }
105
116
  /** Everything the resolver may read: measured usage plus the raw settings and environment. */
106
- async function limitFacts($: Engine, usage: ContextUsage): Promise<Record<string, unknown>> {
117
+ async function limitFacts($: Engine, state: ResetState, usage: ContextUsage): Promise<Record<string, unknown>> {
107
118
  return {
108
119
  usage,
109
120
  breakdown: await breakdownContext($),
110
- settings: await readSettings($),
121
+ settings: await readSettings($, state),
111
122
  env: {
112
- pctOverride: await envValue($, "CLAUDE_AUTOCOMPACT_PCT_OVERRIDE"),
113
- autoCompactWindow: await envValue($, "CLAUDE_CODE_AUTO_COMPACT_WINDOW"),
114
- disableAutoCompact: await envValue($, "DISABLE_AUTO_COMPACT"),
123
+ pctOverride: await envPctOverride($),
124
+ autoCompactWindow: await envAutoCompactWindow($),
125
+ disableAutoCompact: await envDisableAutoCompact($),
115
126
  },
116
127
  }
117
128
  }
118
129
  /**
119
130
  * The points the current window is measured against, resolved by the helper's shared
120
- * derivation. One attempt per reported window value: an unknown window resolves the percent
121
- * fallback, and a later real window re-resolves against it.
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.
122
134
  */
123
135
  async function limitsOf($: Engine, state: ResetState, usage: ContextUsage): Promise<ClaudeLimits | undefined> {
124
136
  const window = usage.window !== undefined && usage.window > 0 ? usage.window : 0
125
- if (state.limitsAttempted && state.limitsWindow === window) return state.limits
126
- const response = await run($, { op: "limits", facts: await limitFacts($, usage) }, state.identity?.cwd ?? ".")
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
127
145
  const limits = response.ok ? limitsShape(response.result) : undefined
128
- state.limitsAttempted = true
129
146
  state.limitsWindow = window
130
- if (limits) state.limits = limits
131
- else if (!state.limitsFailureLogged) {
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) {
132
154
  state.limitsFailureLogged = true
133
155
  log($, THRESHOLDS_UNAVAILABLE)
134
156
  }
135
- return limits ?? state.limits
157
+ return undefined
136
158
  }
137
159
  /** The measured value the points are expressed in; tokens win, percent × window stands in. */
138
160
  function measuredValue(limits: ClaudeLimits, usage: ContextUsage): number | undefined {
@@ -144,7 +166,9 @@ function measuredValue(limits: ClaudeLimits, usage: ContextUsage): number | unde
144
166
  async function loadTexts($: Engine, state: ResetState): Promise<SharedTexts | undefined> {
145
167
  if (state.texts) return state.texts
146
168
  if (!state.identity) return undefined
169
+ const generation = state.generation
147
170
  const response = await run($, { op: "texts" }, state.identity.cwd)
171
+ if (generation !== state.generation) return undefined
148
172
  const texts = response.ok ? sharedTextsOf(response.result) : undefined
149
173
  if (texts) state.texts = texts
150
174
  return texts
@@ -176,34 +200,61 @@ async function run($: { process: { run: (argv: readonly string[], init?: { cwd?:
176
200
  try { return decode(await $.process.run(["node", HELPER], { cwd, stdin: `${JSON.stringify(request)}\n`, timeoutMs: TIMEOUT_MS })) }
177
201
  catch { return { ok: false as const, error: "helper execution failed" } }
178
202
  }
179
- function identityOf(e: { cwd: string }, sessionId: string, home: string, model: string): Identity {
180
- 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
181
244
  }
182
245
 
183
246
  export function register(on: On) {
184
- let identity: Identity | undefined
185
247
  const manualSignal: { wake?: () => void } = {}
186
- const state: ResetState = { window: 0, turnRunning: false, resetting: false, manualPending: false, headless: false, usageFailureLogged: false, compactDisabled: false, limitsFailureLogged: false, limitsAttempted: false, limitsWindow: 0 }
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 }
187
249
  const registered = new Set<string>()
188
250
  on("session.start", async ($, e, next) => {
189
- const home = await $.env.get("PI_NOTES_HOME") ?? `${await $.env.get("HOME") ?? await $.env.get("USERPROFILE") ?? ""}/.agents/notes`
190
- identity = identityOf(e, await $.session.id(), home, "claude")
191
- state.identity = identity
192
- state.window = 0
193
- state.turnRunning = state.resetting = state.manualPending = state.usageFailureLogged = false
251
+ forgetSession(state)
252
+ await refreshIdentity($, state)
194
253
  state.headless = !e.isInteractive
195
254
  if (state.headless) log($, HEADLESS)
196
- state.preparedBoot = state.retainedBoot = undefined
197
- state.texts = state.limits = undefined
198
- state.limitsAttempted = false
199
- state.limitsWindow = 0
200
- state.warnedWindow = undefined
201
255
  // Compaction is the capability the reset is built on; without it, automatic resets stop here.
202
- state.compactDisabled = await envFlag($, "DISABLE_COMPACT")
256
+ state.compactDisabled = await compactDisabled($)
203
257
  if (state.compactDisabled) log($, COMPACT_DISABLED)
204
- // The engine's history view includes retained boots on resume/reload.
205
- // Recover their ordinal without treating that view as inference context.
206
- try { restoreWindow(state, await $.session.messages()) } catch { /* A fresh session starts at zero. */ }
207
258
  registered.clear()
208
259
  await loadTexts($, state)
209
260
  armManual($, state, manualSignal)
@@ -217,8 +268,14 @@ export function register(on: On) {
217
268
  }
218
269
  return next(e)
219
270
  })
271
+ on("session.end", async ($, e, next) => {
272
+ forgetSession(state)
273
+ return next(e)
274
+ })
220
275
  on("tool.call", async ($, e, next) => {
221
- 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")
222
279
  const { tool, tool_use_id: _toolUseId, agentId: _agentId, ...params } = e
223
280
  const result = await run($, { op: "tool", tool: tool.slice(PREFIX.length), params, identity }, identity.cwd)
224
281
  if (!result.ok) return errorResult(result.error)
@@ -228,23 +285,29 @@ export function register(on: On) {
228
285
  return outcome.ok ? { result: outcome.text } : { result: outcome.text, isError: true }
229
286
  })
230
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)
231
292
  state.turnRunning = true
232
293
  return next(e)
233
294
  })
234
295
  on("turn.complete", async ($, e, next) => {
235
296
  const result = await next(e)
236
297
  if (e.agentId !== undefined) return result
298
+ if (!await refreshIdentity($, state)) return result
237
299
  state.turnRunning = false
238
300
  await maybeReset($, state, true)
239
301
  return result
240
302
  })
241
303
  on("session.measure", async ($, e, next) => {
242
304
  const result = await next(e)
243
- await maybeReset($, state, false)
305
+ if (await refreshIdentity($, state)) await maybeReset($, state, false)
244
306
  return result
245
307
  })
246
308
  on("command.run", async ($, e, next) => {
247
309
  if (e.command !== "clear-memory") return next(e)
310
+ if (!await refreshIdentity($, state)) return { text: "🥣 Session changed · try clear-memory again" }
248
311
  if (state.headless) return { text: `🥣 ${HEADLESS}` }
249
312
  if (state.compactDisabled) return { text: `🥣 ${COMPACT_DISABLED}` }
250
313
  if (state.resetting || state.manualPending) return { text: "🥣 Clear-memory already queued" }
@@ -259,11 +322,24 @@ export function register(on: On) {
259
322
  return { text: "🥣 Clearing memory · notes first, then it stops" }
260
323
  })
261
324
  on("session.compact", async ($, e, next) => {
325
+ if (e.agentId !== undefined) return next(e)
326
+ const identity = await refreshIdentity($, state)
262
327
  // Do not take over native /compact or another plugin's compaction.
263
- if (!state.resetting || e.trigger !== "plugin" || e.agentId !== undefined || !identity) return next(e)
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
264
339
  const texts = await loadTexts($, state)
265
340
  if (texts?.continuation === undefined) return { skip: "reset text didn't load" }
266
341
  const boot = await buildBoot($, identity, state.window + 1, texts)
342
+ if (generation !== state.generation) return { skip: "session changed while building the notes boot" }
267
343
  if (!boot.ok) return { skip: `notes didn't load: ${boot.error}` }
268
344
  state.preparedBoot = String(boot.result)
269
345
  // The same closed reset shape as Pi: notes boot first, then the one reset message.
@@ -274,6 +350,8 @@ export function register(on: On) {
274
350
  })
275
351
  on("prompt.context", async ($, e, next) => {
276
352
  const result = await next(e)
353
+ const identity = await refreshIdentity($, state)
354
+ const generation = state.generation
277
355
  // The reset already retained its boot as the sole conversation message.
278
356
  // Prompt context still recomputes, but must not inject a duplicate snapshot.
279
357
  const retained = state.retainedBoot !== undefined
@@ -281,9 +359,10 @@ export function register(on: On) {
281
359
  if (!retained && !blocks.some((block) => block.name === "notesoup:boot") && identity) {
282
360
  const texts = await loadTexts($, state)
283
361
  const boot = await buildBoot($, identity, state.window, texts)
362
+ if (generation !== state.generation) return result
284
363
  if (!boot.ok) {
285
364
  try {
286
- await $.ui.notify("🥣 Notes didn't load")
365
+ await $.ui.toast("🥣 Notes didn't load")
287
366
  } catch { /* Notification failure must not suppress the fallback block. */ }
288
367
  }
289
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.` }]
@@ -300,14 +379,15 @@ export function register(on: On) {
300
379
  */
301
380
  async function warningBlock($: Engine, state: ResetState): Promise<{ name: string; text: string } | undefined> {
302
381
  if (state.headless || state.compactDisabled || !state.identity || state.warnedWindow === state.window) return undefined
382
+ const generation = state.generation
303
383
  const usage = await contextUsage($, state)
304
- if (usage === undefined) return undefined
384
+ if (generation !== state.generation || usage === undefined) return undefined
305
385
  const limits = await limitsOf($, state, usage)
306
386
  if (limits === undefined) return undefined
307
387
  const measured = measuredValue(limits, usage)
308
388
  if (measured === undefined || measured < limits.warn) return undefined
309
389
  const texts = await loadTexts($, state)
310
- if (texts?.warning === undefined) return undefined
390
+ if (generation !== state.generation || texts?.warning === undefined) return undefined
311
391
  state.warnedWindow = state.window
312
392
  return { name: "notesoup:warning", text: texts.warning }
313
393
  }
@@ -316,7 +396,7 @@ function restoreWindow(state: ResetState, messages: readonly { role: string; tex
316
396
  if (!state.identity) return
317
397
  const prefix = `Current context window id: claude:${state.identity.sessionId}:`
318
398
  for (const message of messages) {
319
- 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
320
400
  const line = message.text.split("\n").find((value) => value.startsWith(prefix))
321
401
  if (!line) continue
322
402
  const suffix = line.slice(prefix.length)
@@ -334,13 +414,16 @@ function armManual($: Engine, state: ResetState, signal: { wake?: () => void })
334
414
  const requested = new Promise<void>((resolve) => { signal.wake = resolve })
335
415
  void requested.then(() => {
336
416
  signal.wake = undefined
337
- $.clock.after(0, () => finishManual($, state, signal))
417
+ const generation = state.generation
418
+ $.clock.after(0, () => finishManual($, state, signal, generation))
338
419
  })
339
420
  }
340
- async function finishManual($: Engine, state: ResetState, signal: { wake?: () => void }) {
421
+ async function finishManual($: Engine, state: ResetState, signal: { wake?: () => void }, generation: number) {
341
422
  try {
423
+ if (generation !== state.generation) return
342
424
  if (state.manualPending && !state.turnRunning) {
343
425
  const texts = await loadTexts($, state)
426
+ if (generation !== state.generation) return
344
427
  if (texts?.warning === undefined) {
345
428
  state.manualPending = false
346
429
  log($, "Couldn't clear memory: the close-out prompt didn't load")
@@ -349,16 +432,19 @@ async function finishManual($: Engine, state: ResetState, signal: { wake?: () =>
349
432
  await $.prompt.submit({ text: texts.warning })
350
433
  }
351
434
  } catch {
352
- state.manualPending = false
353
- 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
+ }
354
439
  } finally { armManual($, state, signal) }
355
440
  }
356
441
 
357
442
  // The sandbox permits $ forwarding only to file-top-level helpers.
358
443
  async function maybeReset($: Engine, state: ResetState, complete: boolean) {
359
444
  if (!state.identity || state.resetting || state.headless || state.compactDisabled) return
445
+ const generation = state.generation
360
446
  const usage = await contextUsage($, state)
361
- if (state.turnRunning) return
447
+ if (generation !== state.generation || state.turnRunning) return
362
448
  let due = complete && state.manualPending
363
449
  if (!due && usage !== undefined) {
364
450
  const limits = await limitsOf($, state, usage)
@@ -366,17 +452,19 @@ async function maybeReset($: Engine, state: ResetState, complete: boolean) {
366
452
  // Missing measurements do not trigger a reset.
367
453
  if (limits !== undefined && measured !== undefined && measured >= limits.reset) due = true
368
454
  }
369
- if (due) {
455
+ if (due && generation === state.generation) {
370
456
  state.manualPending = false
371
457
  await reset($, state)
372
458
  }
373
459
  }
374
460
  async function reset($: Engine, state: ResetState): Promise<void> {
375
461
  if (!state.identity || state.headless || state.resetting) return
462
+ const generation = state.generation
376
463
  state.resetting = true
377
464
  state.preparedBoot = undefined
378
465
  try {
379
466
  const result = await $.session.compact({ instructions: RESET_INSTRUCTIONS })
467
+ if (generation !== state.generation) return
380
468
  if (result.skip !== undefined || state.preparedBoot === undefined) {
381
469
  log($, `Memory not cleared · ${result.skip ?? "notes boot was not retained"}`)
382
470
  return
@@ -385,6 +473,7 @@ async function reset($: Engine, state: ResetState): Promise<void> {
385
473
  state.window++
386
474
  log($, "Memory cleared")
387
475
  } catch (error) {
476
+ if (generation !== state.generation) return
388
477
  const text = String(error)
389
478
  if (text.includes("headless (-p / SDK)")) {
390
479
  state.headless = true
@@ -395,7 +484,9 @@ async function reset($: Engine, state: ResetState): Promise<void> {
395
484
  log($, `Couldn't clear memory: ${text.replace(/[\r\n].*$/s, "")}`)
396
485
  }
397
486
  } finally {
398
- state.preparedBoot = undefined
399
- state.resetting = false
487
+ if (generation === state.generation) {
488
+ state.preparedBoot = undefined
489
+ state.resetting = false
490
+ }
400
491
  }
401
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,62 @@
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
+ | `@projects/<name>/<path>` | named project, read-only | discover names and root paths with `notes_list` glob `@projects/*/**` |
27
+
28
+ When notes conflict, the one most relevant to what you're doing applies. If that doesn't settle it, judge the case.
29
+
30
+ Any other `@` prefix is refused. A path is relative and `/`-separated, with no empty, `.` or `..` segments.
31
+
32
+ `@` 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.
33
+
34
+ `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.
35
+
36
+ Write only what git and history cannot give back. Crumple notes that are no longer true; a stale note is worse than none.
37
+
38
+ ## Finding things again
39
+
40
+ - **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.
41
+ - **Something that happened**: `history_list` to browse or search this session's events; `history_read` the seq for the whole event.
42
+ - **An earlier window**: `history_windows` gives window ids; pass one as `window_id` to `history_list`.
43
+
44
+ Seqs are stable. Write the useful ones into a note so they need not be found twice.
45
+
46
+ ## Saving recovery state
47
+
48
+ 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:
49
+
50
+ - the goal and the current step
51
+ - decisions made, and why
52
+ - blockers and the next action
53
+ - how the work was being done, and which skills are still needed
54
+ - where to dig: seqs, note addresses, files
55
+
56
+ `get_context_remaining` reports the room left. `clear_memory` starts a fresh window, so save the note first.
57
+
58
+ ## When a tool is missing or refuses
59
+
60
+ A refusal returns `{ error, code }`; read `error` before retrying.
61
+
62
+ 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.42.0",
3
+ "version": "0.44.0",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
@@ -43,14 +43,16 @@
43
43
  "README.md",
44
44
  "playbook.md",
45
45
  "skills",
46
- "mods"
46
+ "mods",
47
+ "!mods/notesoup/types",
48
+ "!mods/notesoup/tsconfig.json"
47
49
  ],
48
50
  "bin": {
49
51
  "dream": "dist/src/pi/dream/cli.js"
50
52
  },
51
53
  "scripts": {
52
54
  "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json && node scripts/build-extension.mjs && node -e \"require('node:fs').chmodSync('dist/src/pi/dream/cli.js', 0o755)\"",
53
- "typecheck": "tsc -p tsconfig.json --noEmit",
55
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p mods/notesoup/tsconfig.json",
54
56
  "test": "npm run build && node --test dist/test/*.test.js",
55
57
  "prepublishOnly": "npm run typecheck",
56
58
  "prepack": "npm run build"
package/playbook.md CHANGED
@@ -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
 
@@ -23,6 +23,7 @@ The address decides who a note belongs to and how long it lasts.
23
23
  | `@human/<path>` | human note | how to work with this human, across projects |
24
24
  | `@self/<path>` | self note | your reminders; yours alone if you have a name, shared by everyone nameless |
25
25
  | `@model/<path>` | model note | what applies to this model only |
26
+ | `@projects/<name>/<path>` | named project, read-only | discover names and root paths with `notes_list` glob `@projects/*/**` |
26
27
 
27
28
  When notes conflict, the one most relevant to what you're doing applies. If that doesn't settle it, judge the case.
28
29
 
@@ -30,7 +31,7 @@ Any other `@` prefix is refused. A path is relative and `/`-separated, with no e
30
31
 
31
32
  `@` 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
 
33
- `MAP.md` at the root of each `@` home is its index: one line per durable note, address and gist. Update it whenever you add, move or crumple a durable note.
34
+ `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
 
35
36
  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