@aeondave/pi-persona-mind 0.9.2 → 0.9.4

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/AGENTS.md CHANGED
@@ -9,7 +9,7 @@ coupled through a versioned local companion handshake to
9
9
  - Typecheck: `npm run typecheck` (`tsc --noEmit`, strict + `exactOptionalPropertyTypes`)
10
10
  - Tests: `npm test` · both: `npm run verify`
11
11
  - Hermetic choke point: `node --import tsx --import ./test/setup/hermetic-env.ts --test test/*.test.ts`
12
- - Installed Pi 1.5.2 qualification: `node --import tsx scripts/qualify-host.mjs <absolute-pi-package-root> <absolute-pi-persona-extension-path> [<absolute-packed-mind-extension-path>]`
12
+ - Installed Pi 1.6.0 qualification: `node --import tsx scripts/qualify-host.mjs <absolute-pi-package-root> <absolute-pi-persona-extension-path> [<absolute-packed-mind-extension-path>]`
13
13
  (isolated profile, offline synthetic provider; no cloud authentication/model-quality claim).
14
14
 
15
15
  ## Conventions
@@ -17,7 +17,7 @@ coupled through a versioned local companion handshake to
17
17
  - User-requested commits use **AeonDave** as both author and committer, retaining the user's configured
18
18
  email. Never add `Co-authored-by` or assistant/bot attribution; do not push unless explicitly requested.
19
19
  - Erasable-syntax-only TS. `src/core/*` is pure (no Pi imports) and unit-tested.
20
- - Target the latest stable Pi only (currently 1.5.2), Node 22.19.0+. Keep host packages and
20
+ - Target the latest stable Pi only (currently 1.6.0), Node 22.19.0+. Keep host packages and
21
21
  typebox as optional peers on `*`, with all four Pi development packages pinned together.
22
22
  No historical-host branches; never bundle a second host runtime. Scope development security
23
23
  overrides to their affected parent/version and remove them when that graph no longer needs them.
@@ -71,7 +71,10 @@ coupled through a versioned local companion handshake to
71
71
  completed digests, but interrupted explicit work never grants automatic retry. Usage alone never
72
72
  marks memories dirty. Coalesce 2s after `agent_settled` while idle with no queued
73
73
  work; cool down 5min between actual attempts. Only the interrupted attempt can retry without the
74
- token floor, after a later settled event and cooldown. One worker per instance; unchanged semantic
74
+ token floor, after a later settled event and cooldown, once per unchanged input digest; a second
75
+ interruption parks that window (bypassed by rotation, never settled) until its records change, and a
76
+ `failed` worker result is terminal for its input. A skipped window never settles another window's
77
+ pending retry: that retry is dropped without a receipt when its own input is gone, else stays owed. One worker per instance; unchanged semantic
75
78
  digests skip review. New input, agent start,
76
79
  off or owner changes cancel and invalidate plans. Use a real visible
77
80
  Persona-hosted Mind worker on exactly the session model, no fallback or arbitrary tools. Give it
@@ -100,10 +103,19 @@ coupled through a versioned local companion handshake to
100
103
  - Rotate completed automatic review over older records/pages; account for actual byte admission,
101
104
  preserve newest-fact inclusion, and never mark stopped/interrupted work as completed. No unbounded
102
105
  sweeper. Optimizer receipts precede replacement and persist at most 32/2MiB per target; unresolved
103
- prepared receipts are protected. Undo compares affected facts and owner generation under lock,
106
+ prepared receipts are protected unless the store still holds the bytes they were prepared against
107
+ (then the replacement is not in effect and they settle rejected; same store, owner and target only). Undo compares affected facts and owner generation under lock,
104
108
  never restores expired STM or clobbers unrelated writes. Propagate uncertain-finalization warnings.
105
- - Retrieval uses one lexical/tag/path ranker; do not introduce a second recall policy. All injected
106
- tiers share a 2400-token planning estimate (UTF-8 bytes/3); session notes use up to 600. Include
109
+ - Retrieval uses one lexical/tag/path ranker; do not introduce a second recall policy. Matches preserve Unicode and exact-term priority; identifier/vowel-accent bridges have lower weight.
110
+ Keep numeric versions exact and retain negation/exception terms. Test false positives as well as hits.
111
+ Ordinary `remember supersedes` receipts share the optimizer's history/CAS protocol and retain
112
+ before/after provenance. Historical facts never join active recall or injection; ordinary receipt
113
+ undo is refused. History lists metadata and explicit receipt details are paged, not full-store dumps.
114
+ Explicit handoffs use one bounded project sidecar (32 entries per persona, 128 KiB for the file) with persona ownership,
115
+ native session/branch origin and revision checks. No automatic expiry/eviction, injection or worker
116
+ access. Complete requires a resolution; pending text remains historical. Recheck accepting owners
117
+ under the store lock and reject malformed/unsafe persisted fields.
118
+ All injected tiers share a 2400-token planning estimate (UTF-8 bytes/3); session notes use up to 600. Include
107
119
  wrappers, separators and omission counts, keep whole excerpts, and never exempt pinned facts from
108
120
  the bound. The estimate and synthetic evaluation are not billing or semantic-quality guarantees.
109
121
  - `exactOptionalPropertyTypes`: omit optional props; do not assign `undefined`.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,58 @@
1
1
  # Changelog
2
2
 
3
- ## [Unreleased]
3
+ ## [0.9.4](https://github.com/AeonDave/pi-persona-mind/releases/tag/v0.9.4) - 2026-11-23
4
+
5
+ - A memory replacement or consolidation refused before anything was written (a full store, a lock
6
+ timeout, any failure that left the memory unchanged) no longer leaves a permanent `prepared` receipt.
7
+ Thirty-two of them used to block every later replacement and consolidation on that store. Receipts
8
+ left prepared by earlier versions carry no store fingerprint and stay protected, so a store already
9
+ holding 32 of them still refuses replacements until its history file is repaired by hand.
10
+ - Words after a dotted version are searchable again: `node:22.19-alpine` matches `alpine`, `3.12-slim`
11
+ matches `slim`. Numeric versions stay exact (`22.19` still does not match `22.19-alpine`), and a tail
12
+ word is never treated as a negation.
13
+ - Automatic memory review retries an interrupted input once, not on every turn. A second interruption
14
+ parks that window until its records change, and rotation moves past it instead of stopping there.
15
+ Turning automatic review off and on no longer resets the count. When a review is parked, the status
16
+ line says so and a result card reports that it was interrupted twice. A worker that reaches its
17
+ 180-second deadline is a failure and is not retried with pi-persona 1.20.0 or later, which reports it
18
+ as failed; earlier pi-persona versions report it as a stop, so it is retried once and then parked.
19
+ - A skipped review window no longer marks another window's pending retry as reviewed. An input whose
20
+ review was interrupted could be recorded as settled when rotation reached a different window, so it
21
+ was never reviewed. The retry is now kept, or dropped without a receipt when its own records are gone.
22
+ - The 32-handoff limit is per persona. One persona's handoffs no longer stop the others from saving;
23
+ only the 128 KiB file limit is shared, and a save it refuses says how many entries the caller and the
24
+ other personas hold. Handoff refusals for an unreadable file say what is wrong with it (unsafe path, size,
25
+ version, missing with a backup, corrupt or inaccessible), name the file and no longer mention optimizing.
26
+ - `remember` with `supersedes` is no longer blocked by a corrupt memory tier it does not write to, when
27
+ that tier recovers completely from its backup. It still refuses, naming the store, when another tier
28
+ cannot be read completely, because that tier could hide the fact being replaced. A backup that exists
29
+ but cannot be used is now reported as a warning on every read instead of being treated as absent.
30
+ - Session shutdown waits at most 5 seconds for a Persona worker's completion; local apply and
31
+ persistence work is still joined in full.
32
+ - The memory evaluation reports held-out false positives both strictly and with its acceptable-match
33
+ labels (5 and 5 strictly; 5 and 3 with labels), and states that the held-out set was written alongside
34
+ the implementation.
35
+
36
+ ## [0.9.3](https://github.com/AeonDave/pi-persona-mind/releases/tag/v0.9.3) - 2026-11-22
37
+
38
+ - Improve lexical recall for camelCase/acronyms and vowel accents with weaker fallback scores;
39
+ preserve Unicode, exact paths, numeric versions and negation. Extend the offline evaluator with
40
+ the preceding implementation, negative controls and a separate labelled holdout.
41
+ - Retain before/after receipts for ordinary explicit memory replacements in the existing bounded
42
+ history. Discover them with `memory history` or `/mind history`, then page the full retained detail.
43
+ Historical facts stay outside active recall; ordinary replacement undo is deliberately unavailable.
44
+ - Add explicit project/persona handoffs with goals, completed/pending work, next steps, references
45
+ and native session/branch provenance. Read them in later sessions; completion and forgetting require
46
+ the current revision. No automatic expiry, injection, model call or worker restoration is involved.
47
+ - Target and qualify Pi 1.6.0, keeping all four development host packages aligned and unbundled.
48
+ - Recheck the accepting memory owner and replacement expiry under the write lock. Refuse malformed
49
+ history/handoff records, keep discovery output bounded, and distinguish branch navigation from
50
+ ordinary native-session appends.
51
+
52
+ - Preserve recording provenance and lineage when an identical memory is recorded again without
53
+ replacement metadata.
54
+ - Refuse `remember` replacements whose `supersedes` target exists only in another memory tier,
55
+ instead of reporting success while keeping both facts active. No cross-tier deletion is implied.
4
56
 
5
57
  ## [0.9.2](https://github.com/AeonDave/pi-persona-mind/releases/tag/v0.9.2) - 2026-11-18
6
58
 
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  <h1 align="center">pi-persona-mind</h1>
2
2
 
3
3
  <p align="center">
4
- <img src="https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.9.2/assets/banner.png" alt="pi-persona-mind — durable memory for Pi">
4
+ <img src="https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.9.4/assets/banner.png" alt="pi-persona-mind — durable memory for Pi">
5
5
  </p>
6
6
 
7
7
  [![CI](https://github.com/AeonDave/pi-persona-mind/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/AeonDave/pi-persona-mind/actions/workflows/test.yml)
@@ -12,12 +12,15 @@
12
12
  and deferred work without turning every conversation into permanent memory.
13
13
  Mind complements Pi's native conversation history and compaction; it does not replace them.
14
14
 
15
+ ## Features
16
+
15
17
  | What you need | What Mind provides |
16
18
  |---|---|
17
- | Continue a long project | Durable repository decisions, scoped preferences and session notes that survive compaction |
18
- | Keep context focused | Bounded retrieval by words, tags and paths, with explicit full-record reads |
19
+ | Continue a long project | Durable repository decisions, session notes and explicit handoffs for the next session |
20
+ | Keep context focused | Bounded retrieval by words, code identifiers, tags and paths, with explicit full-record reads |
19
21
  | See what the agent remembers | **F10**: saved facts, prepared context and an active-branch timeline |
20
22
  | Maintain a growing archive | Bounded consolidation, evidence-grounded review, change history and guarded undo |
23
+ | Understand a changed decision | Retained before/after records for explicit replacements, kept out of active recall |
21
24
 
22
25
  Memory is stored in local files and Pi's native session history. Recall and browsing need no model
23
26
  call. [Automatic consolidation](#quiet-automatic-maintenance) is on by default; it and explicit
@@ -25,7 +28,7 @@ knowledge reviews use the current session model and incur model usage.
25
28
 
26
29
  ## Quick start
27
30
 
28
- Mind 0.9.2 requires **Pi 1.5.2**, **Node.js 22.19.0+**, and
31
+ Mind 0.9.4 requires **Pi 1.6.0**, **Node.js 22.19.0+**, and
29
32
  [**pi-persona 1.18.1+**](https://github.com/AeonDave/pi-persona) loaded in the same instance.
30
33
 
31
34
  ```bash
@@ -49,6 +52,7 @@ Try asking your agent:
49
52
  - “Remember this preference across projects for this persona.”
50
53
  - “Put the blocked migration in the backlog and remind me tomorrow.”
51
54
  - “Recall the decision about retries and show the complete saved record.”
55
+ - “Save a handoff with the goal, completed work, remaining work, next step and references.”
52
56
 
53
57
  Press **F10** to inspect what Mind has saved and prepared. Use **`/mind`** for a snapshot,
54
58
  **`/mind help`** for commands and **`/mind doctor`** for effective settings and storage warnings.
@@ -78,8 +82,10 @@ project injection and reminders. See [lifetimes and scope](docs/DESIGN.md#four-l
78
82
 
79
83
  ## Retrieval and inspection
80
84
 
81
- Mind selects relevant excerpts each turn within one shared context budget. Words, tags and paths
82
- drive retrieval; lexical matching can miss paraphrases or conflicting facts. Use `memory recall`
85
+ Mind selects relevant excerpts each turn within one shared context budget. Exact words and paths
86
+ receive more weight than matches across code identifiers (`HTTPResponseParser` → “HTTP response parser”)
87
+ and vowel accents (`café` → “cafe”). Unicode text remains searchable. This is lexical retrieval;
88
+ it can miss paraphrases or conflicting facts. Use `memory recall`
83
89
  to search and `memory read` to inspect a complete record. The budget is an estimate, not a billing counter.
84
90
 
85
91
  **F10** toggles the read-only inspector in the interactive TUI:
@@ -101,6 +107,12 @@ windows keep the selection visible, and **?** opens help. See the
101
107
 
102
108
  ## Maintain knowledge deliberately
103
109
 
110
+ **Decision history** keeps the previous fact when an explicit replacement retires it. Use
111
+ `/mind history project-long` to find a receipt and `/mind history show <receiptId> project-long`
112
+ to inspect its before/after records. Old facts stay out of active recall and injected context.
113
+ History is bounded; ordinary replacements are inspectable, while guarded undo applies to consolidation.
114
+ [History and retention →](docs/DESIGN.md#replacement-history)
115
+
104
116
  **Consolidation** merges compatible saved facts and applies validated changes. `/mind optimize`
105
117
  reviews one bounded window per allowed project/persona tier; `/mind optimize project-long` selects
106
118
  durable project memory alone. Inspect changes with `/mind optimize history`; `/mind optimize undo`
@@ -136,6 +148,19 @@ session. `PI_PERSONA_MIND_OPTIMIZE=off` disables automatic optimization at start
136
148
  with `PI_PERSONA_MIND_CAPTURE=auto|prompt|off`, and `PI_PERSONA_MIND_NUDGE=off` disables suggestions.
137
149
  See [automatic review](docs/DESIGN.md#automatic-semantic-review) for admission and cost details.
138
150
 
151
+ ## Hand off a long task
152
+
153
+ Ask the agent to save a handoff before switching sessions. It records the goal, completed work,
154
+ pending work, next step and references, together with the originating session and branch.
155
+ In a new session with the same project and persona, use **`/mind handoff list`** and
156
+ **`/mind handoff show <id>`** to consult it.
157
+
158
+ A handoff is an explicit work snapshot, not proof that a task is complete. It is never injected or
159
+ executed automatically. Completion requires a resolution; forgetting is explicit. Each persona can hold
160
+ up to 32 handoffs in a bounded project file (128 KiB for the whole file), with no automatic expiry or
161
+ eviction.
162
+ [Commands, ownership and limits →](docs/DESIGN.md#cross-session-handoffs)
163
+
139
164
  ## Learn more
140
165
 
141
166
  - [Design: lifetimes, storage, limits, commands and safeguards](docs/DESIGN.md)
package/docs/DESIGN.md CHANGED
@@ -9,7 +9,7 @@ the user workflow is in [README](../README.md). Local design rationale and evalu
9
9
  This design contract describes the current development tree; released changes are recorded separately
10
10
  in CHANGELOG.md.
11
11
 
12
- Target the latest stable Pi only, currently 1.5.2, and Node >=22.19. All four development Pi packages
12
+ Target the latest stable Pi only, currently 1.6.0, and Node >=22.19. All four development Pi packages
13
13
  are pinned together; runtime host/typebox packages remain optional wildcard peers. No second host
14
14
  runtime or historical hook-shape adapter is bundled. A development-only security override does not
15
15
  patch an installed host.
@@ -17,7 +17,7 @@ patch an installed host.
17
17
  Mind requires a loaded compatible pi-persona through its versioned local companion handshake.
18
18
  Missing/incompatible presence leaves tools inactive and suppresses capture, storage/import,
19
19
  injection and reminders. A settings file or installed npm package is not proof of an active
20
- companion. Mind 0.9.2 requires Persona 1.18.1 or later for these paired contracts. Its optional npm
20
+ companion. Mind 0.9.4 requires Persona 1.18.1 or later for these paired contracts. Its optional npm
21
21
  peer declares that requirement without auto-installing or activating another extension.
22
22
 
23
23
  The node-only core has no Pi imports. The factory wires native Pi hooks, tools, scope, scheduling
@@ -35,6 +35,7 @@ Command parsing/presentation lives outside the factory. Important seams:
35
35
  | core/session-memory.ts, session-memory.ts | Session event validation/replay and native owner adapter |
36
36
  | core/optimize.ts, optimize-service.ts | Pure consolidation rules and short-lived staged plans |
37
37
  | core/optimize-history.ts | Bounded durable before images and conflict-checked undo |
38
+ | core/handoff.ts, handoff-store.ts | Explicit scoped handoff snapshots, revision checks and bounded persistence |
38
39
  | core/retrieval.ts, context-budget.ts | Explainable task ranking and shared context estimate |
39
40
  | core/memory-read.ts | Full explicit retrieval without clipped discovery or recovery writes |
40
41
  | tools/memory.ts, memory-optimize.ts | Model-facing action validation and result formatting |
@@ -57,7 +58,12 @@ recall frequency. Read operations do not boost ranking or reset expiry. `term` a
57
58
  `kind: objective` is not automatically promoted, so a short objective remains expiring project context
58
59
  and a session objective remains on that active native session branch.
59
60
 
60
- Supersession retires an active row. derivedFrom stores bounded IDs. Optimizer before images provide
61
+ Exact re-recording preserves existing `source`, `derivedFrom` and `supersedes` when no replacement
62
+ metadata is supplied; nonempty replacement metadata updates the corresponding value. In `remember`,
63
+ an empty source or empty `derivedFrom` list is treated as omitted, not as a request to clear provenance.
64
+ `remember` supersession retires an active row in its selected destination tier. A target found only
65
+ in another tier is refused before writing; moving a fact and replacing one are separate operations.
66
+ derivedFrom stores bounded IDs. Optimizer before images provide
61
67
  bounded recoverability; ordinary supersession/forget are not a temporal database or unlimited undo.
62
68
  Every long-term `remember` requires an explicit destination: project LTM, persona LTM, or shared LTM;
63
69
  there is no implicit persona destination. Short-term memory remains project-scoped by default. Promotion
@@ -116,6 +122,68 @@ with excerpts of at most 700 characters. It shares the total memory budget. Curr
116
122
  precedes recency, with objective priority. Omitted entries and clipping are disclosed. Explicit read returns the whole note.
117
123
  An in-memory session is not advertised as restart-durable.
118
124
 
125
+ ## Cross-session handoffs
126
+
127
+ `memory { action: "handoff", handoff: { operation: "save", goal, completed, pending, nextStep,
128
+ references } }` stores an explicit snapshot. `completed`, `pending` and `references` are arrays of
129
+ strings. `list` discovers metadata; `read` with `id` returns the snapshot. `complete` requires `id`,
130
+ the latest `revision` and a `resolution`; `forget` requires `id` and `revision`. These actions share
131
+ the existing memory tool, not another tool or model service. `/mind handoff list`,
132
+ `/mind handoff show <id>`, `/mind handoff complete <id> <revision> <resolution>` and
133
+ `/mind handoff forget <id> <revision>` provide operator access.
134
+
135
+ Handoffs belong to the actual project and active persona, with the native source session/branch
136
+ and cwd recorded as provenance. A later independent session may explicitly read the same owner's
137
+ handoff. Home sessions and delegated workers cannot access this surface. The live owner is checked
138
+ before IO, after reads and under the write lock; branch/session changes revoke pending operations.
139
+ Stored content is untrusted, scanned and fenced. References remain literal strings, never automatic
140
+ file reads or tool instructions.
141
+
142
+ One `<STM store>.handoffs.json` sidecar is shared by all personas with owner-filtered access. Each
143
+ owner (persona + project) may hold up to 32 entries; the file as a whole is capped at 128 KiB, which is
144
+ its only total bound. Each record, including metadata, is limited to 16 KiB; the normal store backup
145
+ also applies. Listing uses 160-character goal previews and a 40 KiB formatted-output bound. Explicit
146
+ full reads are bounded to 100 KiB after JSON escaping; neither path silently truncates stored records.
147
+ There is no TTL or automatic eviction: at its own quota, a persona's new save fails until it forgets
148
+ one of its handoffs. A save refused by the file-wide byte cap reports the caller's own entry count and
149
+ the other personas' count, never their names, ids or content; when the other personas' entries alone
150
+ fill the file, the refused persona cannot free space itself. A sidecar that cannot be read strictly
151
+ refuses every handoff operation with a message naming the file (and its `.bak` when that is the remedy). Completion increments the revision and records a resolution; earlier pending work remains
152
+ historical. It does not verify tests, execute pending tasks or claim a restored worker session.
153
+ Handoffs never join active fact recall, injection, consolidation or session-note replay.
154
+ `/mind reset` clears working memory and backlog only; handoffs require explicit `forget` by ID and
155
+ revision. This preserves a handoff intended for a later session during routine workspace cleanup.
156
+
157
+ ## Replacement history
158
+
159
+ An ordinary `remember` with `supersedes` that retires an existing fact writes a before/after receipt
160
+ through the same write-ahead/CAS helper and bounded store used by consolidation. `origin: replacement`
161
+ distinguishes it from `optimization`; it has no invented plan ID or model-generated reason. If the
162
+ destination already contains the resulting fact, its prior metadata is retained as well. Plain saves,
163
+ exact re-recording, self-supersession and missing-source lineage do not create receipt noise.
164
+ The destination tier is read strictly (it anchors the compare-and-swap); the other tiers are read with
165
+ ordinary recovery but must be read completely, because one of them could hold a second fact with the id
166
+ being superseded. A tier counts as completely read only when it was read cleanly, is genuinely absent
167
+ (no live file and no backup), or was restored in full from a valid backup. Hidden rows, a quarantine,
168
+ or a backup that exists but cannot be used while the live file is absent leave it unread, and the
169
+ replacement is refused, naming that store.
170
+
171
+ `memory { action: "history", target: "project-long" }` and `/mind history project-long` list compact
172
+ metadata. For detail, provide `receiptId` and an explicit target; `offset` pages 12,000 UTF-16 units
173
+ of serialized before/after JSON. `/mind history show <receiptId> <target> [offset]` is the command
174
+ equivalent. Targets are `project` (working memory), `project-long`, `persona` and `shared`; listing
175
+ defaults to `project`. `/mind optimize history` uses the same compact discovery view.
176
+
177
+ Only the modifying persona can inspect its receipts, with persisted-content scanning on reads.
178
+ Historical values remain outside active recall and injection. Ordinary replacement receipts are
179
+ read-only: optimizer undo refuses them. Consolidation receipts retain their guarded undo path.
180
+ Retention and interrupted-write behavior are the same for both origins, as described below.
181
+ `/mind reset` does not delete these receipts; history follows its own bounded retention policy.
182
+ Ordinary saves and replacements recheck the accepting session/branch/persona at admission and under
183
+ the store lock. A source or replacement that expires while awaiting commit is refused. Revocation
184
+ after a completed write reports possible persistence in the original scope without exposing stale
185
+ record content or claiming rollback.
186
+
119
187
  ## Explicit consolidation
120
188
 
121
189
  Bare `/mind optimize` (and `/mind optimize all`) launches one bounded real Persona-hosted LLM review for each currently allowed nonshared target, sequentially, at most three workers; home allows only persona. A named `/mind optimize project|project-long|persona` remains one target. Each worker uses the exact session model and existing worker admission, prompt, strict JSON validation, provenance, preview, CAS apply and durable receipt pipeline. Explicit requests bypass automatic dirty/token/cooldown/auto-off gates but honor current owner, idle/busy, single-flight and safety checks. The command returns after scheduler acceptance, before store inspection or worker admission; the default toast lists allowed targets and says one bounded window per tier will run sequentially. Completion is displayed as ordinary target-qualified Mind result cards, without a separate activity row. Each tier inspects only one bounded page/window; no-input results show target-local counts, page coverage and a typed reason (invalid input, empty/exhausted page, no safe/owned facts, a single short fact, or insufficient full-record budget), followed by the explicit statement that no worker started and no memory changed. An empty page is not a claim that the whole target is empty. A completed worker returning no operations is a reviewed no-op, not a skipped tier. Skipped tiers and reviewed no-ops allow the batch to continue; cancellation, owner change, failed/refused/uncertain workers or writes stop later tiers. A terminal explicit batch report names the accepting/current target and, when any remain, prominently lists the exact tiers not yet examined; earlier skipped, reviewed, or applied tiers are not called unreviewed. Stale lifecycle work emits no report. Worker refusal/failure diagnostics include run ID, model/thinking, and a retained result reference when available, but never echo malformed worker output or source records; the reference lets the operator inspect the archived result. Strict parent parsing and source/provenance validation remain unchanged. Persona 1.17.6 can make one bounded retry after syntactically invalid JSON, within the same tracked worker and original deadline. Mind still validates the returned proposal independently; its v1 companion contract does not require this optional retry. Reports are target-qualified in batch mode. Interrupted/stale work cannot apply, emit stale reports or schedule a manual retry. Shared is explicitly refused for LLM review and points to `/mind optimize inspect shared` plus manual review. Read-only inspection is `/mind optimize inspect [target]`; inspect/history defaults are unchanged.
@@ -153,9 +221,15 @@ appending ordinary turn entries does not invalidate an owner. Applying never spa
153
221
  Before replacement, persist a scoped before/after receipt to `<store>.optimize-history.json`, under
154
222
  its transaction lock and the memory mutation lock. Maximum 32 receipts / 2 MiB per target, plus the
155
223
  standard backup. Evict settled receipts only; refuse the replacement if unresolved prepared receipts
156
- or the new receipt exceed capacity. A generic IO failure may occur after the memory rename, so its
157
- receipt remains prepared with outcome uncertainty. Known pre-write conflicts/lifecycle refusals are
158
- rejected. Finalization failure after a successful memory commit returns success with a warning.
224
+ or the new receipt exceed capacity. A capacity error, a conflict, a callback refusal,
225
+ or any other failure after which the memory store still holds the bytes the receipt was prepared
226
+ against settles the receipt rejected: the replacement is not in effect, whether it never landed or
227
+ backup recovery rolled it back, so there is nothing to undo. Only a changed or unreadable store leaves
228
+ the receipt prepared with outcome uncertainty. Receipts record the store fingerprint they were
229
+ prepared against (history detail omits it, like the store path). At history capacity, prepared
230
+ receipts of the same store, owner and target whose recorded fingerprint equals the current one are
231
+ resolved as rejected and become evictable; receipts without a fingerprint (written before 0.9.4),
232
+ prepared against other bytes, or belonging to another owner stay protected. Finalization failure after a successful memory commit returns success with a warning.
159
233
 
160
234
  History/undo survive optimizer recreation. History is bounded, owner-filtered and scanner-filtered.
161
235
  Undo restores only exact affected facts, preserving unrelated current records; it refuses changed
@@ -195,8 +269,20 @@ Separate started/settled receipts preserve the attempt target and cooldown witho
195
269
  interrupted review as completed. Restore considers only the latest attempt for each target, so an
196
270
  older interrupted input cannot reappear after its changed-input retry has settled. A semantic digest
197
271
  skips unchanged settled inputs, including terminal refusals. Only a retry of the interrupted attempt
198
- bypasses the token gate; it still requires a later native settled event and cooldown. Cancellation
199
- alone never rearms it. Unexpected current-owner failures persist terminal suppression without advancing
272
+ bypasses the token gate, at most once per unchanged input digest; it still requires a later native
273
+ settled event and cooldown. Cancellation alone never rearms it. Two consecutive interrupted automatic
274
+ launches of the same tier and digest (a stop, a foreground interruption, or a host that reports its
275
+ worker deadline as stopped) park that window: rotation bypasses it without recording it as reviewed or
276
+ settled, bypasses it again whenever it returns to it unchanged, and reviews it again once its records
277
+ change. Parking is derived from the persisted attempt receipts (the last 64), so turning automatic
278
+ review off, in-memory retry state and a restart all give the same answer; turning it off removes the
279
+ permission to retry, never the fact that the retry was used. A pending retry whose own window, at the
280
+ cursor it was launched from, no longer yields its input is dropped without a receipt. A retry whose
281
+ position cannot be verified (after a restart, or when another run moved the cursor) stays owed as one
282
+ token-free admission for that tier, used by the next dirty write and superseded by any launch on the
283
+ tier. Neither records the interrupted input as settled. A worker result with status `failed`
284
+ (including Persona's 180-second deadline) is terminal for that input and never earns a token-free
285
+ retry. Explicit reviews are unaffected. Unexpected current-owner failures persist terminal suppression without advancing
200
286
  the page cursor; a warning asks for inspection when an apply may have completed. If persistence itself
201
287
  fails, durable retry suppression cannot be guaranteed and the failure remains visible.
202
288
  Incoming input, `agent_start`, native branch navigation, off,
@@ -447,7 +533,9 @@ explicit attempt markers; interruptions never create an automatic retry entitlem
447
533
  the worker reservation rather than holding it while waiting for a human. Apply must acquire a new one;
448
534
  concurrent writes or expired plans are refused. New input, agent/model/branch changes, owner revocation
449
535
  and shutdown cancel workers/dialogs and invalidate pending review plans. Shutdown joins admitted apply
450
- work through approval, guarded persistence, receipt finalization and lease cleanup. Revocation blocks new
536
+ work through approval, guarded persistence, receipt finalization and lease cleanup; it bounds only the
537
+ wait for a Persona worker's completion (5 s), and a wait that reaches the bound is treated as an
538
+ interruption. Revocation blocks new
451
539
  admission and guarded writes, but does not roll back an already committed replacement or relabel it as
452
540
  cancelled; its finalization is still awaited and stale completion UI is suppressed. Completion uses display-only
453
541
  native entries/toasts and never triggers a supervisor turn.
@@ -462,7 +550,7 @@ language detector, language-specific factor, local tokenizer execution or runtim
462
550
  The reference encoding is not the current model's billing counter, and eight curated vectors do not
463
551
  establish broad language coverage or justify automatic budget tuning. The runtime budget is unchanged.
464
552
 
465
- Tests isolate PI_PERSONA_* and a throwaway PI_AGENT_DIR, use the actual Pi 1.5.2 SDK/tool pipeline and
553
+ Tests isolate PI_PERSONA_* and a throwaway PI_AGENT_DIR, use the actual Pi 1.6.0 SDK/tool pipeline and
466
554
  offline providers, and join session_shutdown before SDK disposal. Native session tests cover persisted
467
555
  reopen, branch/fork, in-memory behavior and owner revocation. Store tests cover lost writes, stale plans,
468
556
  invalid inputs and concurrent apply. Installed-host/package qualification complements source tests.
@@ -33,6 +33,24 @@ Mind uses deterministic lexical, tag and path ranking, with explicit full reads
33
33
  injection. This is explainable and avoids an additional indexing service, but differently worded
34
34
  queries may miss relevant facts. No general semantic-recall guarantee follows from a passing test.
35
35
 
36
+ Identifier components and vowel-accent folding are lower-weight fallback matches, behind exact
37
+ words and paths. Numeric versions stay exact atoms; alphabetic tail words are also indexed at ordinary
38
+ word weight, while numeric or digit-bearing tail parts stay inside the atom. Negation remains searchable, and Unicode/CJK
39
+ segmentation is preserved. A fallback can still add irrelevant rows: fewer missed identifiers does
40
+ not imply perfect precision. Tags already normalized when saved cannot recover lost camel casing.
41
+
42
+ `npm run eval:memory` compares the previous ranker and injection renderer with the current ones on
43
+ the same corpus, scope and budget. In the 12-case development fixture, positive top-one hits improve
44
+ from 2/7 to 7/7; in the separate nine-case held-out set, they improve from 6/7 to 7/7.
45
+ The held-out set was written alongside the implementation, not withheld from it.
46
+ Negative queries with results fall from one to zero in each set. Strict false positives among the top
47
+ three, ignoring `acceptableIds`, remain 1 to 1 in development and 5 to 5 in the held-out set.
48
+ With acceptable labels, the counts are 1 to 1 and 5 to 3 respectively; that held-out reduction depends
49
+ on the labels excusing weaker accent matches. A weak `memory`/`memoryOwnership` match remains.
50
+ The preceding 30-case fixture's metrics and
51
+ seven sentinel outcomes are unchanged. These small synthetic sets and their labels are inspectable
52
+ regression evidence, not an external benchmark or a general semantic-quality claim.
53
+
36
54
  Injection is a planning budget, not a billing measurement. Preserve wrappers, omission counts and
37
55
  whole admitted excerpts within the documented limits. The runtime estimate operates on UTF-8 bytes;
38
56
  it must not select a correction factor by detecting a language. A comparison against a named reference
@@ -56,6 +74,16 @@ encoding remains a comparison to that encoding, not a count for every possible s
56
74
  Successful validation establishes structural permission and freshness, not semantic truth. A worker
57
75
  can still propose a bad summary. Keep proposals inspectable and state that limitation explicitly.
58
76
 
77
+ Ordinary explicit supersession now uses that same receipt protocol. This preserves a changed
78
+ decision's original evidence without making historical facts compete with current facts in recall.
79
+ An ordinary receipt is read-only; consolidation undo retains its existing conflict checks. No second
80
+ archive, embeddings service or automatically generated summary is introduced.
81
+
82
+ Cross-session handoffs address a separate need: a deliberately saved work snapshot with a next step,
83
+ origin and explicit completion resolution. They remain owner-scoped and manually discoverable, never
84
+ automatic instructions or a claim that a worker session was restored. Quota refusal and explicit
85
+ forgetting preserve unfinished work instead of silently deleting it on a timer.
86
+
59
87
  ## What verification can establish
60
88
 
61
89
  The local suite exercises store concurrency, atomic replacement, stale-plan refusal, provenance,
@@ -83,7 +111,7 @@ reference counts or automatically tune the production budget from a small fixtur
83
111
  ## Inspector architecture decision
84
112
 
85
113
  The memory inspector adds a read-only view over existing stores and the native active branch, rather
86
- than introducing an OptChat-style permanent transcript and summary tree. This preserves Mind's role as
114
+ than introducing a permanent transcript and summary tree. This preserves Mind's role as
87
115
  selective scoped memory and avoids a second retention policy, summarizer budget and source of truth.
88
116
  A separate archive could eventually make older cross-session episodes navigable, but would require an
89
117
  explicit access, deletion and retention design; an opaque source string is not that authorization.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aeondave/pi-persona-mind",
3
- "version": "0.9.2",
3
+ "version": "0.9.4",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Local memory for Pi with pi-persona — durable project and persona facts, session notes, bounded retrieval, and supervised automatic consolidation.",
@@ -52,7 +52,7 @@
52
52
  "verify": "npm run typecheck && npm test"
53
53
  },
54
54
  "pi": {
55
- "image": "https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.9.2/assets/banner.png",
55
+ "image": "https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.9.4/assets/banner.png",
56
56
  "extensions": [
57
57
  "./src/index.ts"
58
58
  ]
@@ -78,10 +78,10 @@
78
78
  }
79
79
  },
80
80
  "devDependencies": {
81
- "@earendil-works/pi-agent-core": "1.5.2",
82
- "@earendil-works/pi-ai": "1.5.2",
83
- "@earendil-works/pi-coding-agent": "1.5.2",
84
- "@earendil-works/pi-tui": "1.5.2",
81
+ "@earendil-works/pi-agent-core": "1.6.0",
82
+ "@earendil-works/pi-ai": "1.6.0",
83
+ "@earendil-works/pi-coding-agent": "1.6.0",
84
+ "@earendil-works/pi-tui": "1.6.0",
85
85
  "@types/node": "^22.0.0",
86
86
  "tsx": "^4.19.0",
87
87
  "typebox": "*",
@@ -0,0 +1,111 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { isAbsolute, relative } from "node:path";
3
+ import { canonicalProjectIdentity, type Scope } from "./scope.ts";
4
+ import { BoundedReadFailure, JsonStore, StoreCapacityError, StoreConflictError, StoreVersionError } from "./store.ts";
5
+ import { MAX_HANDOFF_ENTRIES, MAX_HANDOFF_GOAL_PREVIEW_CHARS, MAX_HANDOFF_RECORD_BYTES, MAX_HANDOFF_STORE_BYTES, validContext, validHandoffContent, validateHandoff, validResolution, type HandoffContext, type HandoffEntry, type HandoffInput } from "./handoff.ts";
6
+
7
+ export type HandoffResult =
8
+ | { ok: false; reason: string }
9
+ | { ok: true; operation: "save" | "read" | "complete"; entry: HandoffEntry }
10
+ | { ok: true; operation: "list"; total: number; entries: (Pick<HandoffEntry, "id" | "revision" | "goal" | "status" | "createdAt" | "updatedAt"> & { goalTruncated: boolean })[] }
11
+ | { ok: true; operation: "forget" };
12
+
13
+ export class HandoffStore {
14
+ private readonly store: JsonStore<HandoffEntry>;
15
+ constructor(privateScope: Scope) {
16
+ this.scope = privateScope;
17
+ // The byte cap bounds the shared file; entry quotas belong to each owner.
18
+ this.store = new JsonStore(`${privateScope.paths.stm}.handoffs.json`, { version: 1, validateEntry: validateHandoff, maxEntries: Number.MAX_SAFE_INTEGER, maxBytes: MAX_HANDOFF_STORE_BYTES });
19
+ }
20
+ private readonly scope: Scope;
21
+
22
+ async execute(context: HandoffContext, input: HandoffInput): Promise<HandoffResult> {
23
+ try {
24
+ if (this.scope.homeWorkspace || !validContext(context) || context.isCurrent?.() === false || context.persona !== this.scope.persona || canonicalProjectIdentity(context.projectRoot) !== canonicalProjectIdentity(this.scope.projectRoot)) return { ok: false, reason: "handoff owner or project unavailable" };
25
+ const cwdRelative = relative(canonicalProjectIdentity(context.projectRoot), canonicalProjectIdentity(context.cwd));
26
+ if (cwdRelative === ".." || cwdRelative.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute(cwdRelative)) return { ok: false, reason: "handoff cwd outside project" };
27
+ if (input.operation === "save" && !validHandoffContent(input)) return { ok: false, reason: "invalid or unsafe handoff content" };
28
+ if (input.operation === "complete" && !validResolution(input.resolution)) return { ok: false, reason: "resolution must be nonempty and safe" };
29
+ for (let attempt = 0; attempt < 10; attempt++) {
30
+ const snapshot = await this.store.inspectStrict();
31
+ if (context.isCurrent?.() === false) return { ok: false, reason: "handoff owner changed" };
32
+ if (new Set(snapshot.store.entries.map((e) => e.id)).size !== snapshot.store.entries.length) return { ok: false, reason: "handoff store contains duplicate IDs" };
33
+ const owned = snapshot.store.entries.filter((e) => e.persona === context.persona && canonicalProjectIdentity(e.projectRoot) === canonicalProjectIdentity(context.projectRoot));
34
+ if (input.operation === "list") return { ok: true, operation: "list", total: owned.length, entries: owned.map(({ id, revision, goal, status, createdAt, updatedAt }) => {
35
+ const goalTruncated = goal.length > MAX_HANDOFF_GOAL_PREVIEW_CHARS;
36
+ const preview = goalTruncated ? `${goal.slice(0, MAX_HANDOFF_GOAL_PREVIEW_CHARS - 1).replace(/[\uD800-\uDBFF]$/, "")}…` : goal;
37
+ return { id, revision, goal: preview, goalTruncated, status, createdAt, updatedAt };
38
+ }) };
39
+ if (input.operation === "read") {
40
+ const entry = owned.find((e) => e.id === input.id);
41
+ return entry ? { ok: true, operation: "read", entry } : { ok: false, reason: "handoff not found" };
42
+ }
43
+ let entry: HandoffEntry;
44
+ if (input.operation === "save") {
45
+ // CAS rechecks this snapshot under the lock, so concurrent saves cannot exceed the quota.
46
+ if (owned.length >= MAX_HANDOFF_ENTRIES) return { ok: false, reason: `handoff quota of ${MAX_HANDOFF_ENTRIES} entries reached for this persona in this project; use forget to free space` };
47
+ const now = new Date().toISOString();
48
+ entry = { id: randomBytes(16).toString("hex"), revision: 1, persona: context.persona, projectRoot: canonicalProjectIdentity(context.projectRoot), origin: { sessionId: context.sessionId, branchId: context.branchId, cwd: context.cwd }, createdAt: now, updatedAt: now, status: "open", goal: input.goal, completed: [...input.completed], pending: [...input.pending], nextStep: input.nextStep, references: [...input.references] };
49
+ } else {
50
+ const found = owned.find((e) => e.id === input.id);
51
+ if (!found) return { ok: false, reason: "handoff not found" };
52
+ if (found.revision !== input.revision) return { ok: false, reason: "handoff changed; read it again" };
53
+ if (input.operation === "complete" && found.status !== "open") return { ok: false, reason: "handoff already completed" };
54
+ entry = input.operation === "complete" ? { ...found, status: "completed", revision: found.revision + 1, updatedAt: new Date().toISOString(), resolution: input.resolution } : found;
55
+ }
56
+ if (Buffer.byteLength(JSON.stringify(entry), "utf8") > MAX_HANDOFF_RECORD_BYTES) return { ok: false, reason: `handoff snapshot including metadata exceeds ${MAX_HANDOFF_RECORD_BYTES} bytes; shorten the content or resolution` };
57
+ const normalized = validateHandoff(entry);
58
+ if (!normalized) return { ok: false, reason: "handoff snapshot metadata is invalid" };
59
+ entry = normalized;
60
+ try {
61
+ await this.store.compareAndUpdate(snapshot.fingerprint, (entries) => {
62
+ if (context.isCurrent?.() === false) throw new Error("handoff owner changed");
63
+ return input.operation === "save" ? [...entries, entry] : input.operation === "forget" ? entries.filter((e) => e.id !== entry.id) : entries.map((e) => e.id === entry.id ? entry : e);
64
+ });
65
+ if (context.isCurrent?.() === false) return { ok: false, reason: "handoff owner changed after commit; inspect the original scope" };
66
+ if (input.operation === "forget") return { ok: true, operation: "forget" };
67
+ return { ok: true, operation: input.operation, entry };
68
+ } catch (error) {
69
+ if (error instanceof StoreConflictError) continue;
70
+ if (error instanceof StoreCapacityError && error.kind === "bytes") {
71
+ const otherEntries = snapshot.store.entries.filter((e) => e.persona !== context.persona);
72
+ // Match JsonStore's envelope, indentation and newline: could this operation fit
73
+ // if the caller freed every existing entry they own?
74
+ const afterForgetting = { ...snapshot.store, sequence: snapshot.store.sequence + 1, updatedAt: new Date().toISOString(),
75
+ entries: input.operation === "forget" ? otherEntries : [...otherEntries, entry] };
76
+ const othersBlock = Buffer.byteLength(`${JSON.stringify(afterForgetting, null, 2)}\n`, "utf8") > error.limit;
77
+ const counts = `your entries: ${owned.length}; other personas: ${otherEntries.length} entries`;
78
+ const remedy = owned.length > 0 ? "; use forget to free space" : "";
79
+ return { ok: false, reason: othersBlock
80
+ ? `other personas' handoffs fill this project's handoff file ${this.store.filePath} (${counts}); ${error.limit}-byte limit exceeded${remedy}`
81
+ : `handoff file ${this.store.filePath} exceeds ${error.limit} bytes (${counts})${remedy}` };
82
+ }
83
+ throw error;
84
+ }
85
+ }
86
+ return { ok: false, reason: "handoff store busy; retry" };
87
+ } catch (error) {
88
+ const file = `handoff file ${this.store.filePath}`;
89
+ if (error instanceof BoundedReadFailure) {
90
+ return { ok: false, reason: error.kind === "path"
91
+ ? `${file} has an unsafe or changing path; repair it as a regular file and retry`
92
+ : `${file} exceeds safe read limits or changed size while being read; repair it within the ${MAX_HANDOFF_STORE_BYTES}-byte limit and retry` };
93
+ }
94
+ if (error instanceof StoreVersionError) {
95
+ return { ok: false, reason: `${file} uses version ${error.found}, but this build reads version ${error.expected}; use a compatible build; the file is left untouched` };
96
+ }
97
+ // JsonStore's two untyped strict-read refusals are covered by real-file regression
98
+ // cases, so a change to either upstream message cannot silently lose this mapping.
99
+ if (error instanceof Error && error.message === "memory store is missing with a recoverable backup; repair before optimizing") {
100
+ return { ok: false, reason: `${file} is missing while ${this.store.filePath}.bak exists; inspect the backup and repair the handoff file by hand` };
101
+ }
102
+ if (error instanceof Error && error.message === "memory store is corrupt or contains invalid entries; repair before optimizing") {
103
+ return { ok: false, reason: `${file} is corrupt or contains invalid entries; repair or remove the invalid entry by hand` };
104
+ }
105
+ if (error instanceof Error && "code" in error && typeof error.code === "string") {
106
+ return { ok: false, reason: `${file} cannot be accessed (${error.code}); check the path and permissions, repair access and retry` };
107
+ }
108
+ return { ok: false, reason: error instanceof Error ? error.message : "handoff storage failure" };
109
+ }
110
+ }
111
+ }