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.
- package/README.md +5 -2
- package/dist/src/boot/render.js +2 -2
- package/dist/src/boot/text.d.ts +0 -4
- package/dist/src/boot/text.js +18 -14
- package/dist/src/budget/policy.js +1 -1
- package/dist/src/budget/text.js +1 -1
- package/dist/src/dream/doctor.js +2 -1
- package/dist/src/dream/git.js +2 -1
- package/dist/src/dream/report.js +3 -2
- package/dist/src/error-message.d.ts +2 -0
- package/dist/src/error-message.js +4 -0
- package/dist/src/history/history.d.ts +23 -18
- package/dist/src/history/history.js +37 -20
- package/dist/src/history/query.d.ts +37 -49
- package/dist/src/history/query.js +114 -56
- package/dist/src/notes/store.d.ts +3 -4
- package/dist/src/notes/store.js +12 -16
- package/dist/src/pi/anchored.d.ts +16 -0
- package/dist/src/pi/anchored.js +55 -0
- package/dist/src/pi/budget.d.ts +1 -1
- package/dist/src/pi/budget.js +33 -28
- package/dist/src/pi/dream/cli.js +3 -2
- package/dist/src/pi/dream/runner.js +2 -1
- package/dist/src/pi/history-tools.d.ts +1 -1
- package/dist/src/pi/history-tools.js +2 -3
- package/dist/src/pi/reset/lifecycle.d.ts +1 -1
- package/dist/src/pi/reset/lifecycle.js +4 -3
- package/dist/src/pi/reset/text.d.ts +3 -3
- package/dist/src/pi/reset/text.js +2 -2
- package/dist/src/pi/runtime.js +12 -15
- package/dist/src/pi/thresholds.js +2 -1
- package/dist/src/pi/tool-names.d.ts +0 -4
- package/dist/src/pi/tool-names.js +0 -4
- package/dist/src/tools/history.d.ts +24 -33
- package/dist/src/tools/history.js +57 -98
- package/dist/src/tools/notes.d.ts +26 -58
- package/dist/src/tools/notes.js +85 -103
- package/dist/src/tools/result.d.ts +16 -13
- package/dist/src/tools/result.js +24 -50
- package/dist/src/tools/schema.d.ts +2 -2
- package/dist/src/tools/schema.js +3 -3
- package/dist/test/agent-loop.test.js +79 -29
- package/dist/test/boot.integration.test.js +6 -6
- package/dist/test/budget-settings.integration.test.js +9 -8
- package/dist/test/claude-mod.test.js +11 -11
- package/dist/test/dependencies.test.js +1 -1
- package/dist/test/helpers/extension.js +2 -3
- package/dist/test/history.integration.test.js +200 -123
- package/dist/test/host-neutral.test.js +32 -58
- package/dist/test/notes-library.test.js +8 -8
- package/dist/test/notes.integration.test.js +75 -57
- package/dist/test/notes.test.js +44 -42
- package/dist/test/reset-lifecycle.test.js +2 -2
- package/docs/architecture.md +3 -3
- package/docs/notes-library.md +6 -6
- package/docs/tool-results.md +15 -25
- package/mods/notesoup/.claude-plugin/plugin.json +1 -1
- package/mods/notesoup/dist/claude/helper.js +128 -179
- package/mods/notesoup/hooks/register.ts +19 -25
- package/mods/notesoup/playbook.md +10 -10
- package/mods/notesoup/skills/dream/SKILL.md +1 -1
- package/package.json +1 -1
- package/playbook.md +10 -10
- package/skills/dream/SKILL.md +1 -1
- package/skills/memory/SKILL.md +11 -9
- package/src/boot/render.ts +2 -2
- package/src/boot/text.ts +18 -18
- package/src/budget/policy.ts +1 -1
- package/src/budget/text.ts +1 -1
- package/src/dream/doctor.ts +2 -1
- package/src/dream/git.ts +2 -1
- package/src/dream/report.ts +3 -2
- package/src/error-message.ts +4 -0
- package/src/history/history.ts +36 -20
- package/src/history/query.ts +130 -55
- package/src/notes/store.ts +15 -18
- package/src/pi/anchored.ts +62 -0
- package/src/pi/budget.ts +27 -26
- package/src/pi/dream/cli.ts +3 -2
- package/src/pi/dream/runner.ts +2 -1
- package/src/pi/history-tools.ts +2 -3
- package/src/pi/reset/lifecycle.ts +5 -4
- package/src/pi/reset/text.ts +2 -2
- package/src/pi/runtime.ts +12 -15
- package/src/pi/thresholds.ts +2 -1
- package/src/pi/tool-names.ts +0 -4
- package/src/tools/history.ts +61 -100
- package/src/tools/notes.ts +84 -97
- package/src/tools/result.ts +24 -49
- package/src/tools/schema.ts +3 -3
- 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)",
|
|
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(
|
|
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($,
|
|
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:
|
|
117
|
-
if (state.resetting || state.manualPending) return { text: "
|
|
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: "
|
|
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: "
|
|
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: `
|
|
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("
|
|
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($, "
|
|
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($, "
|
|
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<
|
|
209
|
-
if (!state.identity
|
|
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
|
-
|
|
218
|
-
|
|
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($,
|
|
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($,
|
|
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($, `
|
|
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.
|
|
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
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
-
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
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.
|
|
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
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
-
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
package/skills/dream/SKILL.md
CHANGED
|
@@ -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
|
|
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/skills/memory/SKILL.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: memory
|
|
3
|
-
description: How notesoup's notes_
|
|
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 |
|
|
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
|
|
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 `
|
|
38
|
-
- **Something that happened**: `
|
|
39
|
-
- **An earlier window**: `history_windows` gives window ids; pass one as `window_id` to
|
|
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
|
|
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. `
|
|
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
|
|
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.
|
package/src/boot/render.ts
CHANGED
|
@@ -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
|
|
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[
|
|
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_
|
|
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_
|
|
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
|
|
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
|
-
-
|
|
31
|
-
-
|
|
32
|
-
-
|
|
33
|
-
-
|
|
34
|
-
-
|
|
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.
|
|
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_\*|
|
|
65
|
+
return PROTOCOL_BLOCK.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]!);
|
|
66
66
|
}
|
package/src/budget/policy.ts
CHANGED
|
@@ -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(
|
|
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
|
}
|
package/src/budget/text.ts
CHANGED
|
@@ -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}\
|
|
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
|
}
|
package/src/dream/doctor.ts
CHANGED
|
@@ -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: ${
|
|
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 =
|
|
62
|
+
const reason = errorMessage(error);
|
|
62
63
|
console.log(`git audit layer failed: ${reason}`);
|
|
63
64
|
return { ok: false, error: reason };
|
|
64
65
|
}
|
package/src/dream/report.ts
CHANGED
|
@@ -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
|
|
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
|
|
19
|
+
catch (error) { return errorMessage(error); }
|
|
19
20
|
}
|
|
20
21
|
|
|
21
22
|
/**
|
package/src/history/history.ts
CHANGED
|
@@ -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
|
-
|
|
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: "
|
|
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.
|
|
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
|
-
|
|
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: "
|
|
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
|
|
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
|
|
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
|
-
/**
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
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 &&
|
|
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
|
}
|