notesoup 0.40.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/dist/src/boot/render.js +1 -1
- package/dist/src/boot/text.js +11 -3
- 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/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/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/test/agent-loop.test.js +78 -28
- package/dist/test/boot.integration.test.js +5 -5
- package/dist/test/budget-settings.integration.test.js +9 -8
- package/dist/test/claude-mod.test.js +7 -7
- package/dist/test/host-neutral.test.js +1 -1
- package/dist/test/notes.integration.test.js +1 -1
- package/dist/test/reset-lifecycle.test.js +2 -2
- package/mods/notesoup/.claude-plugin/plugin.json +1 -1
- package/mods/notesoup/dist/claude/helper.js +12 -4
- package/mods/notesoup/hooks/register.ts +18 -23
- 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 +5 -3
- package/src/boot/render.ts +1 -1
- package/src/boot/text.ts +11 -3
- 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/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/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/mods/pi-context/dist/claude/helper.js +0 -9324
|
@@ -14,6 +14,7 @@ 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`,
|
|
@@ -25,7 +26,7 @@ async function buildBoot($: Engine, identity: Identity, window: number) {
|
|
|
25
26
|
return run($, { op: "boot", identity, window, tools: BOOT_TOOLS }, identity.cwd)
|
|
26
27
|
}
|
|
27
28
|
function log($: Engine, text: string) {
|
|
28
|
-
try { $.ui.log(
|
|
29
|
+
try { $.ui.log(`🥣 ${text}`) } catch { /* UI must not break a turn or reset. */ }
|
|
29
30
|
}
|
|
30
31
|
|
|
31
32
|
function errorResult(message: string): ToolCallResult { return { result: `notesoup: ${message}`, isError: true } }
|
|
@@ -67,7 +68,7 @@ export function register(on: On) {
|
|
|
67
68
|
state.window = 0
|
|
68
69
|
state.turnRunning = state.resetting = state.manualPending = state.usageFailureLogged = false
|
|
69
70
|
state.headless = !e.isInteractive
|
|
70
|
-
if (state.headless) log($,
|
|
71
|
+
if (state.headless) log($, HEADLESS)
|
|
71
72
|
state.preparedBoot = state.retainedBoot = undefined
|
|
72
73
|
// The engine's history view includes retained boots on resume/reload.
|
|
73
74
|
// Recover their ordinal without treating that view as inference context.
|
|
@@ -112,23 +113,23 @@ export function register(on: On) {
|
|
|
112
113
|
})
|
|
113
114
|
on("command.run", async ($, e, next) => {
|
|
114
115
|
if (e.command !== "clear-memory") return next(e)
|
|
115
|
-
if (state.headless) return { text:
|
|
116
|
-
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" }
|
|
117
118
|
if (state.turnRunning) {
|
|
118
119
|
state.manualPending = true
|
|
119
|
-
return { text: "
|
|
120
|
+
return { text: "🥣 Clear-memory queued · runs after this turn" }
|
|
120
121
|
}
|
|
121
122
|
// command.run holds a turn even when idle. Start one hidden close-out
|
|
122
123
|
// turn after it returns; turn.complete is the verified self-hook path.
|
|
123
124
|
state.manualPending = true
|
|
124
125
|
manualSignal.wake?.()
|
|
125
|
-
return { text: "
|
|
126
|
+
return { text: "🥣 Clearing memory · notes first, then it stops" }
|
|
126
127
|
})
|
|
127
128
|
on("session.compact", async ($, e, next) => {
|
|
128
129
|
// Do not take over native /compact or another plugin's compaction.
|
|
129
130
|
if (!state.resetting || e.trigger !== "plugin" || e.agentId !== undefined || !identity) return next(e)
|
|
130
131
|
const boot = await buildBoot($, identity, state.window + 1)
|
|
131
|
-
if (!boot.ok) return { skip: `
|
|
132
|
+
if (!boot.ok) return { skip: `notes didn't load: ${boot.error}` }
|
|
132
133
|
state.preparedBoot = String(boot.result)
|
|
133
134
|
return { messages: [{ role: "user", text: state.preparedBoot, toolUses: [] }] }
|
|
134
135
|
})
|
|
@@ -142,7 +143,7 @@ export function register(on: On) {
|
|
|
142
143
|
const boot = await buildBoot($, identity, state.window)
|
|
143
144
|
if (!boot.ok) {
|
|
144
145
|
try {
|
|
145
|
-
await $.ui.notify("
|
|
146
|
+
await $.ui.notify("🥣 Notes didn't load")
|
|
146
147
|
} catch { /* Notification failure must not suppress the fallback block. */ }
|
|
147
148
|
}
|
|
148
149
|
const block = { name: "notesoup:boot", text: boot.ok ? String(boot.result) : `# notesoup\n${boot.error}` }
|
|
@@ -183,7 +184,7 @@ async function finishManual($: Engine, state: ResetState, signal: { wake?: () =>
|
|
|
183
184
|
}
|
|
184
185
|
} catch {
|
|
185
186
|
state.manualPending = false
|
|
186
|
-
log($, "
|
|
187
|
+
log($, "Couldn't clear memory: the close-out turn didn't start")
|
|
187
188
|
} finally { armManual($, state, signal) }
|
|
188
189
|
}
|
|
189
190
|
|
|
@@ -195,7 +196,7 @@ async function maybeReset($: Engine, state: ResetState, complete: boolean) {
|
|
|
195
196
|
catch {
|
|
196
197
|
if (!state.usageFailureLogged) {
|
|
197
198
|
state.usageFailureLogged = true
|
|
198
|
-
log($, "
|
|
199
|
+
log($, "Context usage unavailable · automatic clear-memory skipped")
|
|
199
200
|
}
|
|
200
201
|
}
|
|
201
202
|
if (state.turnRunning) return
|
|
@@ -204,35 +205,29 @@ async function maybeReset($: Engine, state: ResetState, complete: boolean) {
|
|
|
204
205
|
await reset($, state)
|
|
205
206
|
}
|
|
206
207
|
}
|
|
207
|
-
async function reset($: Engine, state: ResetState): Promise<
|
|
208
|
-
if (!state.identity
|
|
209
|
-
if (state.headless) return "notesoup: reset skipped in headless (-p / SDK) session."
|
|
210
|
-
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
|
|
211
210
|
state.resetting = true
|
|
212
211
|
state.preparedBoot = undefined
|
|
213
212
|
try {
|
|
214
213
|
const result = await $.session.compact({ instructions: RESET_INSTRUCTIONS })
|
|
215
214
|
if (result.skip !== undefined || state.preparedBoot === undefined) {
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
return `notesoup: ${text}`
|
|
215
|
+
log($, `Memory not cleared · ${result.skip ?? "notes boot was not retained"}`)
|
|
216
|
+
return
|
|
219
217
|
}
|
|
220
218
|
state.retainedBoot = state.preparedBoot
|
|
221
219
|
state.window++
|
|
222
|
-
log($,
|
|
223
|
-
return `notesoup: memory cleared · window ${state.window}`
|
|
220
|
+
log($, "Memory cleared")
|
|
224
221
|
} catch (error) {
|
|
225
222
|
const text = String(error)
|
|
226
223
|
if (text.includes("headless (-p / SDK)")) {
|
|
227
224
|
state.headless = true
|
|
228
|
-
log($,
|
|
225
|
+
log($, HEADLESS)
|
|
229
226
|
} else if (/a turn is (running|in flight)/.test(text)) {
|
|
230
227
|
state.manualPending = true
|
|
231
|
-
return "notesoup: reset queued until the turn completes."
|
|
232
228
|
} else {
|
|
233
|
-
log($, `
|
|
229
|
+
log($, `Couldn't clear memory: ${text.replace(/[\r\n].*$/s, "")}`)
|
|
234
230
|
}
|
|
235
|
-
return state.headless ? "notesoup: reset skipped in headless (-p / SDK) session." : "notesoup: reset failed; keeping the current window."
|
|
236
231
|
} finally {
|
|
237
232
|
state.preparedBoot = undefined
|
|
238
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
|
@@ -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
|
|
|
@@ -42,7 +44,7 @@ Seqs are stable. Write the useful ones into a note so they need not be found twi
|
|
|
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
|
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);
|
package/src/boot/text.ts
CHANGED
|
@@ -21,18 +21,26 @@ Your loyal notes are kept safe — no one will steal them. Use \`notes_*\` to re
|
|
|
21
21
|
|
|
22
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
|
-
- \`<path>\`, no @ — the
|
|
34
|
+
- \`<path>\`, no @ — session notes, the ones from above: this session's state and loose ends. They go away with the session.
|
|
31
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.
|
|
32
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.
|
|
33
|
-
- \`@self/<path>\` —
|
|
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~
|
|
34
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.
|
|
35
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.
|
|
43
|
+
|
|
36
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.
|
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
|
/**
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { SessionReader } from "./session-reader.js";
|
|
3
|
+
import { GUIDANCE_TYPE, WARNING_TYPE } from "./entries.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Budget reminders reach the model inside the request that crosses a threshold, but
|
|
7
|
+
* Pi can only persist them at turn_end, after that request's assistant reply. Each
|
|
8
|
+
* durable copy records the reply it preceded; projections move it back before that
|
|
9
|
+
* reply so later requests see the same prefix the first one did, and only one copy.
|
|
10
|
+
*/
|
|
11
|
+
export type AnchorDetails = { anchorEntryId: string };
|
|
12
|
+
|
|
13
|
+
const ANCHORED_TYPES = new Set([GUIDANCE_TYPE, WARNING_TYPE]);
|
|
14
|
+
|
|
15
|
+
function anchorOf(message: AgentMessage): string | undefined {
|
|
16
|
+
if (message.role !== "custom" || !ANCHORED_TYPES.has(message.customType)) return undefined;
|
|
17
|
+
const details = message.details as { anchorEntryId?: unknown } | undefined;
|
|
18
|
+
return typeof details?.anchorEntryId === "string" ? details.anchorEntryId : undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Move each durable reminder directly before the reply it preceded. Only an anchor on
|
|
23
|
+
* the active branch and visible in `messages` counts; any other reminder stays put.
|
|
24
|
+
*/
|
|
25
|
+
export function arrangeAnchoredReminders(messages: AgentMessage[], ctx: SessionReader): AgentMessage[] {
|
|
26
|
+
if (!messages.some((message) => anchorOf(message) !== undefined)) return messages;
|
|
27
|
+
// Replies are cloned into `messages`, so match by timestamp. Fast turns can share a
|
|
28
|
+
// millisecond; rank equal timestamps from the newest, since projections only drop
|
|
29
|
+
// older messages.
|
|
30
|
+
const replies = new Map<string, string>();
|
|
31
|
+
const seen = new Map<number, number>();
|
|
32
|
+
for (const entry of [...ctx.sessionManager.getBranch()].reverse()) {
|
|
33
|
+
if (entry.type !== "message" || entry.message.role !== "assistant") continue;
|
|
34
|
+
const rank = seen.get(entry.message.timestamp) ?? 0;
|
|
35
|
+
seen.set(entry.message.timestamp, rank + 1);
|
|
36
|
+
replies.set(entry.id, `${entry.message.timestamp}#${rank}`);
|
|
37
|
+
}
|
|
38
|
+
const keys = new Map<AgentMessage, string>();
|
|
39
|
+
seen.clear();
|
|
40
|
+
for (const message of [...messages].reverse()) {
|
|
41
|
+
if (message.role !== "assistant") continue;
|
|
42
|
+
const rank = seen.get(message.timestamp) ?? 0;
|
|
43
|
+
seen.set(message.timestamp, rank + 1);
|
|
44
|
+
keys.set(message, `${message.timestamp}#${rank}`);
|
|
45
|
+
}
|
|
46
|
+
const visible = new Set(keys.values());
|
|
47
|
+
const before = new Map<string, AgentMessage[]>();
|
|
48
|
+
const rest = messages.filter((message) => {
|
|
49
|
+
const anchorId = anchorOf(message);
|
|
50
|
+
const key = anchorId ? replies.get(anchorId) : undefined;
|
|
51
|
+
if (key === undefined || !visible.has(key)) return true;
|
|
52
|
+
before.set(key, [...(before.get(key) ?? []), message]);
|
|
53
|
+
return false;
|
|
54
|
+
});
|
|
55
|
+
return rest.flatMap((message) => {
|
|
56
|
+
const key = keys.get(message);
|
|
57
|
+
const moved = key ? before.get(key) : undefined;
|
|
58
|
+
if (!moved) return [message];
|
|
59
|
+
before.delete(key!);
|
|
60
|
+
return [...moved, message];
|
|
61
|
+
});
|
|
62
|
+
}
|
package/src/pi/budget.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { WARNING_CONTENT } from "./reset/text.js";
|
|
|
7
7
|
import { readThresholdSettings, type ThresholdSettingsResolution } from "./thresholds.js";
|
|
8
8
|
import { currentWindowId, hasWindowMessage, isWindowMarker, rootWindowId, windowUsage } from "./window.js";
|
|
9
9
|
import { tokenBudgetGuidance } from "../budget/text.js";
|
|
10
|
+
import { arrangeAnchoredReminders, type AnchorDetails } from "./anchored.js";
|
|
10
11
|
import { output } from "../tools/output.js";
|
|
11
12
|
|
|
12
13
|
/** Remaining tokens in the provider's active window, or null without a usable estimate. */
|
|
@@ -66,7 +67,7 @@ export function registerBudget(
|
|
|
66
67
|
for (const [key, notice] of pendingNotices) {
|
|
67
68
|
if (warningCommittedInWindow(ctx, notice)) {
|
|
68
69
|
pendingNotices.delete(key);
|
|
69
|
-
ctx.ui.notify("
|
|
70
|
+
ctx.ui.notify("🥣 Context almost full · saving notes before memory clears", "warning");
|
|
70
71
|
} else if (settled) {
|
|
71
72
|
// An uncommitted draft must not be matched to a later manual warning.
|
|
72
73
|
pendingNotices.delete(key);
|
|
@@ -85,7 +86,7 @@ export function registerBudget(
|
|
|
85
86
|
notifiedWarnings.clear();
|
|
86
87
|
};
|
|
87
88
|
|
|
88
|
-
const consumeTurnEnd = (ctx: ExtensionContext): SessionBoundaryDraft[] => {
|
|
89
|
+
const consumeTurnEnd = (ctx: ExtensionContext, anchorEntryId: string): SessionBoundaryDraft[] => {
|
|
89
90
|
const staged = [
|
|
90
91
|
pendingGuidance ? { ...pendingGuidance, customType: GUIDANCE_TYPE } : undefined,
|
|
91
92
|
pendingWarning ? { ...pendingWarning, customType: WARNING_TYPE } : undefined,
|
|
@@ -102,6 +103,7 @@ export function registerBudget(
|
|
|
102
103
|
customType: draft.customType,
|
|
103
104
|
content: draft.content,
|
|
104
105
|
display: false,
|
|
106
|
+
details: { anchorEntryId } satisfies AnchorDetails,
|
|
105
107
|
}));
|
|
106
108
|
};
|
|
107
109
|
|
|
@@ -117,41 +119,40 @@ export function registerBudget(
|
|
|
117
119
|
notifyCommittedWarnings(ctx, true);
|
|
118
120
|
clearStaged();
|
|
119
121
|
});
|
|
120
|
-
pi.on("context", (
|
|
122
|
+
pi.on("context", (event, ctx) => {
|
|
121
123
|
if (!isEnabled()) return undefined;
|
|
122
|
-
//
|
|
123
|
-
|
|
124
|
+
// Durable reminders return to the slot where the model first read them.
|
|
125
|
+
const messages = arrangeAnchoredReminders(event.messages, ctx);
|
|
126
|
+
const result = (extra?: { customType: string; content: string }) => {
|
|
127
|
+
if (!extra) return messages === event.messages ? undefined : { messages };
|
|
128
|
+
return { messages: [...messages, { role: "custom" as const, ...extra, display: false, timestamp: Date.now() }] };
|
|
129
|
+
};
|
|
130
|
+
// Each crossing reaches the model in the request that crosses it, with the count
|
|
131
|
+
// measured for that request, and persists the same text at its successful turn_end.
|
|
132
|
+
// Without automatic reset nothing gets cleared, so there is nothing to remind about.
|
|
133
|
+
if (!automaticResetEnabled(ctx)) return result();
|
|
124
134
|
const remaining = remainingTokens(ctx);
|
|
125
|
-
if (remaining === null) return
|
|
135
|
+
if (remaining === null) return result();
|
|
126
136
|
const windowId = currentWindowId(ctx);
|
|
127
137
|
const { reminder, warning } = thresholdsFor(ctx);
|
|
128
|
-
if (remaining <= warning
|
|
138
|
+
if (remaining <= warning) {
|
|
129
139
|
// Re-arm close-out on each eligible request. A prior request may have aborted
|
|
130
140
|
// after persisting the warning, so warning deduplication must not own this state.
|
|
131
141
|
onCloseOut(windowId);
|
|
132
|
-
if (hasWindowMessage(ctx, WARNING_TYPE)
|
|
142
|
+
if (hasWindowMessage(ctx, WARNING_TYPE)) return result();
|
|
133
143
|
// The critical close-out starts at reserve + runway, not at the hard reserve.
|
|
144
|
+
// Another request in the same turn re-sends the staged text instead of re-measuring.
|
|
134
145
|
pendingGuidance = undefined;
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
const warningMessage = {
|
|
138
|
-
role: "custom" as const,
|
|
139
|
-
customType: WARNING_TYPE,
|
|
140
|
-
content,
|
|
141
|
-
display: false,
|
|
142
|
-
timestamp: Date.now(),
|
|
143
|
-
};
|
|
144
|
-
return { messages: [..._event.messages, warningMessage] };
|
|
146
|
+
if (pendingWarning?.windowId !== windowId) pendingWarning = { windowId, content: WARNING_CONTENT };
|
|
147
|
+
return result({ customType: WARNING_TYPE, content: pendingWarning.content });
|
|
145
148
|
}
|
|
146
|
-
if (hasWindowMessage(ctx, WARNING_TYPE) || pendingWarning?.windowId === windowId) return
|
|
147
|
-
if (hasWindowMessage(ctx, GUIDANCE_TYPE)
|
|
148
|
-
if (
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
const left = Math.max(0, remaining - warning);
|
|
152
|
-
pendingGuidance = { windowId, content: tokenBudgetGuidance(left, PI_TOOL_NAMES.wipe) };
|
|
149
|
+
if (hasWindowMessage(ctx, WARNING_TYPE) || pendingWarning?.windowId === windowId) return result();
|
|
150
|
+
if (hasWindowMessage(ctx, GUIDANCE_TYPE)) return result();
|
|
151
|
+
if (pendingGuidance?.windowId !== windowId) {
|
|
152
|
+
if (remaining > reminder) return result();
|
|
153
|
+
pendingGuidance = { windowId, content: tokenBudgetGuidance(remainingBudget(remaining, warning) ?? 0, PI_TOOL_NAMES.wipe) };
|
|
153
154
|
}
|
|
154
|
-
return
|
|
155
|
+
return result({ customType: GUIDANCE_TYPE, content: pendingGuidance.content });
|
|
155
156
|
});
|
|
156
157
|
|
|
157
158
|
pi.registerTool(defineTool({
|
package/src/pi/dream/cli.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { gitCommit } from "../../dream/git.js";
|
|
|
13
13
|
import { readDreamerSettings } from "./settings.js";
|
|
14
14
|
import { doctor } from "../../dream/doctor.js";
|
|
15
15
|
import { notesRoot } from "../notes/adapter.js";
|
|
16
|
+
import { errorMessage } from "../../error-message.js";
|
|
16
17
|
|
|
17
18
|
function args(argv: string[]) { const out: Record<string, string | boolean> = {}; for (let i=0;i<argv.length;i++) { const a=argv[i]!; if (a === "--force" || a === "--help") out[a.slice(2)] = true; else if (a.startsWith("--")) out[a.slice(2)] = argv[++i] ?? ""; } return out; }
|
|
18
19
|
function packageRoot(): string {
|
|
@@ -43,7 +44,7 @@ export async function main(argv = process.argv.slice(2), deps: DreamDependencies
|
|
|
43
44
|
const time = timeGate(stampPath, minHours); console.log(time.reason); if (!a.force && !time.ok) return 0;
|
|
44
45
|
const since = existsSync(stampPath) ? statSync(stampPath).mtimeMs : 0;
|
|
45
46
|
const material = materialGate(home, since, minSessions); console.log(material.reason); if (!a.force && !material.ok) return 0;
|
|
46
|
-
let lock; try { lock = acquireLock(lockPath); } catch (e) { console.log(`lock gate: ${e
|
|
47
|
+
let lock; try { lock = acquireLock(lockPath); } catch (e) { console.log(`lock gate: ${errorMessage(e)}`); return 0; } if (!lock.held) { console.log(lock.reason); return 0; }
|
|
47
48
|
const stamp = new Date(lock.startedAt).toISOString().replace(/[:.]/g, "-"); const reportPath = join(home, "dreams", `${stamp}.md`);
|
|
48
49
|
let succeeded = false;
|
|
49
50
|
try {
|
|
@@ -67,7 +68,7 @@ export async function main(argv = process.argv.slice(2), deps: DreamDependencies
|
|
|
67
68
|
const playbook = loadPlaybook(playbookPath);
|
|
68
69
|
result = await (deps.runDreamer ?? runDreamer)(playbook, home, { modelPattern, sessionFactory: deps.sessionFactory });
|
|
69
70
|
} catch (e) {
|
|
70
|
-
const message =
|
|
71
|
+
const message = errorMessage(e);
|
|
71
72
|
console.error(message);
|
|
72
73
|
return finishDream(home, stamp, reportPath, true, message, []);
|
|
73
74
|
}
|
package/src/pi/dream/runner.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { DreamResult, DreamWrite } from "../../dream/result.js";
|
|
|
3
3
|
import { createAgentSession, createEditToolDefinition, createWriteToolDefinition, ModelRuntime, resolveModelScopeWithDiagnostics, SessionManager, type AgentSession, type ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import { Type, type Api, type Model } from "@earendil-works/pi-ai";
|
|
5
5
|
import { contentText } from "../../history/history.js";
|
|
6
|
+
import { errorMessage } from "../../error-message.js";
|
|
6
7
|
|
|
7
8
|
export type DreamerSession = Pick<AgentSession, "prompt" | "subscribe" | "dispose">;
|
|
8
9
|
export type DreamerSessionFactory = (options: { cwd: string; modelPattern?: string; tools: string[] }) => Promise<DreamerSession>;
|
|
@@ -80,7 +81,7 @@ export async function runDreamer(playbook: string, cwd: string, options: { model
|
|
|
80
81
|
try {
|
|
81
82
|
await session.prompt(playbook);
|
|
82
83
|
} catch (error) {
|
|
83
|
-
return { report: answer, writes, error:
|
|
84
|
+
return { report: answer, writes, error: errorMessage(error) };
|
|
84
85
|
}
|
|
85
86
|
if (providerError) return { report: answer, writes, error: `dreamer failed: ${providerError}` };
|
|
86
87
|
return { report: answer, writes };
|