notesoup 0.0.0-stage → 0.40.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/LICENSE +21 -0
- package/README.md +94 -2
- package/dist/src/boot/render.d.ts +16 -0
- package/dist/src/boot/render.js +95 -0
- package/dist/src/boot/snapshot.d.ts +32 -0
- package/dist/src/boot/snapshot.js +36 -0
- package/dist/src/boot/text.d.ts +17 -0
- package/dist/src/boot/text.js +48 -0
- package/dist/src/budget/constants.d.ts +9 -0
- package/dist/src/budget/constants.js +9 -0
- package/dist/src/budget/policy.d.ts +19 -0
- package/dist/src/budget/policy.js +36 -0
- package/dist/src/budget/text.d.ts +8 -0
- package/dist/src/budget/text.js +10 -0
- package/dist/src/claude/helper.d.ts +15 -0
- package/dist/src/claude/helper.js +87 -0
- package/dist/src/dream/doctor.d.ts +2 -0
- package/dist/src/dream/doctor.js +160 -0
- package/dist/src/dream/gates.d.ts +10 -0
- package/dist/src/dream/gates.js +26 -0
- package/dist/src/dream/git.d.ts +21 -0
- package/dist/src/dream/git.js +71 -0
- package/dist/src/dream/jail.d.ts +11 -0
- package/dist/src/dream/jail.js +71 -0
- package/dist/src/dream/lock.d.ts +31 -0
- package/dist/src/dream/lock.js +99 -0
- package/dist/src/dream/playbook.d.ts +1 -0
- package/dist/src/dream/playbook.js +2 -0
- package/dist/src/dream/report.d.ts +7 -0
- package/dist/src/dream/report.js +43 -0
- package/dist/src/dream/result.d.ts +9 -0
- package/dist/src/dream/result.js +1 -0
- package/dist/src/dream/settings.d.ts +10 -0
- package/dist/src/dream/settings.js +14 -0
- package/dist/src/history/history.d.ts +156 -0
- package/dist/src/history/history.js +212 -0
- package/dist/src/history/query.d.ts +63 -0
- package/dist/src/history/query.js +201 -0
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.js +1 -0
- package/dist/src/notes/address.d.ts +31 -0
- package/dist/src/notes/address.js +123 -0
- package/dist/src/notes/constants.d.ts +3 -0
- package/dist/src/notes/constants.js +3 -0
- package/dist/src/notes/errors.d.ts +11 -0
- package/dist/src/notes/errors.js +13 -0
- package/dist/src/notes/frontmatter.d.ts +44 -0
- package/dist/src/notes/frontmatter.js +145 -0
- package/dist/src/notes/fs-error.d.ts +2 -0
- package/dist/src/notes/fs-error.js +5 -0
- package/dist/src/notes/identity.d.ts +10 -0
- package/dist/src/notes/identity.js +33 -0
- package/dist/src/notes/index.d.ts +5 -0
- package/dist/src/notes/index.js +3 -0
- package/dist/src/notes/paths.d.ts +21 -0
- package/dist/src/notes/paths.js +113 -0
- package/dist/src/notes/store.d.ts +103 -0
- package/dist/src/notes/store.js +474 -0
- package/dist/src/pi/boot.d.ts +24 -0
- package/dist/src/pi/boot.js +56 -0
- package/dist/src/pi/budget.d.ts +13 -0
- package/dist/src/pi/budget.js +178 -0
- package/dist/src/pi/dream/cli.d.ts +10 -0
- package/dist/src/pi/dream/cli.js +140 -0
- package/dist/src/pi/dream/runner.d.ts +27 -0
- package/dist/src/pi/dream/runner.js +90 -0
- package/dist/src/pi/dream/settings.d.ts +7 -0
- package/dist/src/pi/dream/settings.js +17 -0
- package/dist/src/pi/entries.d.ts +7 -0
- package/dist/src/pi/entries.js +7 -0
- package/dist/src/pi/estimate.d.ts +16 -0
- package/dist/src/pi/estimate.js +99 -0
- package/dist/src/pi/extension.d.ts +10 -0
- package/dist/src/pi/extension.js +24 -0
- package/dist/src/pi/history-tools.d.ts +3 -0
- package/dist/src/pi/history-tools.js +9 -0
- package/dist/src/pi/history.d.ts +4 -0
- package/dist/src/pi/history.js +150 -0
- package/dist/src/pi/notes/adapter.d.ts +10 -0
- package/dist/src/pi/notes/adapter.js +27 -0
- package/dist/src/pi/notes/tools.d.ts +3 -0
- package/dist/src/pi/notes/tools.js +15 -0
- package/dist/src/pi/reset/artifacts.d.ts +24 -0
- package/dist/src/pi/reset/artifacts.js +84 -0
- package/dist/src/pi/reset/committed.d.ts +7 -0
- package/dist/src/pi/reset/committed.js +28 -0
- package/dist/src/pi/reset/lifecycle.d.ts +101 -0
- package/dist/src/pi/reset/lifecycle.js +277 -0
- package/dist/src/pi/reset/text.d.ts +5 -0
- package/dist/src/pi/reset/text.js +6 -0
- package/dist/src/pi/runtime.d.ts +3 -0
- package/dist/src/pi/runtime.js +206 -0
- package/dist/src/pi/session-reader.d.ts +5 -0
- package/dist/src/pi/session-reader.js +1 -0
- package/dist/src/pi/thresholds.d.ts +17 -0
- package/dist/src/pi/thresholds.js +33 -0
- package/dist/src/pi/tool-names.d.ts +7 -0
- package/dist/src/pi/tool-names.js +7 -0
- package/dist/src/pi/tool-result.d.ts +15 -0
- package/dist/src/pi/tool-result.js +29 -0
- package/dist/src/pi/window.d.ts +41 -0
- package/dist/src/pi/window.js +127 -0
- package/dist/src/settings.d.ts +9 -0
- package/dist/src/settings.js +18 -0
- package/dist/src/text-match.d.ts +5 -0
- package/dist/src/text-match.js +16 -0
- package/dist/src/tools/history.d.ts +58 -0
- package/dist/src/tools/history.js +210 -0
- package/dist/src/tools/notes.d.ts +250 -0
- package/dist/src/tools/notes.js +360 -0
- package/dist/src/tools/output.d.ts +23 -0
- package/dist/src/tools/output.js +39 -0
- package/dist/src/tools/result.d.ts +82 -0
- package/dist/src/tools/result.js +104 -0
- package/dist/src/tools/schema.d.ts +18 -0
- package/dist/src/tools/schema.js +31 -0
- package/dist/test/agent-loop.test.d.ts +1 -0
- package/dist/test/agent-loop.test.js +1497 -0
- package/dist/test/boot.integration.test.d.ts +1 -0
- package/dist/test/boot.integration.test.js +294 -0
- package/dist/test/budget-settings.integration.test.d.ts +1 -0
- package/dist/test/budget-settings.integration.test.js +144 -0
- package/dist/test/claude-mod.test.d.ts +1 -0
- package/dist/test/claude-mod.test.js +404 -0
- package/dist/test/dependencies.test.d.ts +1 -0
- package/dist/test/dependencies.test.js +101 -0
- package/dist/test/doctor.test.d.ts +1 -0
- package/dist/test/doctor.test.js +37 -0
- package/dist/test/dream-skill.test.d.ts +1 -0
- package/dist/test/dream-skill.test.js +72 -0
- package/dist/test/dream.test.d.ts +1 -0
- package/dist/test/dream.test.js +136 -0
- package/dist/test/helpers/dependency-graph.d.ts +5 -0
- package/dist/test/helpers/dependency-graph.js +73 -0
- package/dist/test/helpers/extension-test-environment.d.ts +1 -0
- package/dist/test/helpers/extension-test-environment.js +9 -0
- package/dist/test/helpers/extension.d.ts +119 -0
- package/dist/test/helpers/extension.js +367 -0
- package/dist/test/helpers/notes.d.ts +6 -0
- package/dist/test/helpers/notes.js +13 -0
- package/dist/test/history.integration.test.d.ts +1 -0
- package/dist/test/history.integration.test.js +633 -0
- package/dist/test/host-neutral.test.d.ts +1 -0
- package/dist/test/host-neutral.test.js +274 -0
- package/dist/test/notes-library.test.d.ts +1 -0
- package/dist/test/notes-library.test.js +214 -0
- package/dist/test/notes.integration.test.d.ts +1 -0
- package/dist/test/notes.integration.test.js +515 -0
- package/dist/test/notes.test.d.ts +1 -0
- package/dist/test/notes.test.js +530 -0
- package/dist/test/reset-lifecycle.test.d.ts +1 -0
- package/dist/test/reset-lifecycle.test.js +605 -0
- package/docs/architecture.md +63 -0
- package/docs/claude-code-mod.md +9 -0
- package/docs/notes-library.md +74 -0
- package/docs/reset-lifecycle.md +75 -0
- package/docs/sdk-integration.md +39 -0
- package/docs/skills.md +30 -0
- package/docs/tool-results.md +78 -0
- package/mods/notesoup/.claude-plugin/plugin.json +8 -0
- package/mods/notesoup/dist/claude/helper.js +9265 -0
- package/mods/notesoup/hooks/hooks.json +4 -0
- package/mods/notesoup/hooks/register.ts +240 -0
- package/mods/notesoup/playbook.md +34 -0
- package/mods/notesoup/skills/dream/SKILL.md +12 -0
- package/mods/pi-context/dist/claude/helper.js +9324 -0
- package/package.json +89 -5
- package/playbook.md +34 -0
- package/skills/dream/SKILL.md +12 -0
- package/skills/memory/SKILL.md +59 -0
- package/src/boot/render.ts +115 -0
- package/src/boot/snapshot.ts +46 -0
- package/src/boot/text.ts +58 -0
- package/src/budget/constants.ts +9 -0
- package/src/budget/policy.ts +36 -0
- package/src/budget/text.ts +11 -0
- package/src/claude/helper.ts +94 -0
- package/src/dream/doctor.ts +117 -0
- package/src/dream/gates.ts +26 -0
- package/src/dream/git.ts +73 -0
- package/src/dream/jail.ts +62 -0
- package/src/dream/lock.ts +82 -0
- package/src/dream/playbook.ts +3 -0
- package/src/dream/report.ts +36 -0
- package/src/dream/result.ts +2 -0
- package/src/dream/settings.ts +16 -0
- package/src/history/history.ts +286 -0
- package/src/history/query.ts +222 -0
- package/src/index.ts +1 -0
- package/src/notes/address.ts +110 -0
- package/src/notes/constants.ts +3 -0
- package/src/notes/errors.ts +15 -0
- package/src/notes/frontmatter.ts +166 -0
- package/src/notes/fs-error.ts +5 -0
- package/src/notes/identity.ts +40 -0
- package/src/notes/index.ts +24 -0
- package/src/notes/paths.ts +109 -0
- package/src/notes/store.ts +494 -0
- package/src/pi/boot.ts +88 -0
- package/src/pi/budget.ts +178 -0
- package/src/pi/dream/cli.ts +92 -0
- package/src/pi/dream/runner.ts +91 -0
- package/src/pi/dream/settings.ts +17 -0
- package/src/pi/entries.ts +7 -0
- package/src/pi/estimate.ts +116 -0
- package/src/pi/extension.ts +27 -0
- package/src/pi/history-tools.ts +11 -0
- package/src/pi/history.ts +162 -0
- package/src/pi/notes/adapter.ts +33 -0
- package/src/pi/notes/tools.ts +18 -0
- package/src/pi/reset/artifacts.ts +100 -0
- package/src/pi/reset/committed.ts +26 -0
- package/src/pi/reset/lifecycle.ts +342 -0
- package/src/pi/reset/text.ts +10 -0
- package/src/pi/runtime.ts +200 -0
- package/src/pi/session-reader.ts +6 -0
- package/src/pi/thresholds.ts +50 -0
- package/src/pi/tool-names.ts +9 -0
- package/src/pi/tool-result.ts +41 -0
- package/src/pi/window.ts +133 -0
- package/src/settings.ts +22 -0
- package/src/text-match.ts +14 -0
- package/src/tools/history.ts +234 -0
- package/src/tools/notes.ts +381 -0
- package/src/tools/output.ts +41 -0
- package/src/tools/result.ts +144 -0
- package/src/tools/schema.ts +31 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# Architecture
|
|
2
|
+
|
|
3
|
+
notesoup uses Pi's session branch as the durable source of truth. It does not maintain a second transcript or a hidden prompt overlay. Runtime state exists only to schedule work and reserve a reminder until Pi persists it.
|
|
4
|
+
|
|
5
|
+
## Ownership
|
|
6
|
+
|
|
7
|
+
| Module | Responsibility | Boundary |
|
|
8
|
+
| --- | --- | --- |
|
|
9
|
+
| `index.ts` | Minimal re-export of the Pi extension and `createNotesoup` | Host entry only; shared domains cannot import it |
|
|
10
|
+
| `notes/identity.ts`, `notes/store.ts`, `notes/address.ts`, `notes/paths.ts` | Explicit `NotesIdentity`, filesystem homes, metadata, addressing and mutations | Node filesystem, no SDK or host environment identity |
|
|
11
|
+
| `boot/snapshot.ts` | Load each of the closed five homes once; isolate filesystem errno failures | Explicit identity, captured time and optional scope loader |
|
|
12
|
+
| `boot/render.ts`, `boot/text.ts` | Render identity, protocol, maps and recent-note metadata | Explicit snapshot and logical tool-name bindings; no I/O or clock |
|
|
13
|
+
| `history/history.ts` | Project decoded events and pair tool calls/results, preserving supplied addresses | Decoded items and branch visibility; never inference messages |
|
|
14
|
+
| `history/query.ts` | Bounded paging, `from` selection, literal matching, folding and preview rendering | Query projection only; no native session traversal |
|
|
15
|
+
| `budget/constants.ts`, `budget/policy.ts`, `budget/text.ts` | Pure thresholds, unknown/clamped countdown and reminder text | Values supplied by the caller; no settings reads or scheduling |
|
|
16
|
+
| `tools/notes.ts`, `tools/history.ts`, `tools/schema.ts`, `tools/result.ts`, `tools/output.ts` | Schema-derived outcomes, note/history operations, bounded result selection and pure text rendering | Explicit identity/projection; one bounded result feeds both text and structured output |
|
|
17
|
+
| `settings.ts`, `dream/settings.ts` | Settings keys, per-key merge and dreamer validation | Parsed values only; no SDK or I/O |
|
|
18
|
+
| `dream/` | Jail, crumpled-only physical deletion, locks, gates, Git audit, doctor, playbook and result/report logic | Independent filesystem/policy functions; no reverse import into Pi |
|
|
19
|
+
| `pi/extension.ts`, `pi/runtime.ts` | Compose registration, lifecycle hooks, commands, provider operations and UI | Public Pi SDK |
|
|
20
|
+
| `pi/entries.ts` | Persisted native custom-entry/message tags | Pi persistence vocabulary, not an omnibus protocol barrel |
|
|
21
|
+
| `pi/window.ts`, `pi/session-reader.ts` | Native `WindowMarker`, checkpoint validation, root/fork identity, branch scans, provider projection and usage | Pi entries/messages and read-only native session traversal |
|
|
22
|
+
| `pi/history.ts` | Decode native messages, allocate seqs from append order and select active-branch visibility | Native SessionEntry/AgentMessage decoding; feeds shared query projection |
|
|
23
|
+
| `pi/notes/`, `pi/history-tools.ts`, `pi/tool-result.ts` | Extract live execution data, register output schemas, package outcomes and render native note diffs | Native API -> shared operations; no second query or pagination path |
|
|
24
|
+
| `pi/thresholds.ts`, `pi/budget.ts` | Read settings/usage, cache policy per instance, stage prompts, warn and schedule native reset decisions | Public SettingsManager and native lifecycle |
|
|
25
|
+
| `pi/reset/lifecycle.ts` | Native turn/settle reducer facts, batching, recovery and continuation | Public Pi lifecycle hooks and boundary drafts |
|
|
26
|
+
| `pi/reset/artifacts.ts`, `pi/reset/committed.ts` | Construct boundaries, repair only safe suffixes, independently confirm committed native boundaries | Active native branch; no shadow commit database |
|
|
27
|
+
| `pi/dream/` | Pi dream sessions, native tool wrappers, settings reads and executable CLI composition | Pi backend over independent dream policy/filesystem functions |
|
|
28
|
+
|
|
29
|
+
Dependencies flow from Pi composition into the domains, never back. Shared code cannot import an SDK, `src/pi`, or the root entry, even through erased types, re-exports, literal dynamic/import-type edges or intermediate modules. `test/dependencies.test.ts` uses TypeScript resolution and AST traversal, checks every shared source (including root settings/text matching), and tests rejecting indirect/aliased paths. Shared external packages must be declared in the package manifest. `typebox` is declared as a peer and development dependency rather than imported through Pi's SDK.
|
|
30
|
+
|
|
31
|
+
The configured extension is `src/index.ts`, loaded straight from TypeScript — no bundling step, so git installs work without a build. Its `pi-ai/utils/estimate` dependency is vendored in `src/pi/estimate.ts` because Pi's root-package aliases misresolve that public subpath on source loads; host-owned SDK APIs stay external. `/notes` is the intentional standalone library API. The CLI is `dist/src/pi/dream/cli.js`. Old internal bags, `NotesContext`, root history helpers and the deep-entry export alias are removed. This breaks source/import paths, not storage: note homes, metadata, session paths and raw history remain intact. There is no universal Harness, host-event emulator, registry, daemon or speculative second backend. No `src/window` exists because the current window responsibilities are genuinely native.
|
|
32
|
+
|
|
33
|
+
## State and persistence
|
|
34
|
+
|
|
35
|
+
`pi/reset/lifecycle.ts` is the sole `turn_end` composer: it accepts incoming drafts, drains budget-owned guidance/warning drafts, and appends a reset boundary for an explicit tool request or the hard-reserve safety path. Manual and budget close-outs stay armed across note/tool turns and commit from `agent_before_settle` after a successful stop with queued work drained; a manual close-out stops the run while a budget close-out continues in the fresh window. Repeated requests for the same window deduplicate. See [reset lifecycle](reset-lifecycle.md).
|
|
36
|
+
|
|
37
|
+
A new reset is a native empty-summary compaction checkpoint configured to retain none, followed by one `notesoup/reset-marker` custom entry with `{ windowId: string }`, a hidden `notesoup/boot` whose `details.windowId` matches, and a hidden continuation. The checkpoint is the canonical-history cut; the marker is the durable logical window identity. Raw session entries remain available to history tools. Legacy marker-only branches keep a narrow projection fallback. `pi/window.ts` owns marker/checkpoint validation, active-branch scan, root/current IDs, and per-window message lookup; `pi/history.ts` consumes those native identity primitives while decoding entries; shared `history/history.ts` only receives decoded, addressed data. The scan never uses a global entry tail.
|
|
38
|
+
|
|
39
|
+
The runtime in `pi/runtime.ts` performs final context projection by selecting the active boot through `details.windowId` and folding only the dropped system prefix through Pi's `getCurrentSystemMessage`. Later prompt patches and new messages stay in order. A missing boot aborts the hook with a safe head and notice rather than silently sending raw history. Startup/tree handling repairs only a genuinely incomplete marker tail: a missing boot with no later raw message, custom message, compaction, branch summary, or authoritative raw boot. If later work exists, boot creation is refused and `/clear-memory` is the explicit recovery path; it does not parse or migrate the legacy reset-v2 protocol.
|
|
40
|
+
|
|
41
|
+
Boot and reminder deduplication inspect the current branch-local window. Reloading JSONL therefore does not duplicate messages, while navigation to a sibling branch cannot inherit another branch's window state. A fork/clone receives a new session ID while copying its selected path, so startup must also verify that a root boot's `details.windowId` matches the new `rootWindowId(sessionId)` before treating it as present.
|
|
42
|
+
|
|
43
|
+
Manual `/clear-memory` arms a close-out and always sends the hidden checkpoint prompt: when idle it starts one ordinary model turn, while streaming it steers the running turn so the agent closes out promptly. The agent may span several note/tool turns; the reset commits at a successful settlement after queued work drains, and the run stops rather than continuing in the fresh window. That prompt and the budget warning share the same text but have distinct persisted types, so an aborted manual request cannot suppress a later budget warning. The budget warning remains a multi-turn close-out with an explicit `clear_memory` commit or a successful normal-stop fallback. Abort and ordinary errors never count as successful close-out. Manual overflow commits a reset without recovery continuation, even with automatic reset disabled. A hard-reserve reset preserves the manual stop in a run-scoped `stop-pending` phase; the lifecycle's `context_with_system` hook verifies the actual committed boundary and cancels an empty tool-batch follow-up through public `ctx.abort()`. Pending or already-delivered user input bypasses cancellation and is answered before settlement stops without a second wipe. The checkpoint, marker, boot, and continuation are emitted as ordered session-boundary drafts. Pi's retain-none compaction entry persists the canonical cut; the marker/boot preserve notesoup's logical identity and protocol.
|
|
44
|
+
|
|
45
|
+
Boot is a fixed snapshot for its window, stored as an extension custom message and converted by Pi to a user-role model message. History internally distinguishes native system summaries and extension-authored custom messages; its public `context` event groups both without implying provider instruction priority. A system-role projection is technically possible through `context_with_system`, but would change the authority of the mixed protocol/MAP content and provider-specific prompt/cache behavior; it is not a prerequisite for persistence. Boot injection is silent, including startup, reload, and boot repair. Only an actual context reset produces `notesoup: memory cleared · <windowId>` through `ctx.ui.notify`, after the verified checkpoint, marker, boot, and continuation are present in the session. Committed resets are checked at the next turn start or final settlement. `pi/reset/committed.ts` confirms an ordered hidden boot/continuation after a checkpoint-backed marker even when later conversation exists. That is distinct from `inspectResetTail`, which refuses suffix repair after real work or malformed ordering. Uncommitted reset drafts never announce success. Boot and continuation messages retain `display: false`.
|
|
46
|
+
|
|
47
|
+
The Pi history adapter decodes the selected raw session branch on demand without a cache. It allocates stable seq values from the session's append-order entry list, then selects current-branch-only visibility, so navigation cannot expose a sibling's history. Shared history pairs and queries those decoded events; it neither traverses SessionReader nor reconstructs inference messages. The public stream combines each tool call with its result at the call seq; paired result slots are not public event addresses, and unpaired results retain their own seq. Summaries and injected messages project as `context`. List pages chronologically with seq anchors and an explicit `from`. Tool executions retain structured call/result facts and any native nested-call metadata. A deterministic event document supplies both query-match positions and read windows. Nested calls have no independent seq and never imply that unrecorded child outputs are available.
|
|
48
|
+
|
|
49
|
+
The boot notes index in `boot/snapshot.ts` is a closed snapshot: the current session, project, human, agent, and model homes are each loaded at most once while constructing a boot. `boot/snapshot.ts` takes explicit `NotesIdentity`, captured `openedAt` and an optional home loader; `boot/render.ts` renders that snapshot and explicit tool bindings without reading the filesystem or consulting the clock. Pi supplies its unchanged tool names. MAP bodies and pocket metadata are derived from the same snapshot, so a boot cannot mix two filesystem reads. Note storage and home traversal use `node:fs/promises`; same-file operations queue by absolute physical filename across store instances in this process, without promising symlink/case-alias or cross-process locking. Known persisted metadata is camelCase. Old snake_case keys are unrecognized extras, not interpreted or migrated; startup does not migrate notes. A missing home (`ENOENT`) is normal. A real read failure omits only that home's index, preserves healthy homes, adds a model-facing `notes_list` recovery notice, and notifies the human once for that window. Boot/reset construction captures session, agent, and model identity before awaiting the snapshot, then checks lifecycle generation, active window, enabled state, and abort status before sending or returning artifacts; stale completions cannot commit into a switched or shut-down session. Boot acquisition uses listing and never updates access metadata. Explicit note reads update `lastAccessed` and `accessCount`; no fallback state is created.
|
|
50
|
+
|
|
51
|
+
Notes remain in their filesystem-backed homes, unchanged by session branch navigation. Tool reads expose metadata separately from body windows; search/read code-point offsets are body-relative and do not depend on frontmatter serialization or access-counter changes.
|
|
52
|
+
|
|
53
|
+
Notes/history operations return schema-derived `Outcome<T>` values, not host `content` objects. One bounded candidate is measured against both its complete structured serialization and its text renderer. Pi registers the outcome schema and packages that same value as `structuredContent`, derives `isError` from it and puts rendered text in `content`. Claude uses the same operations and renderers. Neither adapter parses text or independently chooses a page. Read continuation hints follow Pi's native trailing-notice style and are not part of the addressed text. See [tool results](tool-results.md) for the breaking protocol and coordinate contract.
|
|
54
|
+
|
|
55
|
+
The `/clear-memory` command only waits for idle when the session is busy with non-agent work; during model output it arms the close-out and steers the checkpoint prompt into the running turn. While enabled, `/compact` is cancelled with an actionable `/clear-memory` notice. Disabling notesoup stops new automatic resets, but an existing native checkpoint/marker still excludes earlier history and native compaction is still cancelled on that marked branch; a fresh root may use native Pi semantics. Threshold and warning accounting use active-window provider usage rather than pre-reset global usage. Budget policy and staged prompts are instance-owned, so concurrent sessions cannot share reserve/enablement or uncommitted drafts; default file-backed policy is cached per instance, while injected policy is resolved live on each decision and model/session transitions reset the diagnostic lifecycle.
|
|
56
|
+
|
|
57
|
+
## Evidence and limits
|
|
58
|
+
|
|
59
|
+
The retained integration tests use real SessionManager and SettingsManager instances. They check reset-window history retention, seq-addressed and cursor-paged history, bounded history/notes reads with resumable character windows, notes-home isolation, and settings precedence. The suite is representative rather than exhaustive. Focused host-neutral tests additionally run boot/tool/history/budget logic with explicit inputs and no SDK context; resolved-AST guards enforce the dependency boundary.
|
|
60
|
+
|
|
61
|
+
Scripted SDK tests execute the real Pi agent loop with no model/network request. They inspect provider contexts and durable entries for idle and streaming manual requests, budget close-out, explicit and normal-stop commits, abort/error cleanup, same-window command deduplication, queued steering/follow-up delivery, retain-none checkpoints across two resets and disk reopen, bounded overflow recovery, and settings authority. Smaller dream tests retain lock exclusion/ownership, jailed writes, CLI audit/report failure propagation, and read-only doctor behavior. Removing duplicate scenarios and edge-case matrices reduces coverage; the remaining tests do not establish every malformed-input case, branch interleaving, external-provider behavior, or filesystem failure mode.
|
|
62
|
+
|
|
63
|
+
Mixed tool batches finish before a direct tool or manual reset boundary. Budget close-outs let queued steering/follow-up work run once in the old window before fallback; turn-end resets let Pi schedule queued work across the new boundary. Scripted loop tests check that these messages are neither dropped nor replayed. Runtime overflow recovery is bounded to one reset/retry per failure chain, while ordinary retryable provider errors remain Pi-owned. When either the source or destination branch has a reset marker, `/tree` navigation still succeeds but its generated summary is replaced by an empty summary plus a notice; raw history and branch selection remain available. If neither branch has a marker, Pi's native tree summary is retained.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Claude Code Mod
|
|
2
|
+
|
|
3
|
+
The package also ships `mods/notesoup`, an early-access Claude Code Mod that registers the five notes tools as `mcp__notesoup__notes_*` tools and attaches one host-scoped notes boot block through Claude's conversation-scoped `prompt.context` event; Claude persists it across resume and reload. The sandboxed hooks module delegates filesystem and shared-domain work to the plugin-local `mods/notesoup/dist/claude/helper.js` through Claude's bounded `$.process.run` capability.
|
|
4
|
+
|
|
5
|
+
In interactive sessions it resets automatically when `$.session.usage().context.percent >= 85`, checking after `session.measure` and `turn.complete` and waiting for a running turn to complete. Missing percentages do not trigger a reset. Its own `session.compact` hook replaces the conversation with exactly one freshly built notes boot, not a generated summary. `prompt.context` still recomputes but does not duplicate that retained boot. Boot window IDs end in the ordinal `:0`, `:1`, etc.; retained boots restore the ordinal on resume/reload. Original transcript rows remain on disk.
|
|
6
|
+
|
|
7
|
+
`/clear-memory` requests the same reset. While idle it submits one hidden normal-model close-out turn to let the model save notes, then resets at `turn.complete`; while busy it waits for the current turn instead. This is necessary in Claude Code 2.1.295: `command.run` holds a turn, and calling compact from a detached timer skips the plugin's own compact hook. The timer only schedules the close-out prompt, never compaction. The headless (`-p` / SDK) compact capability is unsupported: automatic attempts are caught and logged once, and the manual command skips without submitting a model turn. Boot acquisition failure vetoes reset, leaving the current window intact. These behaviors add no settings. Claude history tools, Pi-style warning/runway budgeting, and a Claude dream backend are not implemented.
|
|
8
|
+
|
|
9
|
+
The plugin also exposes the shared `skills/dream/SKILL.md` and its referenced `playbook.md`; the build synchronizes both projections from the canonical repository files. Validate it from a built checkout with `claude plugin validate mods/notesoup --strict`; the package build and `npm pack --dry-run` include the manifests, hooks module, helper, skill, and playbook.
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# Standalone notes library
|
|
2
|
+
|
|
3
|
+
The same package provides a **Node.js TypeScript library independent of Pi**:
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install notesoup
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { createNotesStore, type NotesIdentity } from "notesoup/notes";
|
|
11
|
+
|
|
12
|
+
const identity: NotesIdentity = {
|
|
13
|
+
home: "/path/to/notes", // explicit filesystem root
|
|
14
|
+
sessionId: "my-session", // safe single directory component
|
|
15
|
+
projectKey: "my-project-a1b2c3d4",
|
|
16
|
+
agent: "my-agent", // canonical lowercase slug
|
|
17
|
+
model: "my-model", // canonical lowercase slug
|
|
18
|
+
};
|
|
19
|
+
const notes = createNotesStore(identity);
|
|
20
|
+
await notes.write("@project/decisions.md", "Use a shared notes library.", { origin: "user" });
|
|
21
|
+
await notes.update("@project/decisions.md", [
|
|
22
|
+
{ oldText: "shared", newText: "host-independent" },
|
|
23
|
+
]);
|
|
24
|
+
const note = await notes.read("@project/decisions.md"); // body and metadata, or undefined
|
|
25
|
+
const files = await notes.list({ glob: "@project/**" });
|
|
26
|
+
const matches = await notes.search(["library"]);
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`/notes` ships JavaScript and TypeScript declarations. It does not import Pi or read `PI_*` environment variables. Pi packages are optional peers: a notes-only installation does not install them. Using the plugin, root SDK entry, or `dream` CLI still requires Pi. This is a filesystem library for Node, not a browser storage API.
|
|
30
|
+
|
|
31
|
+
## API and identity
|
|
32
|
+
|
|
33
|
+
`createNotesStore(identity)` snapshots the five required identity fields; changing the supplied object afterward does not retarget the store. It resolves `home` once, validates identity components, and creates no files until an operation needs to write. Create a new store to change identity. Multiple stores can use independent roots and identities without changing process environment.
|
|
34
|
+
|
|
35
|
+
- `write(address, content, { origin? }?)` returns `Promise<{ meta, outcome }>` (`created`, `overwritten` or `uncrumpled`). Default origin is `self`; overwriting preserves creation time, existing project ownership, and unknown metadata, and always produces an uncrumpled note (it clears any `crumpledAt`).
|
|
36
|
+
- `read(address)` returns `Promise<{ meta, body, resolvedScope } | undefined>`. **Reads update** `lastAccessed` and `accessCount` on disk. The body is separate from metadata; the serialized frontmatter is not part of the read API.
|
|
37
|
+
- `update(address, edits?, { origin?, crumpled?, replaceAll? }?)` returns `Promise<{ meta, applied, resolvedScope, change }>`. Edits affect the body; metadata-only changes need no edits, but must supply `origin` or `crumpled`. `crumpled: true` records `crumpledAt` (keeping the original time if already set); `crumpled: false` removes it; omitted leaves it unchanged. Crumpling and smoothing never change `updatedAt`, which tracks body or origin changes only. Each replacement uses the evolving body in array order; the complete batch is written atomically only after every edit succeeds. `change` is a typed `{ kind, before, after }`: `kind` is `body`, `metadata`, or `none` with empty strings when neither body, origin, nor `crumpledAt` changed. A body change that also rewrites frontmatter is still `body`, and its diff inputs then span the whole serialized file. It is not a rendered diff.
|
|
38
|
+
- `rename(fromAddress, toAddress)` returns `Promise<{ meta, replacedCrumpledTarget }>`. The note moves with every metadata key preserved (`updatedAt` is bumped); a live note at the target refuses with `already_exists`, a crumpled target is replaced, and renaming onto the same resolved path is `nothing_to_do`.
|
|
39
|
+
- `list({ glob?, scope?, who?, crumpled? }?)` returns `Promise<NoteRow[]>`, sorted by update time descending with address tie-breaking. Rows contain address, scope, virtual path, metadata, body, and body byte size. `scope` narrows the five-home view; `who` names a concrete agent/model home. By default crumpled notes are excluded; `crumpled: true` returns only crumpled notes instead.
|
|
40
|
+
- `search(queries: string[], { glob?, scope?, who?, crumpled? }?)` returns `Promise<NoteSearchRow[]>`, sorted by address, with the same crumpled-note rule as `list`. Matching is case-insensitive literal OR over body lines; matches contain one-based `line`, `text`, and `offsetChars` into the body, excluding frontmatter. Neither listing nor search increments access metadata.
|
|
41
|
+
|
|
42
|
+
`list` and `search` share the `NotesQuery` type. A merged query uses `{ glob?, crumpled? }`; a single-home query adds `scope`. Only `scope: "agent" | "model"` accepts `who`. TypeScript rejects combinations such as `{ scope: "project", who: "root" }`, and JavaScript callers receive a runtime refusal.
|
|
43
|
+
|
|
44
|
+
The library returns full data, not tool envelopes or paginated/truncated output. `NoteError` exposes the existing named store refusals through `code`, with `lineNumbers` for ambiguous edits and `editIndex` for a failed edit. Runtime API fields and known persisted note metadata use camelCase; Pi tool wire fields such as `updated_at`, `offset_chars`, and `replace_all` retain their established names. Unrecognized frontmatter keys, including old snake_case metadata, are preserved as ordinary extras; they are not interpreted as current camelCase fields or migrated automatically. Invalid addresses/identities and filesystem failures reject; only a missing `read` returns `undefined`. Notes remain markdown files with the existing size limits and same-directory atomic rename. Same-file read/modify/write work is serialized by absolute physical filename across all store instances in this process (including `.md` address aliases); symlink/case aliases and cross-process locking are not guaranteed. `list` and `search` asynchronously traverse homes and serialize each discovered file read against pending mutations, but are not global snapshots and may not discover a file created after traversal. Foreign named homes can be read (including the access-metadata update), but their bodies cannot be written or edited through the store. These are cooperative address rules, not an OS security sandbox.
|
|
45
|
+
|
|
46
|
+
Addresses are a path with no `@` (a session note), `@project/`, `@human/`, `@self/`, `@model/`, or explicit `@agents/<slug>/` and `@models/<slug>/`. Relative self/model addresses resolve to the supplied identity. Results show the current agent's and model's notes as `@self/` and `@model/`; only other agents' or models' notes carry an explicit `@agents/<slug>/` or `@models/<slug>/`. Globs accept either form. The disk layout remains `pi/session/<sessionId>/`, `project/<projectKey>/`, `human/`, `agents/<agent>/`, and `models/<model>/`. No data migration happens on library import or construction. Notes already using camelCase metadata retain their metadata; old snake_case keys are preserved as unrecognized extras, not interpreted or migrated. New session notes record the supplied project key.
|
|
47
|
+
|
|
48
|
+
## Library and plugin boundary
|
|
49
|
+
|
|
50
|
+
Ownership is explicit in the file tree:
|
|
51
|
+
|
|
52
|
+
```text
|
|
53
|
+
src/
|
|
54
|
+
index.ts # only the Pi extension and createNotesoup factory
|
|
55
|
+
notes/ # filesystem semantics and explicit NotesIdentity
|
|
56
|
+
boot/ # five-home snapshot and pure rendering with tool bindings
|
|
57
|
+
history/ # decoded query projection, pairing, paging and folding
|
|
58
|
+
budget/ # pure thresholds, countdown policy and reminder text
|
|
59
|
+
tools/ # operation schemas, typed outcomes and bounded presentation
|
|
60
|
+
dream/ # jail, deletion policy, locks, gates, audit, reports, doctor
|
|
61
|
+
settings.ts # SDK-independent settings keys and per-key parsing
|
|
62
|
+
pi/ # native integration, not part of /notes
|
|
63
|
+
extension.ts # registration composition
|
|
64
|
+
runtime.ts # native lifecycle, commands, provider projection and UI
|
|
65
|
+
window.ts # native markers, checkpoints, branches and usage
|
|
66
|
+
history.ts # native decoding, seq allocation and branch selection
|
|
67
|
+
notes/ # live identity extraction, registration and native diffs
|
|
68
|
+
reset/ # reducer, boundary drafts, commit confirmation and repair
|
|
69
|
+
dream/ # Pi session backend, settings reads and CLI
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The public runtime exports are `createNotesStore`, `NoteError`, `projectKey(cwd)`, and `slugify(value)`, alongside the API's TypeScript types. The factory and `projectKey` remain synchronous; `projectKey` provides the existing repository/worktree identity algorithm, while `slugify` normalizes an agent/model name. The six primary store methods return promises and use asynchronous filesystem operations. Path/glob helpers, serialization, validation internals and constants are implementation details, not exported through `/notes`.
|
|
73
|
+
|
|
74
|
+
The Pi adapter supplies the root and live session/project/agent/model identity on each call. Tools and boot use the same storage implementation. Shared tool schemas use `typebox`, declared as a peer supplied by Pi and as a dev dependency for standalone development; their handlers accept explicit identities or decoded history projections. Pi owns registration, execution-context extraction and native edit diff rendering. Boot snapshot acquisition receives identity, a captured timestamp and an optional home loader; rendering receives explicit logical tool names. Native session traversal, stable seq allocation, branch selection and inference projection stay in Pi. Shared history is a query view, never a way to reconstruct inference messages. There are no compatibility shims or generic host runtime. Internal source paths are not the supported library API.
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# Reset lifecycle
|
|
2
|
+
|
|
3
|
+
All lifecycle control flow is native Pi integration. `src/pi/reset/lifecycle.ts` owns close-out phases, native turn/settle reducer facts, batching, bounded overflow recovery and scheduling. `src/pi/budget.ts` reads usage/settings, caches and stages reminders/warnings; `src/budget/policy.ts` only derives pure thresholds and the runway-adjusted countdown. `src/pi/reset/artifacts.ts` constructs ordered drafts and safely repairs incomplete suffixes; `src/pi/reset/committed.ts` separately confirms durable native boundaries. `src/pi/window.ts` owns native markers, checkpoints, branch traversal and provider projection. `src/pi/runtime.ts` wires these parts to public Pi lifecycle hooks, commands and UI.
|
|
4
|
+
|
|
5
|
+
Boot acquisition/rendering is shared: `src/boot/snapshot.ts` receives explicit identity, a captured time and an optional scope loader; `src/boot/render.ts` receives the snapshot and logical tool bindings. Pi supplies its existing names. Shared history is an addressed query projection, never an inference transcript or reset scheduler. There is no generic HostEvent or Harness reducer, and no second commit database.
|
|
6
|
+
|
|
7
|
+
## Lifecycle at a glance
|
|
8
|
+
|
|
9
|
+
| Trigger | Behavior |
|
|
10
|
+
| --- | --- |
|
|
11
|
+
| `clear_memory` tool | Mark the current window tool-requested. At `turn_end`, after the complete tool batch and any accepted budget drafts, append the reset boundary and ask Pi to continue. Repeated requests for that window deduplicate. |
|
|
12
|
+
| `/clear-memory` or `/cm` | Acknowledge immediately and arm a manual close-out. The hidden checkpoint warning always goes out: when idle it starts one ordinary model turn; while streaming it steers the running turn so the agent closes out promptly. The agent may write notes/use tools over several turns; its own `clear_memory` call only acknowledges. A successful normal stop commits at `agent_before_settle` after queued messages drain, and the committed reset stops the run unless a trailing prompt was supplied. With a prompt, append it after the unchanged continuation and request one fresh-window continuation. |
|
|
13
|
+
| Budget warning | When automatic compaction is enabled and remaining active-window budget reaches reserve plus the warning runway, put the same hidden warning in the request and arm an automatic close-out. An explicit `clear_memory` commits the boundary; a successful normal stop alone never resets or requests continuation. |
|
|
14
|
+
| Hard reserve | Independent safety path: if automatic resets are enabled and completed-turn usage reaches Pi's reserve, commit a boundary at `turn_end`. A pending manual stop survives in a run-scoped `stop-pending` phase; empty automatic follow-up is cancelled before provider work, while real queued user input is answered before stopping. |
|
|
15
|
+
| Abort or error | Never count as successful close-out. Abort clears lifecycle state. An ordinary close-out error is dropped without reset. Manual overflow clears and stops without retry, even with automatic reset disabled; automatic provider-overflow recovery remains separately bounded. |
|
|
16
|
+
| `/compact` while active | Cancel native compaction, which could otherwise summarize pre-reset history back into the active window. A manual attempt receives an actionable `/clear-memory` notice. |
|
|
17
|
+
|
|
18
|
+
A new boundary is ordered as:
|
|
19
|
+
|
|
20
|
+
1. A native `compaction` entry with `summary: ""` and `firstKeptEntryId` set to its own ID. This is Pi's retain-none canonical checkpoint; it is not a generated summary request.
|
|
21
|
+
2. A `notesoup/reset-marker` custom entry with `{ windowId }`.
|
|
22
|
+
3. A hidden `notesoup/boot` custom message with matching `details.windowId`.
|
|
23
|
+
4. A hidden continuation message.
|
|
24
|
+
5. If the manual command supplied a prompt, a visible `notesoup/reset-prompt` custom message containing that literal text. Pi boundary drafts do not support ordinary user entries; the prompt is committed with the reset instead of queued separately.
|
|
25
|
+
|
|
26
|
+
The raw session branch is preserved for history. New checkpoint-backed branches use Pi's canonical retain-none projection, which preserves the empty summary wrapper and system/tool state while excluding earlier conversational context. Older marker-only sessions use marker slicing as a narrow compatibility fallback. A marker is trusted as checkpoint-backed only when it directly follows an empty native compaction whose `firstKeptEntryId` is the compaction's own ID; a generic preceding compaction is not enough.
|
|
27
|
+
|
|
28
|
+
`turn_end` is the sole composer for completed turns. It preserves incoming entries, consumes current-window budget drafts, and appends the ordered reset boundary only when the reducer requests one. Direct tool resets and the hard-reserve safety path commit here. `agent_before_settle` commits only manual close-outs after Pi has drained queued work, stopping the run for a bare command or continuing with its appended prompt. A budget close-out without an explicit wipe is discarded at settlement without resetting. Pi owns any ensuing continuation and request scheduling. Reset construction awaits the asynchronous notes snapshot; the handler captures its session/window generation before awaiting, then rechecks generation, session, window, enabled state, and abort status before returning drafts. A stale completion is discarded while incoming/budget entries survive, and success notices are staged only after that guard. Construction failures notify only while the initiating lifecycle is still current and preserve already-collected entries without claiming a continuation.
|
|
29
|
+
|
|
30
|
+
## Reducer state
|
|
31
|
+
|
|
32
|
+
`reduceResetControl` is pure: the adapter supplies all lifecycle facts, and the reducer returns the next state plus a named effect. Its state combines a request phase with a bounded overflow phase:
|
|
33
|
+
|
|
34
|
+
| State | Meaning |
|
|
35
|
+
| --- | --- |
|
|
36
|
+
| `{ phase: "none" }` | No close-out/tool request is pending. |
|
|
37
|
+
| `{ phase: "close-out", windowId, source, prompt? }` | Manual or automatic warning close-out remains armed across ordinary note/tool turns. |
|
|
38
|
+
| `{ phase: "stop-pending", windowId }` | A manual hard-reserve reset was proposed for the given old window. The stop survives a committed window change; settlement stops without a second wipe (or retries construction if the old window is still active). New wipe requests only acknowledge it. |
|
|
39
|
+
| `{ phase: "tool-requested", windowId, source }` | A direct `clear_memory` call commits after its complete turn batch and continues in the fresh window. `source` is `"tool"` for direct calls or `"automatic"` when the agent wipes inside a budget close-out; manual requests never occupy this phase. |
|
|
40
|
+
| `overflow: "idle"` | No overflow recovery is pending. |
|
|
41
|
+
| `overflow: "pending"` | An overflow failure may recover once at pre-settlement. |
|
|
42
|
+
| `overflow: "pending-spent"` | Recovery was already spent in this failure chain. |
|
|
43
|
+
| `overflow: "spent"` | The one recovery has been used until the chain settles. |
|
|
44
|
+
|
|
45
|
+
### Transition rules
|
|
46
|
+
|
|
47
|
+
- `close_out(windowId, source, prompt?)` arms a close-out for that window. Repeating an already-pending request deduplicates and keeps the original prompt (including no prompt); a manual request can upgrade an automatic request for the same window, and a manual request converts a pending tool request into a settle-committed stop.
|
|
48
|
+
- `tool_request(windowId)` marks that window for a turn-end reset. Matching duplicates deduplicate. Inside a budget close-out the call upgrades to a turn-end commit because context pressure cannot wait for settlement; inside a manual close-out it is only an acknowledgement, so a manual wipe is never converted into a turn-end commit that Pi's tool-batch continuation would overrun.
|
|
49
|
+
- `turn_end` first clears everything on abort. Overflow-like errors preserve a manual close-out, including across queued work; other requests arm automatic overflow recovery only when there is no queued work, the extension is enabled, and automatic reset is enabled. Other failures drop the request but preserve the overflow chain. A successful, enabled turn commits for a tool request or hard-reserve condition; a close-out alone remains armed. Bare manual hard-reserve commits request no continuation and retain `stop-pending` across the window change. A manual request with a prompt instead returns the prompt with the commit effect, clears request state, and continues after the prompt is durably appended; it never enters the stop latch. Further turns cannot reset that stopped run again.
|
|
50
|
+
- `agent_before_settle` clears state on actual abort. Pending manual overflow commits a reset without continuation when enabled and unqueued; it does not require automatic reset enablement. Other pending overflow recovery gets its one bounded attempt when enabled and unqueued. A committed `stop-pending` reset needs only a stop, never a second wipe. Otherwise only a manual close-out commits, if the outcome is successful, the request belongs to the current window, the extension is enabled, and no queued work remains. An automatic close-out alone is cleared without a reset.
|
|
51
|
+
- `agent_settled`, session start/tree navigation/shutdown, `/notesoup off`, and abort clear transient request state. Durable checkpoint/marker history remains authoritative after transient state is gone.
|
|
52
|
+
|
|
53
|
+
After a manual safety reset, `context_with_system` verifies the committed checkpoint/marker/boot/continuation before using public `ctx.abort()` to cancel Pi's otherwise unavoidable tool-batch follow-up, returning a system-only safe context. Pending messages or a real user message after the reset marker bypass cancellation so queued work is not swallowed. A follow-up queue may require Pi's ordinary tool follow-up to finish before delivery; the stop intent remains armed until that work settles. Abort/settlement clears the run-scoped latch, so later user prompts work normally.
|
|
54
|
+
|
|
55
|
+
This separation is intentional: a note write or ordinary tool turn during a budget close-out must not consume it. Direct `clear_memory` remains valid without a prior warning. A user abort, an assistant message with a synthetic `stopReason: "aborted"`, and a generic provider error are distinct cases; none commits an ordinary close-out, while only Pi's actual operation cancellation is a user abort.
|
|
56
|
+
|
|
57
|
+
## Budget staging and notifications
|
|
58
|
+
|
|
59
|
+
The early reminder is staged once per window when remaining budget reaches `reserve + reminderMarginTokens`. The final close-out warning is staged/attached at `reserve + WARNING_RUNWAY_TOKENS`, only when automatic compaction is enabled. The hard reserve itself remains a separate safety cutoff. Budget and idle manual requests use the same hidden checkpoint text but distinct message types, so an aborted manual request cannot suppress a later budget warning. The text allows for either reset timing; manual close-outs may span turns and commit at settlement, while budget close-outs commit early only through an explicit `clear_memory` call. After a budget warning is durable, the extension does not repeat it in that window. Warning persistence deduplicates only injection: each eligible low-budget request re-arms transient automatic close-out before checking for the durable warning, so an abort/error can clear its attempt and the next request can retry without another warning.
|
|
60
|
+
|
|
61
|
+
Budget drafts are instance-local and are consumed at turn end. They are discarded on abort, failed turn, transition, or window mismatch. UI reminder notices are emitted only after the matching hidden entry is durable, so failed requests do not report an uncommitted warning. Active-window usage and the exact `SettingsManager` authority drive threshold checks; default file-backed policy is cached per extension instance, while injected managers are read through their public API.
|
|
62
|
+
|
|
63
|
+
## Projection, repair, and history
|
|
64
|
+
|
|
65
|
+
`context_with_system` selects the active boot by durable `details.windowId`. For a verified native checkpoint, Pi's canonical projection is used directly; for a legacy marker-only reset, the compatibility projection slices at the matching boot. The projection preserves system/tool state and later prompt patches. If the boot is absent, the runtime aborts safely instead of sending raw history. Usage estimation uses the same checkpoint-aware projection decision.
|
|
66
|
+
|
|
67
|
+
Commit confirmation and repair are different native facts. `resetBoundaryCommitted` validates a checkpoint-backed marker followed by its matching hidden boot and hidden continuation; later conversation does not undo that commit. `inspectResetTail` instead asks whether the entire suffix remains safe to repair, refusing later conversation, foreign messages, later markers or misordered/duplicate artifacts. UI success notices use confirmation, not the repair predicate, and remain committed-only.
|
|
68
|
+
|
|
69
|
+
Startup/tree repair is narrow: it may complete a repairable marker tail when later conversation does not make the missing metadata ambiguous. It awaits the notes snapshot and rechecks lifecycle/window identity before sending a repaired boot or continuation. Legacy marker-only tails remain supported; repair never moves a boundary or promotes an arbitrary compaction to a retain-none checkpoint. `/tree` summary generation is suppressed with an empty summary when either branch crosses a reset, because the raw summary generator bypasses the provider projection.
|
|
70
|
+
|
|
71
|
+
## Validation and known limits
|
|
72
|
+
|
|
73
|
+
The test suite combines isolated reducer tests with scripted SDK tests executing Pi's real agent loop without model/network calls. The retained scripted AgentSession tests cover idle and streaming manual commands whose close-outs commit at settlement and stop without a fresh-window continuation, direct wipe without warning, budget close-out, same-window concurrent command deduplication, actual and synthetic abort/error cleanup, queued steering/follow-up delivery before the stop, hard-reserve and bounded-overflow recovery, successive resets, and real SessionManager file reopen after two retain-none checkpoints. It also checks raw-history preservation, canonical projection, empty-summary retention, system/tool state, warning/marker order, and fresh-window continuation.
|
|
74
|
+
|
|
75
|
+
Focused regression tests distinguish committed-boundary confirmation from safe suffix repair even after later work. Resolved-AST dependency tests reject shared imports of native adapters and SDKs, including indirect type/re-export/dynamic paths. Retained behavioral cases are representative rather than exhaustive. Tree-summary suppression has no dedicated retained test, and external-provider behavior, every malformed persisted shape, and every filesystem failure mode are not established by this suite.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# SDK integration
|
|
2
|
+
|
|
3
|
+
SDK hosts that create a session directly can bind notesoup to the exact same public `SettingsManager` authority as the session:
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import {
|
|
7
|
+
createAgentSession,
|
|
8
|
+
DefaultResourceLoader,
|
|
9
|
+
SettingsManager,
|
|
10
|
+
} from "@earendil-works/pi-coding-agent";
|
|
11
|
+
import { createNotesoup } from "notesoup";
|
|
12
|
+
|
|
13
|
+
const cwd = process.cwd();
|
|
14
|
+
const agentDir = "/tmp/my-pi-agent";
|
|
15
|
+
const settingsManager = SettingsManager.inMemory({
|
|
16
|
+
compaction: { enabled: true, reserveTokens: 16_384 },
|
|
17
|
+
});
|
|
18
|
+
const resourceLoader = new DefaultResourceLoader({
|
|
19
|
+
cwd,
|
|
20
|
+
agentDir,
|
|
21
|
+
settingsManager,
|
|
22
|
+
noExtensions: true,
|
|
23
|
+
extensionFactories: [createNotesoup({ settingsManager })],
|
|
24
|
+
});
|
|
25
|
+
await resourceLoader.reload();
|
|
26
|
+
|
|
27
|
+
const { session } = await createAgentSession({
|
|
28
|
+
cwd,
|
|
29
|
+
agentDir,
|
|
30
|
+
settingsManager,
|
|
31
|
+
resourceLoader,
|
|
32
|
+
});
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
The root entry exports only the default Pi extension and `createNotesoup`. This is a breaking source/API refactor: `NotesContext` is replaced by `NotesIdentity`; old internal export bags, root history helpers and the `./dist/src/index.js` export alias are removed. Import the root for Pi integration and `/notes` for the standalone library. The configured dream executable is now `dist/src/pi/dream/cli.js`. Stored notes, session paths, metadata and raw histories are unchanged; no migration runs.
|
|
36
|
+
|
|
37
|
+
The manager must be shared by the resource loader's factory and `createAgentSession`. If the host replaces its settings authority, it must create and bind a new `createNotesoup({ settingsManager })` factory together with the replacement manager; an existing factory remains bound to the manager it was created with.
|
|
38
|
+
|
|
39
|
+
The default extension export is file-backed: it reads Pi's standard global settings directory plus the trusted project's `.pi/settings.json`, with project values winning per key. It cannot discover an arbitrary SDK session manager from `cwd`, environment variables, session IDs, or private SDK fields. For an injected manager, compaction settings come from the manager's public `getCompactionSettings(model)` getter, including the active model's `modelOverrides`; notesoup margins are read from the public `getGlobalSettings()` and `getProjectSettings()` scopes. Opaque runtime overrides that those public scope getters do not expose are intentionally not treated as notesoup configuration. Live public manager changes apply on the next policy query/turn, and the extension does not drain the manager's settings I/O diagnostics.
|
package/docs/skills.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Skills, dream, and the notes doctor
|
|
2
|
+
|
|
3
|
+
## Memory skill
|
|
4
|
+
|
|
5
|
+
The package provides `/skill:memory`, a short self-contained guide to the notes and history tools: note addresses and homes, finding and paging notes, searching and paging history, saving recovery state, and what to do when a memory tool is unavailable. It is a fallback for sessions where the boot protocol is missing or unclear and a reference on demand; normal tool calls do not require reading it. It is written independently of the boot text rather than generated from it. The Claude Code Mod does not ship it, because that host has no history tools.
|
|
6
|
+
|
|
7
|
+
## Dream skill
|
|
8
|
+
|
|
9
|
+
The package also provides `/skill:dream` for reviewing notes in the current agent session. The skill reads the same `playbook.md` used by the `dream` CLI; there is only one set of dream instructions.
|
|
10
|
+
|
|
11
|
+
Scope comes from the invocation directory: inside the notes store, dream may inspect across homes; in a project, it extracts from that project's material and all session notes with matching project metadata, and organizes only that project's notes. New session notes record their project key in the frontmatter `project` field. Standard linked Git worktrees resolve to the main checkout's repository root, sharing its project key and `@project/` home. Older metadata and homes remain untouched by the code: there is no automatic migration or backfill; existing data can be migrated manually. Notes without project metadata are skipped in project-only discovery. Changing directories later does not broaden the scope.
|
|
12
|
+
|
|
13
|
+
The skill stays in the current agent session. Its wrapper and shared playbook describe the dreamer's task, not runtime setup: the execution entry point is responsible for supplying readable/writable scope and establishing write permission, including locking and Git audit safeguards. The CLI supplies its own safeguards; the bare skill does not install them. Without an established scope and write permission, the dreamer asks rather than improvising runtime setup. Session records and unapproved homes stay untouched.
|
|
14
|
+
|
|
15
|
+
## Check the notes store
|
|
16
|
+
|
|
17
|
+
Run `dream doctor` (or `dream doctor --notes-home <dir>`) to check home layout, note frontmatter, concrete backtick-quoted note addresses, MAP entries, and lock presence/format. It is read-only: no model, git commits, directory creation, or repairs. Exit status is 0 when clean and 1 when issues are found. References needing an unavailable project context are reported as unresolved; prose and example/glob addresses are not validated. A present lock is reported without inferring process liveness.
|
|
18
|
+
|
|
19
|
+
## The dream lock
|
|
20
|
+
|
|
21
|
+
The `dream` CLI takes an exclusive `.dream.lock` in the notes home with a single O_CREAT|O_EXCL creation. The lock is Git-style existence locking: an existing lock refuses a new run regardless of its contents, PID, or age, and `--force` bypasses only the scheduling and material gates, never the lock. A lock is released only by the run that acquired it (and repeated cleanup is harmless), so a live dream is never displaced.
|
|
22
|
+
|
|
23
|
+
If a dream process crashed, its lock remains and later runs refuse to start. There is no automatic recovery and no force-unlock command: after you have confirmed that no dream process is running, remove the stale lock by hand.
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
# only when no dream is running
|
|
27
|
+
rm "${PI_NOTES_HOME:-$HOME/.agents/notes}/.dream.lock"
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Removing a lock while a holder is running is outside the supported cooperative protocol and can let two dreams run at once.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# Notes and history tool results
|
|
2
|
+
|
|
3
|
+
The eight notes/history tools have one business result model. Pi exposes compact results as `structuredContent` to codemode and renders them as `content` for ordinary model calls. Claude uses the same business handlers and text rendering. Neither host re-runs a query, truncates a different page, or parses formatted text to recover data.
|
|
4
|
+
|
|
5
|
+
This is a breaking tool protocol change: successes no longer have `ok/data` wrappers, errors are flat, and read fields no longer sit under `window`. History execution details live once in the pageable document. Stored notes and raw Pi session entries are not deleted or rewritten by this change. `clear_memory` and `get_context_remaining` are outside this protocol.
|
|
6
|
+
|
|
7
|
+
## Results
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
type Result<T> = T | { error: string; code: string };
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Each operation declares its concrete success schema; `error` is reserved for a refusal message. Success and expected failure both have a structured result; Pi's `isError` follows the outcome. Host-level argument validation, blocked execution and transport errors remain host failures. Shared handlers and the private Claude helper transport retain an internal `Outcome<T>` (`{ ok: true, data }` or `{ ok: false, error: { code, message } }`); this envelope is not the Pi wire result. The Claude hook returns rendered text as a string result and sets `isError: true` only on a refusal.
|
|
14
|
+
|
|
15
|
+
```js
|
|
16
|
+
const result = await tools.notes_list({ glob: "@project/**" });
|
|
17
|
+
if ("error" in result) return result.error;
|
|
18
|
+
return result.files;
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The text representation uses short mutation receipts, lists, search hits or raw text windows. It reports omissions and errors rather than hiding them. A refusal renders as one line, `error: <code>: <message>`, and the message carries every fact a caller needs to recover: the known window ids for `unknown_window_id`, the edit index and match lines for a note edit refusal.
|
|
22
|
+
|
|
23
|
+
## Read windows
|
|
24
|
+
|
|
25
|
+
Both read operations return these fields at the result root, alongside identity and metadata:
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
{
|
|
29
|
+
text: string;
|
|
30
|
+
total_chars: number;
|
|
31
|
+
next_offset_chars: number | null;
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Positions count Unicode code points, not UTF-16 units or UTF-8 bytes. The returned text is a contiguous unmodified prefix of the requested range, without ellipsis markers. `next_offset_chars` names the first undelivered character, or is null at the true end. A negative input offset selects a tail; the delivered window does not echo the offset it resolved.
|
|
36
|
+
|
|
37
|
+
- `notes_read`: `address`, optional `project_key`, and `metadata` accompany the text fields. Positions address only the note **body**. Access counts and last-access times remain stored but are omitted from results.
|
|
38
|
+
- `history_read`: `seq`, `window_id`, `role`, `created_at`, and a tool summary accompany the text fields. Positions address one deterministic document derived from the event's facts. Query matches address that same document, not its decorated presentation.
|
|
39
|
+
|
|
40
|
+
Repeated note reads observe the current file; this is not a retained snapshot service. A concurrent body edit can change positions. History reflects the active branch and recorded facts, including a result that may arrive after a pending call was first observed.
|
|
41
|
+
|
|
42
|
+
Text rendering puts identity and relevant metadata above the payload. Only an incomplete read receives a continuation suffix, which says where to continue and nothing about why the window stopped:
|
|
43
|
+
|
|
44
|
+
```text
|
|
45
|
+
[truncated; continue at offset_chars=12000]
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The suffix and presentation header are never part of `text`, search offsets or total character counts. At the end there is no completion footer.
|
|
49
|
+
|
|
50
|
+
## History identity and execution evidence
|
|
51
|
+
|
|
52
|
+
The native adapter allocates seqs from session append order, selects the active branch and decodes facts. Shared history pairs calls and results without allocating a second transcript. A paired execution is addressed by its call seq. Its result's raw slot is not a public event address; list/search provide the canonical seq. Unpaired results remain independently addressable. Inactive-branch addresses are not readable.
|
|
53
|
+
|
|
54
|
+
Tool events expose `tool`, `tool_status`, and, when recorded, `output_truncated` and `full_output_path`; a truncated run is named even when the host recorded no path, and the full text path is named only when it exists. `history_read` also reports `nested_calls`; a page row does not. Full arguments and nested-call records live only in the searchable/readable document, avoiding a second structured copy on every read.
|
|
55
|
+
|
|
56
|
+
Pi's nested records contain child ID, name, optional arguments, status, timing and error, plus completeness. They contain **no child result bodies**. Absent records do not establish that no nested work occurred. Host-omitted arguments and unfinished calls remain visible as incomplete evidence. Child records belong to their parent event and do not consume seqs.
|
|
57
|
+
|
|
58
|
+
`history_read` reports `nested_calls.call_count` and `nested_calls.complete` exactly as recorded: the count is every record the host stored, even if the current text slice contains none of them. Continue with `next_offset_chars` to recover the entire recorded document. Both a call's result and an unpaired result carry their recorded evidence; neither invents the call the other one is missing. Query results contain event rows only; folded rows exist only in the browse view.
|
|
59
|
+
|
|
60
|
+
## Bounds and continuation
|
|
61
|
+
|
|
62
|
+
One selection determines the structured result and its text. Both complete representations must fit the 32 KiB output budget, including metadata, cursor and rendered notice. A programmatic caller does not receive an unbounded hidden payload beside a truncated textual one.
|
|
63
|
+
|
|
64
|
+
History pages carry `page_older` and `page_newer`, the exact params to merge into the next call; `from` picks which end of a bounded range `limit` counts from, `since`/`until` narrow that range by event `created_at`, and only a call without roles or query folds tool/context runs. Notes listings/search are snapshots with a `more` count and can be narrowed by `glob`; they are not falsely advertised as paginated. `history_windows` is a snapshot too: its `more` counts the windows the budget left out and there is no window cursor, because `history_list` rows also expose `window_id`. A read can stop anywhere in the event document, including inside serialized arguments; concatenate its verbatim text slices before parsing any arguments. There is no separately truncated arguments object.
|
|
65
|
+
|
|
66
|
+
A note read reports unrecognized frontmatter under `metadata.extra`; a value too large to carry, or past the verbatim budget, is named in place as `[omitted: too large]` under its key rather than delivered in part, and the value itself stays in the note file. A rename receipt uses `address` for the destination and `rename_from` for the source; it has no duplicate `rename_to` field.
|
|
67
|
+
|
|
68
|
+
`output_too_large` is not one failure, and a refusal does not mean nothing happened. Each operation's own message says what it means: a `notes_update` whose receipt cannot fit reports that the update was already applied, so read the note before retrying, and a read that cannot deliver a single advancing character is refused rather than answered with an empty window. A receipt whose diff or search-match line cannot fit is cut to the longest prefix that does, and its own text ends with the marker: `[diff truncated; update applied]` for a diff, ` [truncated]` for a match line. Narrowing helps only where a parameter genuinely reduces the selection — `glob` or `query`, `roles`, `window_id`, `limit`, `max_chars_per_item`, a `before_seq`/`after_seq` range, or a `since`/`until` time window — and cannot help a read whose own metadata is what overflows. History pages refuse with `page_too_large` for the same reason. Nothing is ever quietly delivered short: every other omission is reported on the successful result that carries it.
|
|
69
|
+
|
|
70
|
+
## Ownership
|
|
71
|
+
|
|
72
|
+
- The notes store owns addressing, file contents, metadata and mutations.
|
|
73
|
+
- The history adapter owns native decoding, seq allocation and branch visibility.
|
|
74
|
+
- Shared operations own the typed result, filtering, paging, character windows and refusal messages.
|
|
75
|
+
- Shared renderers derive text from that result.
|
|
76
|
+
- Pi/Claude adapters supply host identity, projections and transport packaging only.
|
|
77
|
+
|
|
78
|
+
There is no second query implementation for codemode, no copy of session storage and no migration of user records.
|