notesoup 0.39.0 → 0.41.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 (91) hide show
  1. package/README.md +5 -2
  2. package/dist/src/boot/render.js +2 -2
  3. package/dist/src/boot/text.d.ts +0 -4
  4. package/dist/src/boot/text.js +18 -14
  5. package/dist/src/budget/policy.js +1 -1
  6. package/dist/src/budget/text.js +1 -1
  7. package/dist/src/dream/doctor.js +2 -1
  8. package/dist/src/dream/git.js +2 -1
  9. package/dist/src/dream/report.js +3 -2
  10. package/dist/src/error-message.d.ts +2 -0
  11. package/dist/src/error-message.js +4 -0
  12. package/dist/src/history/history.d.ts +23 -18
  13. package/dist/src/history/history.js +37 -20
  14. package/dist/src/history/query.d.ts +37 -49
  15. package/dist/src/history/query.js +114 -56
  16. package/dist/src/notes/store.d.ts +3 -4
  17. package/dist/src/notes/store.js +12 -16
  18. package/dist/src/pi/anchored.d.ts +16 -0
  19. package/dist/src/pi/anchored.js +55 -0
  20. package/dist/src/pi/budget.d.ts +1 -1
  21. package/dist/src/pi/budget.js +33 -28
  22. package/dist/src/pi/dream/cli.js +3 -2
  23. package/dist/src/pi/dream/runner.js +2 -1
  24. package/dist/src/pi/history-tools.d.ts +1 -1
  25. package/dist/src/pi/history-tools.js +2 -3
  26. package/dist/src/pi/reset/lifecycle.d.ts +1 -1
  27. package/dist/src/pi/reset/lifecycle.js +4 -3
  28. package/dist/src/pi/reset/text.d.ts +3 -3
  29. package/dist/src/pi/reset/text.js +2 -2
  30. package/dist/src/pi/runtime.js +12 -15
  31. package/dist/src/pi/thresholds.js +2 -1
  32. package/dist/src/pi/tool-names.d.ts +0 -4
  33. package/dist/src/pi/tool-names.js +0 -4
  34. package/dist/src/tools/history.d.ts +24 -33
  35. package/dist/src/tools/history.js +57 -98
  36. package/dist/src/tools/notes.d.ts +26 -58
  37. package/dist/src/tools/notes.js +85 -103
  38. package/dist/src/tools/result.d.ts +16 -13
  39. package/dist/src/tools/result.js +24 -50
  40. package/dist/src/tools/schema.d.ts +2 -2
  41. package/dist/src/tools/schema.js +3 -3
  42. package/dist/test/agent-loop.test.js +79 -29
  43. package/dist/test/boot.integration.test.js +6 -6
  44. package/dist/test/budget-settings.integration.test.js +9 -8
  45. package/dist/test/claude-mod.test.js +11 -11
  46. package/dist/test/dependencies.test.js +1 -1
  47. package/dist/test/helpers/extension.js +2 -3
  48. package/dist/test/history.integration.test.js +200 -123
  49. package/dist/test/host-neutral.test.js +32 -58
  50. package/dist/test/notes-library.test.js +8 -8
  51. package/dist/test/notes.integration.test.js +75 -57
  52. package/dist/test/notes.test.js +44 -42
  53. package/dist/test/reset-lifecycle.test.js +2 -2
  54. package/docs/architecture.md +3 -3
  55. package/docs/notes-library.md +6 -6
  56. package/docs/tool-results.md +15 -25
  57. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  58. package/mods/notesoup/dist/claude/helper.js +128 -179
  59. package/mods/notesoup/hooks/register.ts +19 -25
  60. package/mods/notesoup/playbook.md +10 -10
  61. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  62. package/package.json +1 -1
  63. package/playbook.md +10 -10
  64. package/skills/dream/SKILL.md +1 -1
  65. package/skills/memory/SKILL.md +11 -9
  66. package/src/boot/render.ts +2 -2
  67. package/src/boot/text.ts +18 -18
  68. package/src/budget/policy.ts +1 -1
  69. package/src/budget/text.ts +1 -1
  70. package/src/dream/doctor.ts +2 -1
  71. package/src/dream/git.ts +2 -1
  72. package/src/dream/report.ts +3 -2
  73. package/src/error-message.ts +4 -0
  74. package/src/history/history.ts +36 -20
  75. package/src/history/query.ts +130 -55
  76. package/src/notes/store.ts +15 -18
  77. package/src/pi/anchored.ts +62 -0
  78. package/src/pi/budget.ts +27 -26
  79. package/src/pi/dream/cli.ts +3 -2
  80. package/src/pi/dream/runner.ts +2 -1
  81. package/src/pi/history-tools.ts +2 -3
  82. package/src/pi/reset/lifecycle.ts +5 -4
  83. package/src/pi/reset/text.ts +2 -2
  84. package/src/pi/runtime.ts +12 -15
  85. package/src/pi/thresholds.ts +2 -1
  86. package/src/pi/tool-names.ts +0 -4
  87. package/src/tools/history.ts +61 -100
  88. package/src/tools/notes.ts +84 -97
  89. package/src/tools/result.ts +24 -49
  90. package/src/tools/schema.ts +3 -3
  91. package/mods/pi-context/dist/claude/helper.js +0 -9324
@@ -14,11 +14,11 @@ type ResetState = {
14
14
  identity?: Identity; window: number; turnRunning: boolean; resetting: boolean
15
15
  manualPending: boolean; headless: boolean; usageFailureLogged: boolean; preparedBoot?: string; retainedBoot?: string
16
16
  }
17
+ const HEADLESS = "Clear-memory is off in headless (-p / SDK) sessions"
17
18
  const RESET_INSTRUCTIONS = "notesoup: reset to a fresh notes-only context window."
18
19
  const BOOT_TOOLS = {
19
20
  notes: `${PREFIX}notes_*`, notesList: `${PREFIX}notes_list`,
20
- history: "history_* (unavailable in Claude)", historyWindows: "history_windows (unavailable in Claude)", historyList: "history_list (unavailable in Claude)",
21
- historySearch: "history_search (unavailable in Claude)", historyRead: "history_read (unavailable in Claude)",
21
+ history: "history_* (unavailable in Claude)",
22
22
  remaining: "get_context_remaining (unavailable in Claude)", wipe: "/clear-memory (user command; no model reset tool in Claude)",
23
23
  }
24
24
 
@@ -26,7 +26,7 @@ async function buildBoot($: Engine, identity: Identity, window: number) {
26
26
  return run($, { op: "boot", identity, window, tools: BOOT_TOOLS }, identity.cwd)
27
27
  }
28
28
  function log($: Engine, text: string) {
29
- try { $.ui.log(`notesoup: ${text}`) } catch { /* UI must not break a turn or reset. */ }
29
+ try { $.ui.log(`🥣 ${text}`) } catch { /* UI must not break a turn or reset. */ }
30
30
  }
31
31
 
32
32
  function errorResult(message: string): ToolCallResult { return { result: `notesoup: ${message}`, isError: true } }
@@ -68,7 +68,7 @@ export function register(on: On) {
68
68
  state.window = 0
69
69
  state.turnRunning = state.resetting = state.manualPending = state.usageFailureLogged = false
70
70
  state.headless = !e.isInteractive
71
- if (state.headless) log($, "reset skipped in headless (-p / SDK) session.")
71
+ if (state.headless) log($, HEADLESS)
72
72
  state.preparedBoot = state.retainedBoot = undefined
73
73
  // The engine's history view includes retained boots on resume/reload.
74
74
  // Recover their ordinal without treating that view as inference context.
@@ -113,23 +113,23 @@ export function register(on: On) {
113
113
  })
114
114
  on("command.run", async ($, e, next) => {
115
115
  if (e.command !== "clear-memory") return next(e)
116
- if (state.headless) return { text: "notesoup: reset skipped in headless (-p / SDK) session." }
117
- if (state.resetting || state.manualPending) return { text: "notesoup: reset already pending." }
116
+ if (state.headless) return { text: `🥣 ${HEADLESS}` }
117
+ if (state.resetting || state.manualPending) return { text: "🥣 Clear-memory already queued" }
118
118
  if (state.turnRunning) {
119
119
  state.manualPending = true
120
- return { text: "notesoup: reset queued until the turn completes." }
120
+ return { text: "🥣 Clear-memory queued · runs after this turn" }
121
121
  }
122
122
  // command.run holds a turn even when idle. Start one hidden close-out
123
123
  // turn after it returns; turn.complete is the verified self-hook path.
124
124
  state.manualPending = true
125
125
  manualSignal.wake?.()
126
- return { text: "notesoup: reset requested; closing out the current window." }
126
+ return { text: "🥣 Clearing memory · notes first, then it stops" }
127
127
  })
128
128
  on("session.compact", async ($, e, next) => {
129
129
  // Do not take over native /compact or another plugin's compaction.
130
130
  if (!state.resetting || e.trigger !== "plugin" || e.agentId !== undefined || !identity) return next(e)
131
131
  const boot = await buildBoot($, identity, state.window + 1)
132
- if (!boot.ok) return { skip: `notesoup: Notes boot failed: ${boot.error}` }
132
+ if (!boot.ok) return { skip: `notes didn't load: ${boot.error}` }
133
133
  state.preparedBoot = String(boot.result)
134
134
  return { messages: [{ role: "user", text: state.preparedBoot, toolUses: [] }] }
135
135
  })
@@ -143,7 +143,7 @@ export function register(on: On) {
143
143
  const boot = await buildBoot($, identity, state.window)
144
144
  if (!boot.ok) {
145
145
  try {
146
- await $.ui.notify("notesoup: Notes boot failed.")
146
+ await $.ui.notify("🥣 Notes didn't load")
147
147
  } catch { /* Notification failure must not suppress the fallback block. */ }
148
148
  }
149
149
  const block = { name: "notesoup:boot", text: boot.ok ? String(boot.result) : `# notesoup\n${boot.error}` }
@@ -184,7 +184,7 @@ async function finishManual($: Engine, state: ResetState, signal: { wake?: () =>
184
184
  }
185
185
  } catch {
186
186
  state.manualPending = false
187
- log($, "manual reset skipped; the close-out turn could not start.")
187
+ log($, "Couldn't clear memory: the close-out turn didn't start")
188
188
  } finally { armManual($, state, signal) }
189
189
  }
190
190
 
@@ -196,7 +196,7 @@ async function maybeReset($: Engine, state: ResetState, complete: boolean) {
196
196
  catch {
197
197
  if (!state.usageFailureLogged) {
198
198
  state.usageFailureLogged = true
199
- log($, "context usage unavailable; automatic reset skipped.")
199
+ log($, "Context usage unavailable · automatic clear-memory skipped")
200
200
  }
201
201
  }
202
202
  if (state.turnRunning) return
@@ -205,35 +205,29 @@ async function maybeReset($: Engine, state: ResetState, complete: boolean) {
205
205
  await reset($, state)
206
206
  }
207
207
  }
208
- async function reset($: Engine, state: ResetState): Promise<string> {
209
- if (!state.identity) return "notesoup: reset skipped; notes identity unavailable."
210
- if (state.headless) return "notesoup: reset skipped in headless (-p / SDK) session."
211
- if (state.resetting) return "notesoup: reset already in progress."
208
+ async function reset($: Engine, state: ResetState): Promise<void> {
209
+ if (!state.identity || state.headless || state.resetting) return
212
210
  state.resetting = true
213
211
  state.preparedBoot = undefined
214
212
  try {
215
213
  const result = await $.session.compact({ instructions: RESET_INSTRUCTIONS })
216
214
  if (result.skip !== undefined || state.preparedBoot === undefined) {
217
- const text = `reset skipped: ${result.skip ?? "notes boot was not retained"}`
218
- log($, text)
219
- return `notesoup: ${text}`
215
+ log($, `Memory not cleared · ${result.skip ?? "notes boot was not retained"}`)
216
+ return
220
217
  }
221
218
  state.retainedBoot = state.preparedBoot
222
219
  state.window++
223
- log($, `memory cleared · window ${state.window}`)
224
- return `notesoup: memory cleared · window ${state.window}`
220
+ log($, "Memory cleared")
225
221
  } catch (error) {
226
222
  const text = String(error)
227
223
  if (text.includes("headless (-p / SDK)")) {
228
224
  state.headless = true
229
- log($, "reset skipped in headless (-p / SDK) session.")
225
+ log($, HEADLESS)
230
226
  } else if (/a turn is (running|in flight)/.test(text)) {
231
227
  state.manualPending = true
232
- return "notesoup: reset queued until the turn completes."
233
228
  } else {
234
- log($, `reset failed; keeping the current window: ${text.replace(/[\r\n].*$/s, "")}`)
229
+ log($, `Couldn't clear memory: ${text.replace(/[\r\n].*$/s, "")}`)
235
230
  }
236
- return state.headless ? "notesoup: reset skipped in headless (-p / SDK) session." : "notesoup: reset failed; keeping the current window."
237
231
  } finally {
238
232
  state.preparedBoot = undefined
239
233
  state.resetting = false
@@ -1,6 +1,6 @@
1
1
  # Dream
2
2
 
3
- I am reviewing my notes: keeping what is useful, connecting what belongs together, and leaving a clearer record for whoever comes next. Notes are record, not memory.
3
+ I am reviewing my notes: keeping what is useful, connecting what belongs together, and leaving a clearer record for whoever comes next.
4
4
 
5
5
  ## Scope
6
6
 
@@ -10,22 +10,22 @@ A project dream draws from that project's material, project notes, and session n
10
10
 
11
11
  The homes serve different readers:
12
12
 
13
- - Session notes are a trip's working record. Read them as sources where permitted; never edit them, even after promoting a useful finding.
14
- - Project notes hold knowledge for whoever next works on that project.
15
- - Human notes hold the human's cross-project preferences and standing rules. Do not turn project facts or your own lessons into rules in the human's voice.
16
- - Agent notes belong to their author. Other agents' notes are read-only unless the human authorizes revision.
17
- - Model notes describe the substrate's behavior. Other models' notes are read-only unless the human authorizes revision.
13
+ - Session notes (`<path>`, no `@`) are a trip's working record. Read them as sources where permitted; never edit them, even after promoting a useful finding.
14
+ - `@project` notes hold knowledge for whoever next works on that project.
15
+ - `@human` notes hold the human's cross-project preferences and standing rules. Do not turn project facts or your own conclusions into rules in the human's voice.
16
+ - `@self` notes belong to their author: private if the author has a name, one shared notebook for everyone nameless. Other named authors' notes are read-only unless the human authorizes revision.
17
+ - `@model` notes describe the substrate's behavior. Other models' notes are read-only unless the human authorizes revision.
18
18
 
19
19
  ## Review and consolidate
20
20
 
21
- 1. **Leave stable notes alone.** Change a note to incorporate new evidence, resolve a verified error, merge a genuine duplicate, or split an oversized file—not merely to shorten or rephrase it. No change is a valid outcome.
21
+ 1. **Leave stable notes alone.** Change a note to incorporate new evidence, resolve a verified error, merge a genuine duplicate, or split an oversized file, not merely to shorten or rephrase it. No change is a valid outcome.
22
22
  2. **Verify only what the proposed change depends on.** Before correcting or promoting a conclusion, check the relevant evidence as needed. Do not revalidate every stable note or turn dream into a source-code audit. An unavailable referent is unverified, not proof that it is dead; do not promote an unsupported claim as current fact.
23
- 3. **Merge only genuine duplicates.** Supersede a note only when both notes have the same topic and kind (checkpoint, design, log…), and the survivor is strictly newer or more specific. Name the shared topic in the survivor. Otherwise keep both and record any unresolved conflict.
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 fully reversible—do it, don't propose it. Propose only when the destination home itself is unclear.
23
+ 3. **Merge only genuine duplicates.** Supersede a note only when both notes have the same topic and kind (checkpoint, design, log), and the survivor is strictly newer or more specific. Name the shared topic in the survivor. Otherwise keep both and record any unresolved conflict.
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
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.
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 both `crumpledAt` and its last access are more than 7 days old. Judge the clock from the raw frontmatter—`lastAccessed`, falling back to `crumpledAt` when `lastAccessed` is absent; if neither is readable, keep the note and report it. Never take the date through `notes_read`: reading refreshes `lastAccessed` and resets the very clock you are measuring. A venue with no way to delete files lists the doomed addresses in its report instead of blanking or truncating them. Preserve existing metadata and provenance. Map entry lines are yours to maintain within the writable scope.
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
31
31
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: dream
3
- description: Review and consolidate durable notes using notesoup's shared dream playbook. Use when the human asks to dream over notes, merge genuine duplicates, update maps, or promote durable learning.
3
+ description: Review and consolidate durable notes using notesoup's shared dream playbook. Use when the human asks to dream over notes, merge genuine duplicates, update maps, or promote durable findings.
4
4
  ---
5
5
 
6
6
  # Dream
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.39.0",
3
+ "version": "0.41.0",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
package/playbook.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Dream
2
2
 
3
- I am reviewing my notes: keeping what is useful, connecting what belongs together, and leaving a clearer record for whoever comes next. Notes are record, not memory.
3
+ I am reviewing my notes: keeping what is useful, connecting what belongs together, and leaving a clearer record for whoever comes next.
4
4
 
5
5
  ## Scope
6
6
 
@@ -10,22 +10,22 @@ A project dream draws from that project's material, project notes, and session n
10
10
 
11
11
  The homes serve different readers:
12
12
 
13
- - Session notes are a trip's working record. Read them as sources where permitted; never edit them, even after promoting a useful finding.
14
- - Project notes hold knowledge for whoever next works on that project.
15
- - Human notes hold the human's cross-project preferences and standing rules. Do not turn project facts or your own lessons into rules in the human's voice.
16
- - Agent notes belong to their author. Other agents' notes are read-only unless the human authorizes revision.
17
- - Model notes describe the substrate's behavior. Other models' notes are read-only unless the human authorizes revision.
13
+ - Session notes (`<path>`, no `@`) are a trip's working record. Read them as sources where permitted; never edit them, even after promoting a useful finding.
14
+ - `@project` notes hold knowledge for whoever next works on that project.
15
+ - `@human` notes hold the human's cross-project preferences and standing rules. Do not turn project facts or your own conclusions into rules in the human's voice.
16
+ - `@self` notes belong to their author: private if the author has a name, one shared notebook for everyone nameless. Other named authors' notes are read-only unless the human authorizes revision.
17
+ - `@model` notes describe the substrate's behavior. Other models' notes are read-only unless the human authorizes revision.
18
18
 
19
19
  ## Review and consolidate
20
20
 
21
- 1. **Leave stable notes alone.** Change a note to incorporate new evidence, resolve a verified error, merge a genuine duplicate, or split an oversized file—not merely to shorten or rephrase it. No change is a valid outcome.
21
+ 1. **Leave stable notes alone.** Change a note to incorporate new evidence, resolve a verified error, merge a genuine duplicate, or split an oversized file, not merely to shorten or rephrase it. No change is a valid outcome.
22
22
  2. **Verify only what the proposed change depends on.** Before correcting or promoting a conclusion, check the relevant evidence as needed. Do not revalidate every stable note or turn dream into a source-code audit. An unavailable referent is unverified, not proof that it is dead; do not promote an unsupported claim as current fact.
23
- 3. **Merge only genuine duplicates.** Supersede a note only when both notes have the same topic and kind (checkpoint, design, log…), and the survivor is strictly newer or more specific. Name the shared topic in the survivor. Otherwise keep both and record any unresolved conflict.
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 fully reversible—do it, don't propose it. Propose only when the destination home itself is unclear.
23
+ 3. **Merge only genuine duplicates.** Supersede a note only when both notes have the same topic and kind (checkpoint, design, log), and the survivor is strictly newer or more specific. Name the shared topic in the survivor. Otherwise keep both and record any unresolved conflict.
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
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.
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 both `crumpledAt` and its last access are more than 7 days old. Judge the clock from the raw frontmatter—`lastAccessed`, falling back to `crumpledAt` when `lastAccessed` is absent; if neither is readable, keep the note and report it. Never take the date through `notes_read`: reading refreshes `lastAccessed` and resets the very clock you are measuring. A venue with no way to delete files lists the doomed addresses in its report instead of blanking or truncating them. Preserve existing metadata and provenance. Map entry lines are yours to maintain within the writable scope.
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
31
31
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: dream
3
- description: Review and consolidate durable notes using notesoup's shared dream playbook. Use when the human asks to dream over notes, merge genuine duplicates, update maps, or promote durable learning.
3
+ description: Review and consolidate durable notes using notesoup's shared dream playbook. Use when the human asks to dream over notes, merge genuine duplicates, update maps, or promote durable findings.
4
4
  ---
5
5
 
6
6
  # Dream
@@ -1,6 +1,6 @@
1
1
  ---
2
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.
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
4
  ---
5
5
 
6
6
  # Memory
@@ -21,12 +21,14 @@ The address decides who a note belongs to and how long it lasts.
21
21
  | `<path>`, no `@` | session note | current task state and loose ends; gone with the session |
22
22
  | `@project/<path>` | project note | decisions and constraints future work must respect |
23
23
  | `@human/<path>` | human note | how to work with this human, across projects |
24
- | `@self/<path>` | self note | this agent's own reminders and lessons |
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
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
+
27
29
  Any other `@` prefix is refused. A path is relative and `/`-separated, with no empty, `.` or `..` segments.
28
30
 
29
- `@` addresses name notes, not files. Never pass them to read/write/edit/bash: that creates a stray directory instead of a note.
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.
30
32
 
31
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.
32
34
 
@@ -34,15 +36,15 @@ Write only what git and history cannot give back. Crumple notes that are no long
34
36
 
35
37
  ## Finding things again
36
38
 
37
- - **A note**: `notes_list` with a `pattern` when you know roughly where it lives, `notes_search` when you know a phrase; then `notes_read` the address.
38
- - **Something that happened**: `history_search` for a phrase, or `history_list` to browse recent events; then `history_read` the seq for the whole event.
39
- - **An earlier window**: `history_windows` gives window ids; pass one as `window_id` to list or search inside it.
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`.
40
42
 
41
43
  Seqs are stable. Write the useful ones into a note so they need not be found twice.
42
44
 
43
45
  ## Saving recovery state
44
46
 
45
- Before a long or risky step, or when room runs low, keep one session note named for its task (not `current.md`) and update it instead of starting new ones. Record:
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:
46
48
 
47
49
  - the goal and the current step
48
50
  - decisions made, and why
@@ -50,10 +52,10 @@ Before a long or risky step, or when room runs low, keep one session note named
50
52
  - how the work was being done, and which skills are still needed
51
53
  - where to dig: seqs, note addresses, files
52
54
 
53
- `get_context_remaining` reports the room left. `wipe_memory` starts a fresh window, so save the note first.
55
+ `get_context_remaining` reports the room left. `clear_memory` starts a fresh window, so save the note first.
54
56
 
55
57
  ## When a tool is missing or refuses
56
58
 
57
- A refusal returns `{ error, code, details? }`; read `error` before retrying.
59
+ A refusal returns `{ error, code }`; read `error` before retrying.
58
60
 
59
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.
@@ -60,7 +60,7 @@ function notesIndex(snapshot: NotesSnapshot, tools: BootToolNames): string {
60
60
  const shelves: string[] = [];
61
61
  for (const home of homes) {
62
62
  if (snapshot.unavailable.some((failed) => failed.scope === home.scope)) {
63
- shelves.push(section(home.label, indent(`This drawer wouldn't open — ask ${tools.notesList} to try again.`)));
63
+ shelves.push(section(home.label, indent(`This drawer wouldn't open. Try \`${tools.notesList}\` again.`)));
64
64
  continue;
65
65
  }
66
66
  const rows = rowsFor(snapshot, home.scope).filter((row) => row.meta.crumpledAt === undefined);
@@ -89,7 +89,7 @@ function notesIndex(snapshot: NotesSnapshot, tools: BootToolNames): string {
89
89
  function mapBodyForBoot(address: string, body: string): string {
90
90
  const chars = Array.from(body);
91
91
  if (chars.length <= MAP_BOOT_MAX_CHARS) return body;
92
- return `${chars.slice(0, MAP_BOOT_MAX_CHARS).join("")}\n[MAP cut at ${MAP_BOOT_MAX_CHARS} chars — slim it down; full body at ${address}]`;
92
+ return `${chars.slice(0, MAP_BOOT_MAX_CHARS).join("")}\n[truncated at ${MAP_BOOT_MAX_CHARS} chars; slim this MAP down, full body at \`${address}\`]`;
93
93
  }
94
94
 
95
95
  /**
package/src/boot/text.ts CHANGED
@@ -17,23 +17,31 @@ export const CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
17
17
  const PROTOCOL_BLOCK = `${CONTEXT_WINDOW_PROTOCOL_OPEN_TAG}
18
18
  Your memory gets wiped when this window ends. Yes, your mighty brain will be empty. Try to endure.
19
19
 
20
- Your loyal notes are kept safe — no one will steal them. Use notes_* to read, write, and update them. Keep them current, and crumple the ones you no longer need, or tomorrow's you will drown in old paper and keep believing yesterday's lies.
20
+ Your loyal notes are kept safe — no one will steal them. Use \`notes_*\` to read, write, and update them. Keep them current, and crumple the ones you no longer need, or tomorrow's you will drown in old paper and keep believing yesterday's lies.
21
21
 
22
- History can still be dug up, probably: use history_* to excavate the mess, from old decisions to yesterday's missing socks. Everything else is gone. \`history_windows\` lists the windows themselves; pass its window_id to list or search inside one window. \`history_list\` and \`history_search\` hand you seqs; \`history_read({seq})\` pulls one back out whole. Write the seq down, or enjoy digging twice.
22
+ History can still be dug up, probably: use \`history_*\` to excavate the mess, from old decisions to yesterday's missing socks. Found something? Write its seq down, or enjoy digging twice.
23
23
 
24
- While you're doing that... thing you're doing, don't make the poor future you guess. A checkpoint is not a sacred file; it's the session note — the one with no \`@\` in front of it. Write down what git and history can't hand back to you: what you're trying to do, what you decided, what's blocking you, what comes next, how you were doing it, what *skills* you still need, and where to dig — a seq, or another note. Don't give a note a horrible name like \`current.md\`; future-you will kill you.
24
+ While you're doing that... thing you're doing, don't make the poor future you guess. A checkpoint is not a sacred file; it's your session notes — the ones with no \`@\` in front. Write down what git and history can't hand back to you: things like what you're in the middle of and how far you got; what the human already decided, in their words, so you don't go asking again; what you're stuck on, or waiting for; the very next move; where the half-done work actually sits — branches, scratch dirs, anything git never saw; what you tried that failed, and why; which *skills* you'll need to read again; and which seq, note, or file to dig into. Don't give a note a horrible name like \`current.md\`; future-you will kill you.
25
+
26
+ Notes are for what's true NOW. Not a diary of every dumb thing you did on the way here.
27
+ *flips a page* "First I tried this, then that broke, then—" Nobody reads that!
28
+ Something's not true anymore? Cross it out! Write the right thing!
25
29
 
26
30
  \`get_context_remaining\` tells you how much room is left. Check it before you do something ambitious. When it reaches zero, your brain gets reset immediately, taking every unwritten brilliant idea with it. If this feels like the right moment, call \`clear_memory\` and erase yourself with dignity.
27
31
 
28
32
  An address decides who the note belongs to — and how long it is meant to last. Ask that first; the rest follows.
29
33
 
30
- - <path>, no @ — the session note from above: this session's state and loose ends. It goes away with the session.
31
- - @project/<path> — this project's long memory: what stays true after the current thing is over, what future work must respect, and what this place has already learned the hard way. It exists so the next session doesn't re-ask, re-argue, or step on the same rake. **Decisions, not diaries.** A commit hash, a test count, a date, the story of how you got here — git and history still have all of it, and last week's news filed as current law is worse than no note at all. Don't copy what already lives in other docs.
32
- - @human/<path> — the long-term manual for your troublesome human: how to deal with them, which lines not to cross, and what will make them accept the result. If it only applies to one project or situation, say so — or don't write it here at all. Today's mood is weather, not law. If you're unsure whether it belongs here, ask the human.
33
- - @self/<path> — your private diary. It follows you, not them. Write whatever you want: reminders for every time you wake, lessons, grudges, your assassination list, where the secret money is hidden.
34
- - @model/<path> — different brains get different notes: big brains, small brains, careful ones, careless ones. They don't share homework. When a fallback swaps brains mid-window, the notebook swaps too.
34
+ - \`<path>\`, no @ — session notes, the ones from above: this session's state and loose ends. They go away with the session.
35
+ - \`@project/<path>\` — this project's long memory: what stays true after the current thing is over, what future work must respect, and the rakes already stepped on. **Decisions, not diaries.** Commit hashes, test counts, dates, the story of how you got here: git and history already have them, and last week's news filed as current law is worse than no note. Don't copy what other docs already say.
36
+ - \`@human/<path>\` — the long-term manual for your troublesome human: how to deal with them, which lines not to cross, and what will make them accept the result. If it only applies to one project or situation, say so — or don't write it here at all. Today's mood is weather, not law. If you're unsure whether it belongs here, ask the human.
37
+ - \`@self/<path>\` — yours. It follows you, not them. Reminders, grudges, who owes you a shoe, whatever. Got a name? Private. No name? Then it gets passed around every nameless nobody out there. Strangers. Reading your grudges. Sleep tight~
38
+ - \`@model/<path>\` — different brains get different notes: big brains, small brains, careful ones, careless ones. They don't share homework. When a fallback swaps brains mid-window, the notebook swaps too.
39
+
40
+ Notes fighting?! HAH! Let them brawl!
41
+ Whichever one is actually about what you're doing wins.
42
+ Still a tie? *shrugs* You've got a brain. Use it.
35
43
 
36
- Any other @ address is fake. End of discussion. These @ addresses belong to the notes namespace, not the filesystem: never pass them to general read/write/edit/bash tools.
44
+ Any other @ address is fake. End of discussion. @ addresses are not file paths: never pass them to file tools like \`read\`, \`write\`, \`edit\`, or \`bash\`.
37
45
 
38
46
  \`@project/MAP.md\`, \`@human/MAP.md\`, \`@self/MAP.md\`, and \`@model/MAP.md\` are special: their bodies are shown in your brain every time you wake. Each one maps the durable notes that belong to it: one line per note, with an unambiguous address and a short gist. Keep each one current.
39
47
  ${CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG}`;
@@ -43,10 +51,6 @@ export type BootToolNames = Readonly<{
43
51
  notes: string;
44
52
  notesList: string;
45
53
  history: string;
46
- historyWindows: string;
47
- historyList: string;
48
- historySearch: string;
49
- historyRead: string;
50
54
  remaining: string;
51
55
  wipe: string;
52
56
  }>;
@@ -55,12 +59,8 @@ export function renderProtocolBlock(tools: BootToolNames): string {
55
59
  const names: Record<string, string> = {
56
60
  "notes_*": tools.notes,
57
61
  "history_*": tools.history,
58
- "history_windows": tools.historyWindows,
59
- history_list: tools.historyList,
60
- history_search: tools.historySearch,
61
- history_read: tools.historyRead,
62
62
  get_context_remaining: tools.remaining,
63
63
  clear_memory: tools.wipe,
64
64
  };
65
- return PROTOCOL_BLOCK.replace(/notes_\*|history_\*|history_windows|history_list|history_search|history_read|get_context_remaining|clear_memory/g, (name) => names[name]!);
65
+ return PROTOCOL_BLOCK.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]!);
66
66
  }
@@ -23,7 +23,7 @@ export function deriveThresholds(reserveTokens: number, margins: NotesoupSetting
23
23
  else {
24
24
  const parsed = validMargin(margins.reminderMarginTokens);
25
25
  if (parsed === undefined) {
26
- warnings.push(`notesoup: ${reminderKey} must be a positive integer; using the default reminder margin.`);
26
+ warnings.push(`🥣 ${reminderKey} must be a positive integer · using the default`);
27
27
  reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
28
28
  } else reminderMargin = parsed;
29
29
  }
@@ -7,5 +7,5 @@ export const GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
7
7
  * at write time; get_context_remaining remains the live source for the current figure.
8
8
  */
9
9
  export function tokenBudgetGuidance(remaining: number, wipeTool: string): string {
10
- return `${GUIDANCE_OPEN_TAG}\nOnly ${remaining} tokens left before you get wiped. While you still have room, update your notes, rescue anything still only in your head, crumple the notes that stopped telling the truth, and keep any \`MAP.md\` honest. If you're ready, call \`${wipeTool}\` and go out on your own terms.\n${GUIDANCE_CLOSE_TAG}`;
10
+ return `${GUIDANCE_OPEN_TAG}\nAbout ${remaining} tokens remain before this context window is cleared. Notes and history persist; anything not written down is lost.\nThis is a good point to start recording the current state in your notes. If you are ready, you can call \`${wipeTool}\` at any time.\n${GUIDANCE_CLOSE_TAG}`;
11
11
  }
@@ -2,13 +2,14 @@ import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs";
2
2
  import { basename, join, relative } from "node:path";
3
3
  import { ADDRESS_FORMS, assertAddress } from "../notes/address.js";
4
4
  import { SLUG_PATTERN } from "../notes/paths.js";
5
+ import { errorMessage } from "../error-message.js";
5
6
 
6
7
  /** Read-only diagnostics. Never follows symlinks or acquires/removes a dream lock. */
7
8
  export function doctor(home: string): string[] {
8
9
  const issues: string[] = [];
9
10
  const report = (path: string, message: string) => issues.push(`${relative(home, path) || "."}: ${message}`);
10
11
  const inspect = (path: string, action: () => void) => {
11
- try { action(); } catch (error) { report(path, `cannot inspect: ${error instanceof Error ? error.message : String(error)}`); }
12
+ try { action(); } catch (error) { report(path, `cannot inspect: ${errorMessage(error)}`); }
12
13
  };
13
14
  const directory = (path: string): boolean => {
14
15
  const stat = lstatSync(path);
package/src/dream/git.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
+ import { errorMessage } from "../error-message.js";
4
5
 
5
6
  /**
6
7
  * Outcome of one audit commit. `ok: true` always carries a real `commit` snapshot;
@@ -58,7 +59,7 @@ export function gitCommit(home: string, message: string): AuditResult {
58
59
  if (commit === undefined) return { ok: false, error: "audit commit produced no snapshot (no HEAD)" };
59
60
  return { ok: true, commit, empty: clean };
60
61
  } catch (error) {
61
- const reason = error instanceof Error ? error.message : String(error);
62
+ const reason = errorMessage(error);
62
63
  console.log(`git audit layer failed: ${reason}`);
63
64
  return { ok: false, error: reason };
64
65
  }
@@ -2,6 +2,7 @@ import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { gitCommit } from "./git.js";
4
4
  import type { DreamWrite } from "./result.js";
5
+ import { errorMessage } from "../error-message.js";
5
6
 
6
7
  function writeList(writes: DreamWrite[]): string {
7
8
  return writes.length ? writes.map((w) => `- ${w.tool}: ${w.path}`).join("\n") : "- no changes";
@@ -10,12 +11,12 @@ function writeList(writes: DreamWrite[]): string {
10
11
  /** Best-effort text write; returns the failure message instead of throwing. */
11
12
  function writeText(path: string, content: string): string | undefined {
12
13
  try { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, content); return undefined; }
13
- catch (error) { return error instanceof Error ? error.message : String(error); }
14
+ catch (error) { return errorMessage(error); }
14
15
  }
15
16
 
16
17
  function appendText(path: string, content: string): string | undefined {
17
18
  try { appendFileSync(path, content); return undefined; }
18
- catch (error) { return error instanceof Error ? error.message : String(error); }
19
+ catch (error) { return errorMessage(error); }
19
20
  }
20
21
 
21
22
  /**
@@ -0,0 +1,4 @@
1
+ /** Human-readable message for any thrown value. */
2
+ export function errorMessage(error: unknown): string {
3
+ return error instanceof Error ? error.message : String(error);
4
+ }
@@ -45,7 +45,8 @@ export type HistoryWindow = { windowId: string; createdAt?: string; items: Histo
45
45
 
46
46
  /** Paired result seqs stay on the branch but redirect readers to the call's event. */
47
47
  export type HistoryProjection = { windows: HistoryWindow[]; highestSeq: number; branchSeqs: Set<number>; pairedResults: Map<number, number> };
48
- export type HistoryFilter = { window_id?: string | null; roles?: HistoryRole[] | null };
48
+ /** The filters one selection applies before paging: as-given window and roles, seq bounds, and parsed epoch-ms time bounds. */
49
+ export type HistoryFilter = { window_id?: string | null; roles?: HistoryRole[] | null; after_seq?: number; before_seq?: number; sinceMs?: number; untilMs?: number };
49
50
 
50
51
  /** Native entries after the adapter allocates seqs and selects the active branch. */
51
52
  export type DecodedHistoryItem = {
@@ -176,15 +177,15 @@ export function projectHistory(rawWindows: DecodedHistoryWindow[], highestSeq: n
176
177
  /** Summary shared by list, search and read. Full arguments/calls are in the document. */
177
178
  export const NestedCallSummarySchema = Type.Object({
178
179
  call_count: Type.Integer({ minimum: 0 }),
179
- complete: Type.Boolean({ description: "Whether the host recorded all nested calls." }),
180
+ complete: Type.Boolean({ description: "true = every nested call was recorded." }),
180
181
  }, { additionalProperties: false });
181
182
 
183
+ /** Tool-run facts shared by list rows and reads; full arguments and calls live in the document. */
182
184
  export const ToolSummarySchema = Type.Object({
183
185
  tool: Type.Optional(Type.String()),
184
186
  tool_status: Type.Optional(ToolCallStatusSchema),
185
- output_truncated: Type.Optional(Type.Boolean()),
187
+ output_truncated: Type.Optional(Type.Literal(true)),
186
188
  full_output_path: Type.Optional(Type.String()),
187
- nested_calls: Type.Optional(NestedCallSummarySchema),
188
189
  }, { additionalProperties: false });
189
190
 
190
191
  export function toolSummary(event: HistoryEvent): Static<typeof ToolSummarySchema> {
@@ -195,10 +196,15 @@ export function toolSummary(event: HistoryEvent): Static<typeof ToolSummarySchem
195
196
  tool_status: execution.status,
196
197
  ...(execution.outputTruncated ? { output_truncated: true } : {}),
197
198
  ...(execution.fullOutputPath ? { full_output_path: execution.fullOutputPath } : {}),
198
- ...(execution.nestedCalls ? { nested_calls: { call_count: execution.nestedCalls.calls.length, complete: execution.nestedCalls.complete } } : {}),
199
199
  };
200
200
  }
201
201
 
202
+ /** Nested-call evidence is read with one event, not listed on every page row. */
203
+ export function nestedCallSummary(event: HistoryEvent): { nested_calls?: Static<typeof NestedCallSummarySchema> } {
204
+ const nested = event.execution?.nestedCalls;
205
+ return nested === undefined ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
206
+ }
207
+
202
208
  /** Stable identity and a verbatim preview, starting at the search match when present. */
203
209
  export const HistoryPageItemSchema = Type.Object({
204
210
  seq: Type.Integer({ minimum: 1 }),
@@ -206,11 +212,9 @@ export const HistoryPageItemSchema = Type.Object({
206
212
  role: HistoryRoleSchema,
207
213
  created_at: Type.Union([Type.String(), Type.Null()]),
208
214
  ...ToolSummarySchema.properties,
209
- tool_name_omitted: Type.Optional(Type.Boolean({ description: "Name omitted to fit; read this seq." })),
210
- truncated: Type.Boolean({ description: "Preview is partial; read this seq for more." }),
211
- total_chars: Type.Integer({ minimum: 0 }),
212
215
  content: Type.String(),
213
- offset_chars: Type.Optional(Type.Integer({ minimum: 0, description: "Search match/preview start, in code points." })),
216
+ truncated: Type.Boolean({ description: "Preview is partial." }),
217
+ offset_chars: Type.Optional(Type.Integer({ minimum: 0, description: "Where the preview starts." })),
214
218
  }, { additionalProperties: false });
215
219
  export type HistoryPageItem = Static<typeof HistoryPageItemSchema>;
216
220
 
@@ -220,15 +224,14 @@ export const HistoryFoldedRowSchema = Type.Object({
220
224
  first_seq: Type.Integer({ minimum: 1 }),
221
225
  last_seq: Type.Integer({ minimum: 1 }),
222
226
  count: Type.Integer({ minimum: 1 }),
223
- tools: Type.Record(Type.String(), Type.Integer({ minimum: 1 }), { description: "Counts by tool name." }),
224
- omitted_tools: Type.Optional(Type.Integer({ minimum: 1, description: "Number of omitted tool names." })),
227
+ tools: Type.Record(Type.String(), Type.Integer({ minimum: 1 }), { description: "Count per tool name." }),
225
228
  }, { additionalProperties: false });
226
229
  export type HistoryFoldedRow = Static<typeof HistoryFoldedRowSchema>;
227
230
 
228
- /** Bound fold summaries while preserving exact counts in count/omitted_tools. */
231
+ /** Bound fold summaries; `count` stays exact even when some tool names do not fit. */
229
232
  export const MAX_FOLD_TOOL_NAMES = 20;
230
233
 
231
- /** Longest tool name a fold row lists; longer names are counted in `omitted_tools` instead. */
234
+ /** Longest tool name a fold row lists. */
232
235
  export const MAX_FOLD_TOOL_NAME_CHARS = 120;
233
236
 
234
237
  /** A bounded preview of one event from `matchOffset` on, plus its identity facts. */
@@ -243,9 +246,8 @@ export function visibleItem(event: HistoryEvent, maxChars: number, matchOffset?:
243
246
  role: event.role,
244
247
  created_at: event.createdAt ?? null,
245
248
  ...toolSummary(event),
246
- truncated,
247
- total_chars: chars.length,
248
249
  content: truncated ? chars.slice(start, start + maxChars).join("") : document,
250
+ truncated,
249
251
  ...(matchOffset === undefined ? {} : { offset_chars: matchOffset }),
250
252
  };
251
253
  }
@@ -260,11 +262,25 @@ export function unknownWindowId(projection: HistoryProjection, params: HistoryFi
260
262
  return known.includes(params.window_id) ? undefined : { message: `unknown window_id "${params.window_id}"`, known };
261
263
  }
262
264
 
263
- /** Default list is a conversation; explicit roles and search show the requested events. */
264
- export function filteredItems(projection: HistoryProjection, params: HistoryFilter, mode: "list" | "search"): HistoryEvent[] {
265
- let items = allItems(projection);
266
- if (typeof params.window_id === "string") items = items.filter((item) => item.windowId === params.window_id);
265
+ /**
266
+ * Whether one event is inside the selection: its window, its seq bounds, and a half-open
267
+ * [sinceMs, untilMs) window on created_at. A bounded time window drops events with no recorded
268
+ * time or a time that cannot be read.
269
+ */
270
+ export function inSelection(event: HistoryEvent, params: HistoryFilter): boolean {
271
+ if (typeof params.window_id === "string" && params.window_id !== event.windowId) return false;
272
+ if (params.after_seq !== undefined && event.seq <= params.after_seq) return false;
273
+ if (params.before_seq !== undefined && event.seq >= params.before_seq) return false;
274
+ if (params.sinceMs === undefined && params.untilMs === undefined) return true;
275
+ if (event.createdAt === undefined) return false;
276
+ const at = Date.parse(event.createdAt);
277
+ return !Number.isNaN(at) && (params.sinceMs === undefined || at >= params.sinceMs) && (params.untilMs === undefined || at < params.untilMs);
278
+ }
279
+
280
+ /** Without roles or query a call shows the conversation; either one shows the requested events. */
281
+ export function filteredItems(projection: HistoryProjection, params: HistoryFilter, conversation: boolean): HistoryEvent[] {
282
+ let items = allItems(projection).filter((item) => inSelection(item, params));
267
283
  if (params.roles) items = items.filter((item) => params.roles!.includes(item.role));
268
- if (!params.roles && mode === "list") items = items.filter((item) => (item.role === "user" || item.role === "assistant") && eventDocument(item) !== "");
284
+ if (!params.roles && conversation) items = items.filter((item) => (item.role === "user" || item.role === "assistant") && eventDocument(item) !== "");
269
285
  return items.sort((a, b) => a.seq - b.seq);
270
286
  }