@aeondave/pi-persona-mind 0.9.7 → 0.9.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/AGENTS.md +137 -137
  2. package/CHANGELOG.md +287 -282
  3. package/LICENSE +24 -24
  4. package/README.md +1 -1
  5. package/docs/DESIGN.md +605 -605
  6. package/docs/MEMORY-RESEARCH.md +163 -163
  7. package/package.json +11 -2
  8. package/src/core/auto-optimize.ts +323 -323
  9. package/src/core/backlog.ts +228 -228
  10. package/src/core/blocked.ts +38 -38
  11. package/src/core/capture.ts +155 -155
  12. package/src/core/context-budget.ts +74 -74
  13. package/src/core/handoff-store.ts +111 -111
  14. package/src/core/handoff.ts +70 -70
  15. package/src/core/host-compat.ts +16 -16
  16. package/src/core/ids.ts +59 -59
  17. package/src/core/inject.ts +247 -247
  18. package/src/core/knowledge-review.ts +107 -107
  19. package/src/core/memory-read.ts +34 -34
  20. package/src/core/memory.ts +321 -321
  21. package/src/core/migrate.ts +713 -713
  22. package/src/core/mind-settings.ts +54 -54
  23. package/src/core/optimize-history.ts +163 -163
  24. package/src/core/optimize-service.ts +189 -189
  25. package/src/core/optimize.ts +127 -127
  26. package/src/core/retrieval.ts +164 -164
  27. package/src/core/scanner.ts +146 -146
  28. package/src/core/scope.ts +201 -201
  29. package/src/core/service.ts +720 -720
  30. package/src/core/session-memory.ts +71 -71
  31. package/src/core/store.ts +1002 -1002
  32. package/src/extension/activity.ts +79 -79
  33. package/src/extension/auto-optimize-session.ts +143 -143
  34. package/src/extension/auto-optimize.ts +565 -565
  35. package/src/extension/handoff.ts +23 -23
  36. package/src/extension/knowledge-review.ts +229 -229
  37. package/src/extension/memory-inspector.ts +82 -82
  38. package/src/extension/mind-actions.ts +38 -38
  39. package/src/extension/mind-worker.ts +32 -32
  40. package/src/extension/persona-dependency.ts +76 -76
  41. package/src/extension/reference-anchor.ts +48 -48
  42. package/src/extension/review-evidence.ts +222 -222
  43. package/src/extension/worker-memory-anchor.ts +28 -28
  44. package/src/session-memory.ts +127 -127
  45. package/src/tools/backlog.ts +126 -126
  46. package/src/tools/memory-handoff.ts +30 -30
  47. package/src/tools/memory-history.ts +46 -46
  48. package/src/tools/memory.ts +6 -4
  49. package/src/ui/card-frame.ts +161 -161
  50. package/src/ui/inspector-frame.ts +44 -44
  51. package/src/ui/memory-inspector.ts +464 -464
  52. package/src/ui/mind-result-card.ts +48 -48
  53. package/src/ui/presentation.ts +87 -87
  54. package/src/ui/session-note-card.ts +58 -58
package/docs/DESIGN.md CHANGED
@@ -1,605 +1,605 @@
1
- # pi-persona-mind — current design
2
-
3
- This is the binding implementation contract. Release history belongs in [CHANGELOG](../CHANGELOG.md);
4
- the user workflow is in [README](../README.md). Local design rationale and evaluation boundaries are in
5
- [MEMORY-RESEARCH](MEMORY-RESEARCH.md).
6
-
7
- ## Host and module boundaries
8
-
9
- This design contract describes the current development tree; released changes are recorded separately
10
- in CHANGELOG.md.
11
-
12
- Target the latest stable Pi only, currently 1.7.0, and Node >=22.19. All four development Pi packages
13
- are pinned together; runtime host/typebox packages remain optional wildcard peers. No second host
14
- runtime or historical hook-shape adapter is bundled. A development-only security override does not
15
- patch an installed host.
16
-
17
- Mind and Persona use the profile Pi selects through `--agent-dir` or `PI_CODING_AGENT_DIR`.
18
- `PI_AGENT_DIR` applies when it is the only profile override. Mind resolves the profile when the
19
- extension loads, after Pi has applied the CLI flag.
20
-
21
- Mind requires a loaded compatible pi-persona through its versioned local companion handshake.
22
- Missing/incompatible presence leaves tools inactive and suppresses capture, storage/import,
23
- injection and reminders. A settings file or installed npm package is not proof of an active
24
- companion. Mind requires Persona 1.18.1 or later for these paired contracts. Its optional npm
25
- peer declares that requirement without auto-installing or activating another extension.
26
-
27
- The node-only core has no Pi imports. The factory wires native Pi hooks, tools, scope, scheduling
28
- and lifecycle owners. Session persistence uses Pi's public SessionManager and appendEntry contracts.
29
- Command parsing/presentation lives outside the factory. Important seams:
30
-
31
- | Module | Responsibility |
32
- |---|---|
33
- | core/service.ts | Scope-bound memory/backlog operations, mutation ordering |
34
- | core/store.ts | Atomic writes, exclusive ownership, recovery, strict snapshots and CAS |
35
- | core/memory.ts, backlog.ts | Validated facts, shared persisted-content guard and deferred-work state |
36
- | core/scope.ts, mind-settings.ts | Project identity, safe paths and canonical Mind preferences |
37
- | extension/persona-dependency.ts | Loaded capability and actual memory-owner contracts |
38
- | core/migrate.ts | Bounded, non-destructive import of previous memory layouts |
39
- | core/session-memory.ts, session-memory.ts | Session event validation/replay and native owner adapter |
40
- | core/optimize.ts, optimize-service.ts | Pure consolidation rules and short-lived staged plans |
41
- | core/optimize-history.ts | Bounded durable before images and conflict-checked undo |
42
- | core/handoff.ts, handoff-store.ts | Explicit scoped handoff snapshots, revision checks and bounded persistence |
43
- | core/retrieval.ts, context-budget.ts | Explainable task ranking and shared context estimate |
44
- | core/memory-read.ts | Full explicit retrieval without clipped discovery or recovery writes |
45
- | tools/memory.ts, memory-optimize.ts | Model-facing action validation and result formatting |
46
- | extension/mind-command.ts | One command handler for persona-mind and mind |
47
- | ui/ | Sanitized compact cards, full expansion and native custom-entry renderers |
48
-
49
- ## Four lifetimes
50
-
51
- - **Durable facts:** persona-private LTM, explicit shared LTM and repository-scoped project LTM.
52
- Never expire automatically. Project facts remain repository-bound across persona changes.
53
- - **Working project facts:** STM with persona attribution; 48-hour default TTL. Project injection can include
54
- other personas' observations, but optimizer mutations require the current persona's ownership.
55
- - **Session notes:** native custom entries on the active branch, including source session identity.
56
- - **Deferred intent:** project backlog, open/taken/done/dropped. Default expiry is 48 hours; a later
57
- reminder extends it. A repeated take is idempotent; re-add does not reopen completed work.
58
-
59
- LTM/STM facts have content identity based on kind, text and sorted tags; provenance is excluded.
60
- Exact re-recording updates identical normalized content (not semantic equivalence). lastSeenAt tracks recording/promotion, not
61
- recall frequency. Read operations do not boost ranking or reset expiry. `term` alone selects lifetime:
62
- `kind: objective` is not automatically promoted, so a short objective remains expiring project context
63
- and a session objective remains on that active native session branch.
64
-
65
- Exact re-recording preserves existing `source`, `derivedFrom` and `supersedes` when no replacement
66
- metadata is supplied; nonempty replacement metadata updates the corresponding value. In `remember`,
67
- an empty source or empty `derivedFrom` list is treated as omitted, not as a request to clear provenance.
68
- `remember` supersession retires an active row in its selected destination tier. A target found only
69
- in another tier is refused before writing; moving a fact and replacing one are separate operations.
70
- derivedFrom stores bounded IDs. Optimizer before images provide
71
- bounded recoverability; ordinary supersession/forget are not a temporal database or unlimited undo.
72
- Every long-term `remember` requires an explicit destination: project LTM, persona LTM, or shared LTM;
73
- there is no implicit persona destination. Short-term memory remains project-scoped by default. Promotion
74
- defaults to project LTM and requires an owned live STM source; persona/shared promotion destinations
75
- must be explicit. A scope value selects API routing intent; it is not authenticated user consent. Use
76
- session for task-specific or uncertain choices (models, strategies, task constraints), project for
77
- stable repository facts, persona for facts intended across all projects of the same persona, and shared
78
- only for facts truly intended across personas. Existing persona facts are never reassigned to guessed projects. Promotion removes
79
- only its exact source row; equal-text observations from another owner retain their provenance.
80
-
81
- ## Scope and companion integration
82
-
83
- The active persona comes only from pi-persona:memory-owner:v1, a synchronous query bound to the
84
- native session ID. Its response identifies the loaded provider, readiness and actual persona (or
85
- null for no persona). pi-persona:memory-owner-changed:v1 broadcasts readiness and selection changes.
86
- Before Persona finishes startup, Mind returns without memory IO; it must not await a later extension's
87
- session_start. Missing, ambiguous or stale owners refuse access. Saved selection and CLI flags are
88
- not substitutes for the runtime owner, including when Persona persistence is disabled.
89
-
90
- Mind capture/nudge preferences are session snapshots from canonical
91
- <agentDir>/persona/settings.json. The retired state.json and PI_PERSONA_STATE_FILE are not runtime
92
- sources; Persona owns its settings migration. Contribute effective Mind preferences through
93
- pi-persona:settings:collect:v1; never edit companion settings or start another service.
94
-
95
- Use the canonical project path and collision-safe persona scope names. Reserved shared/default
96
- names, lossy Unicode conversions and Windows device names must not merge unrelated personas.
97
- Home is not a project: skip project injection and reminders there.
98
-
99
- A delegated leg is sampled at factory activation through PI_PERSONA_LEG / PI_PERSONA_CHILD.
100
- PI_PERSONA_DISABLE alone does not designate a worker. Workers get lean objective/LTM injection,
101
- no project/session notes, no memory/backlog tools and no reminders. Both Persona engines freeze the
102
- launching persona. In-process workers receive it through their own extension bus; child processes
103
- receive a scrubbed spawn-local payload. A later parent selection cannot move a worker's memory scope.
104
- Mind appends worker memory through Pi's prompt options. Persona can preload the selected skill
105
- bodies in Pi's skills section and verify both inputs when the worker resumes. Pi records the
106
- worker's memory excerpts in its native system messages when the worker transcript is saved.
107
- For a persisted worker with one valid Persona v1 contract on the active branch, lean memory ranking
108
- uses the first user turn after that contract. Labels such as `today` and `1d` in the worker's lean
109
- memory refer to that launch turn's timestamp. Mind reads current durable memory for each turn, and
110
- Persona checks the resulting prompt against the saved contract.
111
-
112
- After upgrading from 0.9.5, a worker saved with memory in a full-prompt override can report
113
- `prompt configuration` on resume. Start a fresh delegation with the same brief and skills in that case.
114
-
115
- Intercom/Exocom and worker output stay foreign reference material, not automatic capture requests.
116
- Only the reserved pi-persona-deferred-input custom type replays direct user input. This is a
117
- trusted-extension convention, not authentication against other code running in the same process.
118
- Do not read Persona's private result archive. The supervisor explicitly retrieves a report through
119
- Intercom before curating a fact. A saved ref remains an opaque source string, not a cross-session grant.
120
-
121
- ## Session notes
122
-
123
- Version-1 save/forget events live under pi-persona-mind-session-note. Reads replay only the active
124
- branch; all session events count toward the lifetime budget. Branching/forking follows native Pi
125
- history; new sessions do not inherit notes. Forked notes preserve originSessionId. A forget appends
126
- a branch-local tombstone and does not erase previous transcript bytes.
127
-
128
- Limits: 64 active notes, 8,000 text characters per note, 1,000 source characters, 256 lifetime events,
129
- 512 KiB encoded event data. Unknown versions, unsafe history or exceeded bounds fail closed.
130
- Admission and replay both scan content. No append occurs after owner revocation; owner identity
131
- includes the native manager, session ID and file. No asynchronous gap separates validation and append.
132
-
133
- Receipts distinguish session storage from memory-only storage; Pi controls disk flushing.
134
- An identical automatic capture reuses the active note when kind, text and source match.
135
- It consumes no additional note or history slot and produces no new notification. After a
136
- branch-local forget, the user can capture it again. Explicit writes keep their own provenance.
137
- Injection is reference data, escaped and bounded to a 600-token planning estimate (UTF-8 bytes / 3)
138
- with excerpts of at most 700 characters. It shares the total memory budget. Current task matching
139
- precedes recency, with objective priority. Omitted entries and clipping are disclosed. Explicit read returns the whole note.
140
- An in-memory session is not advertised as restart-durable.
141
-
142
- The supervisor gets one request-local, labelled memory reference. Pi converts it to user-role
143
- content for the provider. On ordinary tool continuations the reference stays at the turn's
144
- starting input. If Pi compacts inside the run, Mind rebuilds it from the current owner's stores
145
- and active-branch notes and places it before the native summary. This preserves changes made by
146
- tools since the run began. Mind adds no reference to the session log or summary prompt.
147
- The worker retains its separate lean system-prompt contract and selected skills. Explicit
148
- memory tool arguments, results and anything the model repeats follow Pi's ordinary history rules.
149
-
150
- Pi can also replay a previously sent request to warm an eligible provider cache. If the memory
151
- owner changes, that replay can still contain the previous owner's reference. Pi 1.7.0 reuses the
152
- original request context. Its warming decision exposes costs and an action without a request ID,
153
- so Mind cannot reliably veto only that replay. Pi's global `cacheWarming`
154
- setting defaults to `"idle"` for eligible, cost-effective requests. `"streaming"` limits warming
155
- to active runs, and `"off"` disables warm requests. [Pi 1.7.0 settings](https://github.com/earendil-works/pi/blob/v1.7.0/packages/coding-agent/docs/settings.md)
156
-
157
- ## Cross-session handoffs
158
-
159
- `memory { action: "handoff", handoff: { operation: "save", goal, completed, pending, nextStep,
160
- references } }` stores an explicit snapshot. `completed`, `pending` and `references` are arrays of
161
- strings. `list` discovers metadata; `read` with `id` returns the snapshot. `complete` requires `id`,
162
- the latest `revision` and a `resolution`; `forget` requires `id` and `revision`. These actions share
163
- the existing memory tool, not another tool or model service. `/mind handoff list`,
164
- `/mind handoff show <id>`, `/mind handoff complete <id> <revision> <resolution>` and
165
- `/mind handoff forget <id> <revision>` provide operator access.
166
-
167
- Handoffs belong to the actual project and active persona, with the native source session/branch
168
- and cwd recorded as provenance. A later independent session may explicitly read the same owner's
169
- handoff. Home sessions and delegated workers cannot access this surface. The live owner is checked
170
- before IO, after reads and under the write lock; branch/session changes revoke pending operations.
171
- Stored content is untrusted, scanned and fenced. References remain literal strings, never automatic
172
- file reads or tool instructions.
173
-
174
- One `<STM store>.handoffs.json` sidecar is shared by all personas with owner-filtered access. Each
175
- owner (persona + project) may hold up to 32 entries; the file as a whole is capped at 128 KiB, which is
176
- its only total bound. Each record, including metadata, is limited to 16 KiB; the normal store backup
177
- also applies. Listing uses 160-character goal previews and a 40 KiB formatted-output bound. Explicit
178
- full reads are bounded to 100 KiB after JSON escaping; neither path silently truncates stored records.
179
- There is no TTL or automatic eviction: at its own quota, a persona's new save fails until it forgets
180
- one of its handoffs. A save refused by the file-wide byte cap reports the caller's own entry count and
181
- the other personas' count, never their names, ids or content; when the other personas' entries alone
182
- fill the file, the refused persona cannot free space itself. A sidecar that cannot be read strictly
183
- 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
184
- historical. It does not verify tests, execute pending tasks or claim a restored worker session.
185
- Handoffs never join active fact recall, injection, consolidation or session-note replay.
186
- `/mind reset` clears working memory and backlog only; handoffs require explicit `forget` by ID and
187
- revision. This preserves a handoff intended for a later session during routine workspace cleanup.
188
-
189
- ## Replacement history
190
-
191
- An ordinary `remember` with `supersedes` that retires an existing fact writes a before/after receipt
192
- through the same write-ahead/CAS helper and bounded store used by consolidation. `origin: replacement`
193
- distinguishes it from `optimization`; it has no invented plan ID or model-generated reason. If the
194
- destination already contains the resulting fact, its prior metadata is retained as well. Plain saves,
195
- exact re-recording, self-supersession and missing-source lineage do not create receipt noise.
196
- The destination tier is read strictly (it anchors the compare-and-swap); the other tiers are read with
197
- ordinary recovery but must be read completely, because one of them could hold a second fact with the id
198
- being superseded. A tier counts as completely read only when it was read cleanly, is genuinely absent
199
- (no live file and no backup), or was restored in full from a valid backup. Hidden rows, a quarantine,
200
- or a backup that exists but cannot be used while the live file is absent leave it unread, and the
201
- replacement is refused, naming that store.
202
-
203
- `memory { action: "history", target: "project-long" }` and `/mind history project-long` list compact
204
- metadata. For detail, provide `receiptId` and an explicit target; `offset` pages 12,000 UTF-16 units
205
- of serialized before/after JSON. `/mind history show <receiptId> <target> [offset]` is the command
206
- equivalent. Targets are `project` (working memory), `project-long`, `persona` and `shared`; listing
207
- defaults to `project`. `/mind optimize history` uses the same compact discovery view.
208
-
209
- Only the modifying persona can inspect its receipts, with persisted-content scanning on reads.
210
- Historical values remain outside active recall and injection. Ordinary replacement receipts are
211
- read-only: optimizer undo refuses them. Consolidation receipts retain their guarded undo path.
212
- Retention and interrupted-write behavior are the same for both origins, as described below.
213
- `/mind reset` does not delete these receipts; history follows its own bounded retention policy.
214
- Ordinary saves and replacements recheck the accepting session/branch/persona at admission and under
215
- the store lock. A source or replacement that expires while awaiting commit is refused. Revocation
216
- after a completed write reports possible persistence in the original scope without exposing stale
217
- record content or claiming rollback.
218
-
219
- ## Explicit consolidation
220
-
221
- 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.
222
-
223
- The manual workflow is inspect → stage exact replacements → apply plan ID. An omitted replacement tag
224
- list inherits the normalized union from selected sources; an explicit empty list clears tags. Lexical
225
- rules never approve semantic changes. Learned decay rates, recall counters and age-based LTM deletion
226
- remain outside the contract.
227
-
228
- Inspection reads a strict store snapshot without recovery/quarantine writes. It returns at most 100
229
- safe entries (20 by default), an exact raw-byte fingerprint, omission counts and at most 12 lexical
230
- candidate pairs. Similarity is advisory: negation can preserve nearly all words while reversing meaning.
231
- Inspection exposes offset/matched/nextOffset so old facts remain reachable in bounded pages;
232
- fingerprint changes invalidate a paginated inspection's snapshot. Pairs compare one page only.
233
- The foreground agent must inspect full text and current evidence before proposing replacements.
234
-
235
- Each plan affects one store: `project` STM, `project-long` durable repository memory, persona LTM,
236
- or shared LTM. Both project tiers require the current persona's ownership. One source rewrites a fact;
237
- multiple sources consolidate facts. Explicit deletion remains memory forget. Operations specify exact
238
- persisted source IDs; ambiguous/overlapping IDs, unsafe content, mixed ownership, replacement collisions,
239
- expired sources, malformed stores and provenance overflow refuse the plan.
240
-
241
- A replacement keeps earliest recording time, all bounded source origins and lineage. Project replacements
242
- keep the earliest source expiry; consolidation cannot revive or extend stale working context.
243
- Unselected entries are preserved. No capacity-enforcing truncation is allowed.
244
-
245
- At most four plans per session/scope owner, ten-minute lifetime. Preview is immutable to callers.
246
- Invalidation during an asynchronous preview read also refuses that preview; it cannot stage a new
247
- plan belonging to the invalidated owner after the read returns.
248
- Apply rechecks raw-byte fingerprint, lifetime, source expiry and owner invalidation under the store lock
249
- and Mind's mutation lock. Even a same-sequence external file replacement invalidates the fingerprint.
250
- Concurrent apply cannot commit twice. Session/scope changes and native branch navigation discard plans;
251
- appending ordinary turn entries does not invalidate an owner. Applying never spawns a model.
252
-
253
- Before replacement, persist a scoped before/after receipt to `<store>.optimize-history.json`, under
254
- its transaction lock and the memory mutation lock. Maximum 32 receipts / 2 MiB per target, plus the
255
- standard backup. Evict settled receipts only; refuse the replacement if unresolved prepared receipts
256
- or the new receipt exceed capacity. A capacity error, a conflict, a callback refusal,
257
- or any other failure after which the memory store still holds the bytes the receipt was prepared
258
- against settles the receipt rejected: the replacement is not in effect, whether it never landed or
259
- backup recovery rolled it back, so there is nothing to undo. Only a changed or unreadable store leaves
260
- the receipt prepared with outcome uncertainty. Receipts record the store fingerprint they were
261
- prepared against (history detail omits it, like the store path). At history capacity, prepared
262
- receipts of the same store, owner and target whose recorded fingerprint equals the current one are
263
- resolved as rejected and become evictable; receipts without a fingerprint (written before 0.9.4),
264
- prepared against other bytes, or belonging to another owner stay protected. Finalization failure after a successful memory commit returns success with a warning.
265
-
266
- History/undo survive optimizer recreation. History is bounded, owner-filtered and scanner-filtered.
267
- Undo restores only exact affected facts, preserving unrelated current records; it refuses changed
268
- replacements, source collisions, expired facts and owner revocation. Check the lifecycle generation
269
- inside the store mutation callback. An ambiguous interrupted receipt is never presumed applied or
270
- discarded; unresolved IO failures can require manual recovery. This is consolidation recovery,
271
- not rollback of arbitrary user edits or a claim of semantic correctness.
272
-
273
- These are authorization mechanics, not truth verification: an explicit memory tool call has the same
274
- mutation authority as existing remember/forget. The LLM chooses the destination by meaning and context;
275
- users need not provide API scope names or a literal “global” keyword, and no new per-save confirmation
276
- loop is imposed. Truly portable preferences remain eligible for persona/shared memory. Background
277
- review eligibility does not restrict ordinary model-facing saves, updates or staged curation. The
278
- runtime does not silently invent operator approval.
279
- The full proposal is reviewable before application; no additional mandatory confirmation loop is added.
280
-
281
- ## Automatic semantic review
282
-
283
- The user-authorized automatic path uses the same validation and fingerprint-checked mutation boundary.
284
- It is session-scoped, on by default unless `PI_PERSONA_MIND_OPTIMIZE=off`; `/mind optimize auto
285
- [status|on|off]` reads or changes that session's setting. Off cancels running review and clears queued
286
- targets/retry permissions; saves while off do not queue work. On waits for the next successful save.
287
- Doctor reports the scheduler's current status. No persistent preference is silently written.
288
-
289
- A successful remember/promotion marks its eligible tier dirty. The first eligible burst needs no
290
- token minimum. Later attempts require dirty memories and 1,000,000 main-session input tokens since
291
- the preceding actual launch, including an explicit review; output, cache read/write and worker tokens are excluded. Usage alone
292
- cannot dirty a tier. Rapid additions coalesce, and dirty tiers left after a review wait for the same
293
- token gate rather than launching in a cleanup loop. Token counters restart at zero on activation;
294
- the native session's attempt records preserve whether the first attempt already happened.
295
- Requests coalesce for two seconds after native `agent_settled`, while idle and without queued work.
296
- Actual worker attempts have a five-minute cooldown and only one may be in flight per Mind instance.
297
- Explicit commands bypass automatic admission gates but record their actual launches and settled
298
- digests. They never receive automatic retry permission when interrupted. Failed attempt persistence
299
- cancels and joins the admitted worker before releasing the active slot.
300
- Separate started/settled receipts preserve the attempt target and cooldown without treating an
301
- interrupted review as completed. Restore considers only the latest attempt for each target, so an
302
- older interrupted input cannot reappear after its changed-input retry has settled. A semantic digest
303
- skips unchanged settled inputs, including terminal refusals. Only a retry of the interrupted attempt
304
- bypasses the token gate, at most once per unchanged input digest; it still requires a later native
305
- settled event and cooldown. Cancellation alone never rearms it. Two consecutive interrupted automatic
306
- launches of the same tier and digest (a stop, a foreground interruption, or a host that reports its
307
- worker deadline as stopped) park that window: rotation bypasses it without recording it as reviewed or
308
- settled, bypasses it again whenever it returns to it unchanged, and reviews it again once its records
309
- change. Parking is derived from the persisted attempt receipts (the last 64), so turning automatic
310
- review off, in-memory retry state and a restart all give the same answer; turning it off removes the
311
- permission to retry, never the fact that the retry was used. A pending retry whose own window, at the
312
- cursor it was launched from, no longer yields its input is dropped without a receipt. A retry whose
313
- position cannot be verified (after a restart, or when another run moved the cursor) stays owed as one
314
- token-free admission for that tier, used by the next dirty write and superseded by any launch on the
315
- tier. Neither records the interrupted input as settled. A worker result with status `failed`
316
- (including Persona's 180-second deadline) is terminal for that input and never earns a token-free
317
- retry. Explicit reviews are unaffected. Unexpected current-owner failures persist terminal suppression without advancing
318
- the page cursor; a warning asks for inspection when an apply may have completed. If persistence itself
319
- fails, durable retry suppression cannot be guaranteed and the failure remains visible.
320
- Incoming input, `agent_start`, native branch navigation, off,
321
- session/persona/workspace changes and shutdown cancel and invalidate pending plans. Native branch
322
- navigation preserves session identity but interrupts the old consolidation generation: its worker cannot
323
- apply or report on the new branch. Explicit work never earns an automatic retry; automatic work retains
324
- the documented later-settled/cooldown retry policy through a fresh worker, not reuse of an old proposal. Delegated legs
325
- do not recursively schedule automatic workers. Shared memories are excluded.
326
-
327
- Persona hosts a real asynchronous Mind worker, visible in its standard agent view. The exact current
328
- session model is the only allowed selection: no alternate provider/model or fallback. The worker has
329
- no arbitrary tools, a 180-second deadline, and at most 12 full source records within 24,000 JSON
330
- characters, with explicit IDs and provenance. Selection normally reserves the newest eligible
331
- record. If it would crowd out the next full record or separate a same-kind pair that fits without
332
- it, that window gives the older records priority. Selection rotates within and across pages.
333
- Each tier keeps the current page's
334
- ordered IDs in memory (up to 100). The next page follows a recording-time and ID boundary, so new
335
- writes and changes to last-seen time cannot push older facts continually out of reach. The next
336
- sweep can include records restored behind an already traversed boundary. Reactivation starts from
337
- the first page. Progress is session/scope-local and
338
- advances only for completed reviews or explicitly ineligible/already-reviewed sets; cancelled work
339
- does not count as reviewed. Byte-excluded records remain eligible on later passes. Coverage requires
340
- further admitted triggers, never an unbounded autonomous sweep. Its output is strict JSON with at most four replacement
341
- operations and at most 12 source IDs per operation, never direct storage writes. Automatic application
342
- requires at least two compatible supplied source IDs in every operation. A proposal containing a
343
- single-record rewrite is not staged or applied automatically; the completed attempt is settled without
344
- an automatic retry loop. Single-record correction remains available through explicit workflows. A
345
- selected automatic window with no same-kind pair starts no worker and consumes no actual-attempt
346
- allowance. A merge count alone still does not establish semantic truth; conflicting conclusions must
347
- not be adjudicated by the background reviewer.
348
-
349
- A foreground settle observed while cancelled work finishes still counts toward the next eligible
350
- retry. New foreground input invalidates that idle signal. Competing sessions may review the same
351
- tier, and the fingerprint check prevents a stale proposal from overwriting newer facts.
352
-
353
- The parent rejects malformed, unsafe, unattributed, stale or foreign-owner changes and applies accepted
354
- replacements through the existing plan/CAS boundary. Kind does not change lifetime: consolidating
355
- owned short-term objectives stays in project STM and preserves the earliest expiry. Unrelated rows
356
- survive, and semantic deletion by age is not introduced.
357
-
358
- Before apply, the complete automatic proposal is appended to an unrendered native audit entry; append
359
- failure still prevents application. Durable store before images and guarded undo remain unchanged.
360
- An actual automatic change produces one lowercase `mind` information toast using the scheduler's
361
- existing structured target and summary, without adding a routine transcript result card.
362
- Automatic no-ops settle silently while retaining attempt/digest/status evidence. Failures, refusals and
363
- uncertain receipt finalization remain visible with an important warning. Explicit/manual reports keep
364
- their detailed cards. The unrendered proposal audit preserves worker/model/effort and result reference;
365
- `/mind optimize history <target>` exposes durable changes and undo provenance. The real worker's
366
- normal Persona row uses lowercase `mind` and terminates through the same tracked lifecycle.
367
- No semantic-quality guarantee or invented token savings follows from execution.
368
-
369
- ## Durable files and recovery
370
-
371
- Under <agentDir>/persona-mind/:
372
-
373
- - memory/ltm/<persona>.json and memory/ltm/_shared.json
374
- - memory/project/<project>.json
375
- - memory/stm/<project>.json
376
- - backlog/<project>.json
377
-
378
- Stores carry version, sequence, updatedAt and entries. Mutations use same-directory temporary writes,
379
- fsync, atomic rename, exclusive lockfiles and ownership checks. Directory fsync is best-effort on
380
- Windows. A live/foreign/malformed lock holder is never stolen merely for being old. Corruption is
381
- recovered or quarantined with diagnostics, never silently treated as an empty valid store.
382
- Backup recovery re-reads the live file after acquiring its exclusive lock: a writer that committed
383
- while recovery waited takes precedence over the previously observed backup. Recovery never overwrites
384
- that new live state or replaces a healthy backup with the damaged/missing state it is repairing.
385
- Windows sharing conflicts during recovery-gate acquisition return to the existing bounded lock
386
- wait; they never authorize entering the protected callback or deleting another recovery gate.
387
- Ordinary memory stores default to 10,000 entries and 4 MiB; writes over capacity fail without truncating
388
- existing facts. Backlog terminal retention and optimizer history have their own bounds. Retrieval and
389
- injection remain bounded independently of archive size.
390
- Third-party attribution and license notices are retained in [LICENSE](../LICENSE).
391
-
392
- Multi-store memory decisions serialize through one profile-wide memory transaction lock, anchored
393
- beside shared LTM. A project-only lock is insufficient: persona/shared facts are visible across
394
- projects, and another Pi could otherwise invalidate an ambiguity check before deletion. Lock order
395
- is memory transaction → target history transaction → individual store; backlog remains independently
396
- serialized. This is local same-profile coordination, not cross-host replication. Exocom scope aliases
397
- do not change Mind's actual workspace identity or import another Pi's memory. Intercom/Exocom reports
398
- remain untrusted material for explicit supervisor curation.
399
-
400
- Ordinary recovery and migrations preserve user data. Imports scan bounded historical layouts,
401
- deduplicate by semantic identity and reconcile the later record; originals are not removed.
402
- A background import is bounded per turn and may finish after the turn continues. Incomplete import
403
- means imported facts may not yet be available; it does not by itself prove corruption.
404
- While import is pending, startup/injection defer disk expiry cleanup instead of waiting again on
405
- the import's transaction lock. Read-time expiry filtering stays active; a later ordinary turn resumes
406
- disk cleanup. Progress is informational, shown once per import and cleared when the import settles.
407
-
408
- Expiry cleanup operates on the current entries under the mutation lock. Never compute a retained
409
- backlog snapshot before acquiring the write lock: a concurrent add would otherwise be erased.
410
- Promotion writes LTM before removing STM, so interruption leaves a duplicate rather than data loss.
411
- Promotion rechecks persisted source text, tags, origin and persona through the same content guard
412
- used by full reads, consolidation and undo. An unsafe out-of-band record stays in its original tier;
413
- it is not copied to durable/shared memory or removed from working memory.
414
- Backlog cleanup retains active items and bounded terminal history.
415
-
416
- ## Capture, injection and UI
417
-
418
- Persona exposes pi-persona:companion:v1 as a synchronous local capability query. Exactly one
419
- valid loaded provider is required; disabled, absent, ambiguous or incompatible responses refuse
420
- Mind access. Tools remain guarded even through programmatic executeTool. Real delegated legs
421
- receive memory capability for lean injection, not write tools or activity publishing.
422
-
423
- Local explicit optimization publishes pi-persona:activity:v1 only for actual inspect/stage/apply work. The closed
424
- payload contains session identity, activity identity, phase, state and target, never memory text,
425
- paths, model or token claims. Persona projects it as a Mind activity row, separate from agents and
426
- wake sources. It cannot be steered, stopped as a worker, counted as an agent or exported as agent
427
- telemetry. Pending proposals are staged, not running. Native owner and scope changes suppress
428
- late events; terminal rows have bounded retention. This is cooperative UI, not task authority.
429
-
430
- In AUTO mode, strong direct-user persistence cues may be captured deterministically before the model
431
- starts, but every such capture is provisional and writes only a native active-branch session note—never
432
- external project/persona/shared memory, migration destinations, or optimizer dirty state. This includes
433
- “remember”, “from now on”, and explicitly durable/permanent wording. The receipt says session-only, says
434
- no durable store was written, and invites a separate deliberate scoped memory call if broader retention
435
- matches actual user intent; it does not forbid deliberate durable curation. A session append failure
436
- has no durable fallback. Prompt mode remains nudge-only and off disables detection/capture. Quoted,
437
- fenced, peer, worker, extension-follow-up and unattributed content are not direct-user capture input.
438
- Leading negation such as “Never remember that …” is not stripped into a positive capture request.
439
- Decision extraction also rejects negation in a premise it would discard before `:`. Negative wording
440
- inside an affirmative fact (“Remember that I never …” or “We decided …: never …”) remains valid.
441
- No-cue input skips migration waits. Lifecycle/current-input/owner generations prevent stale capture
442
- notices; accepted notes stay with the original native owner and are never copied to a replacement session.
443
- Asynchronous status reads use that same owner guard: results and failures from a previous owner
444
- cannot replace the current owner's counts or display a stale storage warning after shutdown.
445
-
446
- Normal injection uses entry caps (8 persona/shared LTM, 4 project LTM, 5 STM, 6 backlog), plus a
447
- combined 2,400-token planning estimate across all memory blocks, including session notes (up to 600),
448
- wrappers and omission notices. The estimate is UTF-8 bytes / 3, not a provider tokenizer or billing
449
- guarantee. Whole excerpts are admitted, with bounded objective/invariant priority; they never bypass
450
- the cap. Full reads are
451
- explicit; no whole worker report is inserted as a memory merely because it exists. Scanner checks
452
- run on admission and resurfacing, including new full-read source/tags. Scanning/fencing mitigates
453
- unsafe content but cannot prove semantic truth or provide a security boundary against same-process code.
454
-
455
- Nested report provenance follows Pi parentToolCallId, never guessed ID syntax. Only a visible relayed
456
- blocked report from delegate/council/flow can suggest backlog capture. Discarded nested reports do not.
457
- Bound and clear relay state at settlement.
458
-
459
- Wakes are display-only appendEntry plus a short toast, never sendUserMessage/triggerTurn. Acknowledged
460
- due reminders are not replayed. Newly due reminders are armed immediately and cancel on closure.
461
- Keep pending/delivered deadline identity across maintenance re-arms. Persistence acknowledges only
462
- the exact `(id, dueAtEpochMs)` shown to the user, compared under the backlog write lock; an old
463
- acknowledgement cannot consume a concurrent renewal. It clears that deadline, not the backlog item.
464
-
465
- Standalone cards use Persona's single `createCardFrame` implementation through the synchronous local
466
- `pi-persona:card-frame:v1` presentation query. Mind mirrors the small structural contract and queries
467
- at each renderer invocation, without hard-importing an optional package or caching a factory across
468
- reload. Missing, incompatible, ambiguous or throwing providers use a minimal sanitized full-text
469
- history fallback, not a second styled card engine. This port conveys no memory, scheduling or
470
- security authority. Presentation models carry title, semantic state, full body, width-aware preview,
471
- optional metadata and Markdown; the frame owns theme, truncation, expansion and padding. Custom-entry
472
- renderers pass their original stable entry object as optional `CardFrameContext.expansionKey`; the
473
- shared frame owns any click/keyboard synchronization, keyed weakly without retaining entry text. A
474
- missing key is presentation-only (native tool renderers retain their host-owned interaction shell).
475
-
476
- Entry cards read the current public `pi.getSettings().outputPad` (native 0/1, default 1) because entry
477
- render options omit it, and use host-provided expand hints. Native memory/backlog tool results retain
478
- Pi's shell and receive no duplicate padding or standalone frame. Saved-memory receipts use a compact
479
- summary with an expand hint; expansion reveals the original receipt, including its addressable ID,
480
- without rewriting the tool payload or repeating the call title. A session read is not a save receipt. Optimization previews must retain their
481
- selected-window qualification and never imply every record was reviewed; expansion retains worker,
482
- model/effort and terminal-reference provenance. Commands retain reports in custom-entry history;
483
- warnings/toasts stay short and are not duplicate durable cards. Display callbacks must still belong
484
- to their accepting session and scope after asynchronous reads.
485
-
486
- ## Read-only memory inspector
487
-
488
- F10 and `/mind browse [memories|context|timeline]` open one native TUI inspector; `/mind timeline`
489
- selects its timeline tab. Existing bare `/mind` and `/mind session` reports remain unchanged. RPC,
490
- print and JSON modes do not open custom TUI. Delegated legs do not receive the shortcut or browse
491
- access. Entry points require compatible Persona and the actual current native session owner.
492
-
493
- F10 obtains Persona's stateless frame through the synchronous local
494
- `pi-persona:inspector-frame:v1` query when opening. Both inspectors use the same width, row
495
- allocation, gutters and theme `border` role. Mind mirrors only the structural service contract,
496
- not a second painter; if the service is unavailable, opening reports a compatible-Persona/reload
497
- diagnostic while memory operations remain unchanged. Selection, tabs, sources, data admission and
498
- lifecycle remain Mind-owned. Page movement uses the actual rendered list/detail/source/help
499
- capacity, and narrow layouts shorten controls before hiding the selected record. The native search
500
- Input receives focus only during search.
501
-
502
- The inspector is a query/view layer, not a new memory engine. Its explicit `a` action launcher closes
503
- the overlay before opening native action/approval dialogs. Consolidation calls the existing bounded
504
- explicit optimizer for the chosen nonshared scope; the launcher does not create a second merge path.
505
- Knowledge review is a separate proposal workflow described below. Browsing alone remains read-only. Durable browsing reuses strict optimizer
506
- inspection (including safe/owned admission and pagination); opening it never repairs, migrates, saves,
507
- schedules, or starts a model call. Session browsing reuses native note replay. Home suppresses project
508
- scopes. Searches are literal browsing filters, not a replacement for the runtime retrieval ranker.
509
-
510
- Source metadata (`source`, `derivedFrom`, `supersedes`) remains literal, never an instruction to open
511
- paths, URLs or private worker archives. Successful explicit `memory remember` results carry a versioned
512
- native `recording` descriptor with the accepting persona, repository identity and target. A recording
513
- link requires an exact matching successful tool call/result, current fact content and scope identity
514
- within the bounded active branch. Old receipts without that attribution cannot establish such a link.
515
- Session-note links refer to validated native save events. These are recording provenance, not evidence
516
- that the assertion is true, nor automatic citations of a preceding user message. No store schema,
517
- retention policy, cross-session access grant or independent transcript archive is introduced.
518
-
519
- The timeline is an on-demand view of at most 2,000 newest native active-branch entries, with 40 results
520
- per page and explicit older-entry omissions. It includes user/assistant text and validated session-note
521
- save/forget events, never reasoning, image bytes, arbitrary custom reports or tool-result bodies.
522
- Message details are bounded to 32,000 characters with clipping disclosed. Search counts describe only
523
- that bounded window, not the user's complete conversation history. Tombstones remain historical events.
524
-
525
- Context inspection holds only the last block prepared by Mind in memory, including session notes,
526
- capture hints and omission notices. It never reconstructs a supposedly historical selection from today's
527
- stores, and never claims to observe the provider payload. The existing UTF-8-bytes/3 planning estimator
528
- and injection policy remain unchanged. A new process has no prior prepared-context snapshot.
529
-
530
- Native session/branch changes, owner revocation and persona/project changes clear that snapshot and
531
- abort the open inspector. Every asynchronous page read checks the accepting owner before and after IO;
532
- revoked results cannot repaint a different owner. UI content is sanitized, width-bounded and navigable
533
- without executing links or sending model messages. The user can explicitly refresh the view.
534
-
535
- ## Evidence-grounded knowledge review
536
-
537
- `/mind review [project|project-long|persona]` and F10's action menu run an explicit knowledge review.
538
- The default is durable project memory (persona at home). F10 can review a selected fact or a bounded
539
- scope window. Session/shared are not model-review write targets. The current Persona companion protocol
540
- admits only the exact active session model/thinking level; Mind does not infer a better model from names,
541
- change providers, or silently choose a fallback. The real visible `mind` worker still has no tools.
542
-
543
- The parent inspects safe, owned facts and admits at most six complete records within 12,000 JSON
544
- characters. The user explicitly selects up to six repository-relative text files. Trusted-workspace,
545
- containment, symlink, regular-file, size, secret and content checks gate reads; no recursive search,
546
- source-string path resolution, network access or private worker archive is used. Native user-role text
547
- is sampled only from a bounded active-branch window. A stored user role is not authenticated human
548
- intent: quotations, hypotheticals and programmatic messages must be critically assessed. Evidence
549
- snapshots carry IDs, labels, excerpts, hashes and coverage; omissions cannot establish absence.
550
-
551
- The task requires one classified finding per supplied fact: supported, proposed correction, conflict,
552
- insufficient evidence, or proposed retirement. The parent rejects unknown records/citations, duplicate
553
- findings, malformed fields and unsafe replacement text. Corrective operations preserve kind and scope;
554
- source lineage and bounded evidence references survive consolidation. These checks establish attribution
555
- and structural validity, not factual truth. Local repository evidence must not turn a repository-specific
556
- rule into a universal persona preference; age and latest mention alone are not obsolescence evidence.
557
-
558
- There is NO automatic application. A complete native proposal report shows reasons, cited evidence,
559
- coverage and before/after corrections. `/mind review show` reopens it; `/mind review apply` displays it
560
- and asks for explicit approval. The staged plan lives in a dedicated optimizer instance, not the generic
561
- memory-tool plan cache, so `/mind optimize apply` cannot bypass evidence validation. Approval reacquires
562
- maintenance admission, checks evidence freshness and applies through the same CAS/history/undo boundary.
563
- A synchronous parent evidence guard runs again inside the guarded store callback. This verifies source
564
- state at the check, not a transaction locking arbitrary repository files against external writers.
565
-
566
- Retirement is deliberately recommendation-only: the reviewer cannot delete a standalone memory.
567
- A deliberate scoped `memory forget` remains available for a separately judged retirement, with its
568
- existing semantics (not consolidation undo). No delete-shaped optimizer plan, new durable schema or
569
- unbounded history is introduced. `/mind review discard` cancels/discards pending work; an applied change
570
- requires the ordinary history/undo workflow.
571
-
572
- A parent review reservation prevents automatic and explicit consolidation from overlapping collection
573
- or worker execution. Only actual review launches reset automatic usage/cooldown accounting and persist
574
- explicit attempt markers; interruptions never create an automatic retry entitlement. Staging releases
575
- the worker reservation rather than holding it while waiting for a human. Apply must acquire a new one;
576
- concurrent writes or expired plans are refused. New input, agent/model/branch changes, owner revocation
577
- and shutdown cancel workers/dialogs and invalidate pending review plans. Shutdown joins admitted apply
578
- work through approval, guarded persistence, receipt finalization and lease cleanup; it bounds only the
579
- wait for a Persona worker's completion (5 s), and a wait that reaches the bound is treated as an
580
- interruption. Revocation blocks new
581
- admission and guarded writes, but does not roll back an already committed replacement or relabel it as
582
- cancelled; its finalization is still awaited and stale completion UI is suppressed. Completion uses display-only
583
- native entries/toasts and never triggers a supervisor turn.
584
-
585
- ## Verification boundaries
586
-
587
- The source-checkout `eval:memory` command reports individual paired sentinel ranks and actual bounded
588
- injection outcomes, retaining historical queries and corruption/removed-fact negative controls.
589
- Token diagnostics compare the unchanged UTF-8-bytes/3 estimate to pinned published reference vectors,
590
- with exact input/token-ID hashes and source provenance. All inputs use the same calculation: no
591
- language detector, language-specific factor, local tokenizer execution or runtime network request.
592
- The reference encoding is not the current model's billing counter, and eight curated vectors do not
593
- establish broad language coverage or justify automatic budget tuning. The runtime budget is unchanged.
594
-
595
- Tests isolate PI_PERSONA_* and use a throwaway profile, the actual Pi 1.7.0 SDK/tool pipeline and
596
- offline providers, and join session_shutdown before SDK disposal. Native session tests cover persisted
597
- reopen, branch/fork, in-memory behavior and owner revocation. Store tests cover lost writes, stale plans,
598
- invalid inputs and concurrent apply. Installed-host/package qualification complements source tests.
599
-
600
- The [post-release source audit](https://github.com/AeonDave/pi-persona-mind/blob/main/docs/reviews/2026-11-12-post-release-audit.md)
601
- records the qualified snapshots, large-store checks, concurrent-writer stress tests and real-provider
602
- smokes, with their evidence and platform limits.
603
-
604
- Passing these checks proves tested behavior, not perfect memory, semantic compression quality, external
605
- provider authentication or every operating system. CI provides separate Windows/Linux/macOS evidence.
1
+ # pi-persona-mind — current design
2
+
3
+ This is the binding implementation contract. Release history belongs in [CHANGELOG](../CHANGELOG.md);
4
+ the user workflow is in [README](../README.md). Local design rationale and evaluation boundaries are in
5
+ [MEMORY-RESEARCH](MEMORY-RESEARCH.md).
6
+
7
+ ## Host and module boundaries
8
+
9
+ This design contract describes the current development tree; released changes are recorded separately
10
+ in CHANGELOG.md.
11
+
12
+ Target the latest stable Pi only, currently 1.7.0, and Node >=22.19. All four development Pi packages
13
+ are pinned together; runtime host/typebox packages remain optional wildcard peers. No second host
14
+ runtime or historical hook-shape adapter is bundled. A development-only security override does not
15
+ patch an installed host.
16
+
17
+ Mind and Persona use the profile Pi selects through `--agent-dir` or `PI_CODING_AGENT_DIR`.
18
+ `PI_AGENT_DIR` applies when it is the only profile override. Mind resolves the profile when the
19
+ extension loads, after Pi has applied the CLI flag.
20
+
21
+ Mind requires a loaded compatible pi-persona through its versioned local companion handshake.
22
+ Missing/incompatible presence leaves tools inactive and suppresses capture, storage/import,
23
+ injection and reminders. A settings file or installed npm package is not proof of an active
24
+ companion. Mind requires Persona 1.18.1 or later for these paired contracts. Its optional npm
25
+ peer declares that requirement without auto-installing or activating another extension.
26
+
27
+ The node-only core has no Pi imports. The factory wires native Pi hooks, tools, scope, scheduling
28
+ and lifecycle owners. Session persistence uses Pi's public SessionManager and appendEntry contracts.
29
+ Command parsing/presentation lives outside the factory. Important seams:
30
+
31
+ | Module | Responsibility |
32
+ |---|---|
33
+ | core/service.ts | Scope-bound memory/backlog operations, mutation ordering |
34
+ | core/store.ts | Atomic writes, exclusive ownership, recovery, strict snapshots and CAS |
35
+ | core/memory.ts, backlog.ts | Validated facts, shared persisted-content guard and deferred-work state |
36
+ | core/scope.ts, mind-settings.ts | Project identity, safe paths and canonical Mind preferences |
37
+ | extension/persona-dependency.ts | Loaded capability and actual memory-owner contracts |
38
+ | core/migrate.ts | Bounded, non-destructive import of previous memory layouts |
39
+ | core/session-memory.ts, session-memory.ts | Session event validation/replay and native owner adapter |
40
+ | core/optimize.ts, optimize-service.ts | Pure consolidation rules and short-lived staged plans |
41
+ | core/optimize-history.ts | Bounded durable before images and conflict-checked undo |
42
+ | core/handoff.ts, handoff-store.ts | Explicit scoped handoff snapshots, revision checks and bounded persistence |
43
+ | core/retrieval.ts, context-budget.ts | Explainable task ranking and shared context estimate |
44
+ | core/memory-read.ts | Full explicit retrieval without clipped discovery or recovery writes |
45
+ | tools/memory.ts, memory-optimize.ts | Model-facing action validation and result formatting |
46
+ | extension/mind-command.ts | One command handler for persona-mind and mind |
47
+ | ui/ | Sanitized compact cards, full expansion and native custom-entry renderers |
48
+
49
+ ## Four lifetimes
50
+
51
+ - **Durable facts:** persona-private LTM, explicit shared LTM and repository-scoped project LTM.
52
+ Never expire automatically. Project facts remain repository-bound across persona changes.
53
+ - **Working project facts:** STM with persona attribution; 48-hour default TTL. Project injection can include
54
+ other personas' observations, but optimizer mutations require the current persona's ownership.
55
+ - **Session notes:** native custom entries on the active branch, including source session identity.
56
+ - **Deferred intent:** project backlog, open/taken/done/dropped. Default expiry is 48 hours; a later
57
+ reminder extends it. A repeated take is idempotent; re-add does not reopen completed work.
58
+
59
+ LTM/STM facts have content identity based on kind, text and sorted tags; provenance is excluded.
60
+ Exact re-recording updates identical normalized content (not semantic equivalence). lastSeenAt tracks recording/promotion, not
61
+ recall frequency. Read operations do not boost ranking or reset expiry. `term` alone selects lifetime:
62
+ `kind: objective` is not automatically promoted, so a short objective remains expiring project context
63
+ and a session objective remains on that active native session branch.
64
+
65
+ Exact re-recording preserves existing `source`, `derivedFrom` and `supersedes` when no replacement
66
+ metadata is supplied; nonempty replacement metadata updates the corresponding value. In `remember`,
67
+ an empty source or empty `derivedFrom` list is treated as omitted, not as a request to clear provenance.
68
+ `remember` supersession retires an active row in its selected destination tier. A target found only
69
+ in another tier is refused before writing; moving a fact and replacing one are separate operations.
70
+ derivedFrom stores bounded IDs. Optimizer before images provide
71
+ bounded recoverability; ordinary supersession/forget are not a temporal database or unlimited undo.
72
+ Every long-term `remember` requires an explicit destination: project LTM, persona LTM, or shared LTM;
73
+ there is no implicit persona destination. Short-term memory remains project-scoped by default. Promotion
74
+ defaults to project LTM and requires an owned live STM source; persona/shared promotion destinations
75
+ must be explicit. A scope value selects API routing intent; it is not authenticated user consent. Use
76
+ session for task-specific or uncertain choices (models, strategies, task constraints), project for
77
+ stable repository facts, persona for facts intended across all projects of the same persona, and shared
78
+ only for facts truly intended across personas. Existing persona facts are never reassigned to guessed projects. Promotion removes
79
+ only its exact source row; equal-text observations from another owner retain their provenance.
80
+
81
+ ## Scope and companion integration
82
+
83
+ The active persona comes only from pi-persona:memory-owner:v1, a synchronous query bound to the
84
+ native session ID. Its response identifies the loaded provider, readiness and actual persona (or
85
+ null for no persona). pi-persona:memory-owner-changed:v1 broadcasts readiness and selection changes.
86
+ Before Persona finishes startup, Mind returns without memory IO; it must not await a later extension's
87
+ session_start. Missing, ambiguous or stale owners refuse access. Saved selection and CLI flags are
88
+ not substitutes for the runtime owner, including when Persona persistence is disabled.
89
+
90
+ Mind capture/nudge preferences are session snapshots from canonical
91
+ <agentDir>/persona/settings.json. The retired state.json and PI_PERSONA_STATE_FILE are not runtime
92
+ sources; Persona owns its settings migration. Contribute effective Mind preferences through
93
+ pi-persona:settings:collect:v1; never edit companion settings or start another service.
94
+
95
+ Use the canonical project path and collision-safe persona scope names. Reserved shared/default
96
+ names, lossy Unicode conversions and Windows device names must not merge unrelated personas.
97
+ Home is not a project: skip project injection and reminders there.
98
+
99
+ A delegated leg is sampled at factory activation through PI_PERSONA_LEG / PI_PERSONA_CHILD.
100
+ PI_PERSONA_DISABLE alone does not designate a worker. Workers get lean objective/LTM injection,
101
+ no project/session notes, no memory/backlog tools and no reminders. Both Persona engines freeze the
102
+ launching persona. In-process workers receive it through their own extension bus; child processes
103
+ receive a scrubbed spawn-local payload. A later parent selection cannot move a worker's memory scope.
104
+ Mind appends worker memory through Pi's prompt options. Persona can preload the selected skill
105
+ bodies in Pi's skills section and verify both inputs when the worker resumes. Pi records the
106
+ worker's memory excerpts in its native system messages when the worker transcript is saved.
107
+ For a persisted worker with one valid Persona v1 contract on the active branch, lean memory ranking
108
+ uses the first user turn after that contract. Labels such as `today` and `1d` in the worker's lean
109
+ memory refer to that launch turn's timestamp. Mind reads current durable memory for each turn, and
110
+ Persona checks the resulting prompt against the saved contract.
111
+
112
+ After upgrading from 0.9.5, a worker saved with memory in a full-prompt override can report
113
+ `prompt configuration` on resume. Start a fresh delegation with the same brief and skills in that case.
114
+
115
+ Intercom/Exocom and worker output stay foreign reference material, not automatic capture requests.
116
+ Only the reserved pi-persona-deferred-input custom type replays direct user input. This is a
117
+ trusted-extension convention, not authentication against other code running in the same process.
118
+ Do not read Persona's private result archive. The supervisor explicitly retrieves a report through
119
+ Intercom before curating a fact. A saved ref remains an opaque source string, not a cross-session grant.
120
+
121
+ ## Session notes
122
+
123
+ Version-1 save/forget events live under pi-persona-mind-session-note. Reads replay only the active
124
+ branch; all session events count toward the lifetime budget. Branching/forking follows native Pi
125
+ history; new sessions do not inherit notes. Forked notes preserve originSessionId. A forget appends
126
+ a branch-local tombstone and does not erase previous transcript bytes.
127
+
128
+ Limits: 64 active notes, 8,000 text characters per note, 1,000 source characters, 256 lifetime events,
129
+ 512 KiB encoded event data. Unknown versions, unsafe history or exceeded bounds fail closed.
130
+ Admission and replay both scan content. No append occurs after owner revocation; owner identity
131
+ includes the native manager, session ID and file. No asynchronous gap separates validation and append.
132
+
133
+ Receipts distinguish session storage from memory-only storage; Pi controls disk flushing.
134
+ An identical automatic capture reuses the active note when kind, text and source match.
135
+ It consumes no additional note or history slot and produces no new notification. After a
136
+ branch-local forget, the user can capture it again. Explicit writes keep their own provenance.
137
+ Injection is reference data, escaped and bounded to a 600-token planning estimate (UTF-8 bytes / 3)
138
+ with excerpts of at most 700 characters. It shares the total memory budget. Current task matching
139
+ precedes recency, with objective priority. Omitted entries and clipping are disclosed. Explicit read returns the whole note.
140
+ An in-memory session is not advertised as restart-durable.
141
+
142
+ The supervisor gets one request-local, labelled memory reference. Pi converts it to user-role
143
+ content for the provider. On ordinary tool continuations the reference stays at the turn's
144
+ starting input. If Pi compacts inside the run, Mind rebuilds it from the current owner's stores
145
+ and active-branch notes and places it before the native summary. This preserves changes made by
146
+ tools since the run began. Mind adds no reference to the session log or summary prompt.
147
+ The worker retains its separate lean system-prompt contract and selected skills. Explicit
148
+ memory tool arguments, results and anything the model repeats follow Pi's ordinary history rules.
149
+
150
+ Pi can also replay a previously sent request to warm an eligible provider cache. If the memory
151
+ owner changes, that replay can still contain the previous owner's reference. Pi 1.7.0 reuses the
152
+ original request context. Its warming decision exposes costs and an action without a request ID,
153
+ so Mind cannot reliably veto only that replay. Pi's global `cacheWarming`
154
+ setting defaults to `"idle"` for eligible, cost-effective requests. `"streaming"` limits warming
155
+ to active runs, and `"off"` disables warm requests. [Pi 1.7.0 settings](https://github.com/earendil-works/pi/blob/v1.7.0/packages/coding-agent/docs/settings.md)
156
+
157
+ ## Cross-session handoffs
158
+
159
+ `memory { action: "handoff", handoff: { operation: "save", goal, completed, pending, nextStep,
160
+ references } }` stores an explicit snapshot. `completed`, `pending` and `references` are arrays of
161
+ strings. `list` discovers metadata; `read` with `id` returns the snapshot. `complete` requires `id`,
162
+ the latest `revision` and a `resolution`; `forget` requires `id` and `revision`. These actions share
163
+ the existing memory tool, not another tool or model service. `/mind handoff list`,
164
+ `/mind handoff show <id>`, `/mind handoff complete <id> <revision> <resolution>` and
165
+ `/mind handoff forget <id> <revision>` provide operator access.
166
+
167
+ Handoffs belong to the actual project and active persona, with the native source session/branch
168
+ and cwd recorded as provenance. A later independent session may explicitly read the same owner's
169
+ handoff. Home sessions and delegated workers cannot access this surface. The live owner is checked
170
+ before IO, after reads and under the write lock; branch/session changes revoke pending operations.
171
+ Stored content is untrusted, scanned and fenced. References remain literal strings, never automatic
172
+ file reads or tool instructions.
173
+
174
+ One `<STM store>.handoffs.json` sidecar is shared by all personas with owner-filtered access. Each
175
+ owner (persona + project) may hold up to 32 entries; the file as a whole is capped at 128 KiB, which is
176
+ its only total bound. Each record, including metadata, is limited to 16 KiB; the normal store backup
177
+ also applies. Listing uses 160-character goal previews and a 40 KiB formatted-output bound. Explicit
178
+ full reads are bounded to 100 KiB after JSON escaping; neither path silently truncates stored records.
179
+ There is no TTL or automatic eviction: at its own quota, a persona's new save fails until it forgets
180
+ one of its handoffs. A save refused by the file-wide byte cap reports the caller's own entry count and
181
+ the other personas' count, never their names, ids or content; when the other personas' entries alone
182
+ fill the file, the refused persona cannot free space itself. A sidecar that cannot be read strictly
183
+ 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
184
+ historical. It does not verify tests, execute pending tasks or claim a restored worker session.
185
+ Handoffs never join active fact recall, injection, consolidation or session-note replay.
186
+ `/mind reset` clears working memory and backlog only; handoffs require explicit `forget` by ID and
187
+ revision. This preserves a handoff intended for a later session during routine workspace cleanup.
188
+
189
+ ## Replacement history
190
+
191
+ An ordinary `remember` with `supersedes` that retires an existing fact writes a before/after receipt
192
+ through the same write-ahead/CAS helper and bounded store used by consolidation. `origin: replacement`
193
+ distinguishes it from `optimization`; it has no invented plan ID or model-generated reason. If the
194
+ destination already contains the resulting fact, its prior metadata is retained as well. Plain saves,
195
+ exact re-recording, self-supersession and missing-source lineage do not create receipt noise.
196
+ The destination tier is read strictly (it anchors the compare-and-swap); the other tiers are read with
197
+ ordinary recovery but must be read completely, because one of them could hold a second fact with the id
198
+ being superseded. A tier counts as completely read only when it was read cleanly, is genuinely absent
199
+ (no live file and no backup), or was restored in full from a valid backup. Hidden rows, a quarantine,
200
+ or a backup that exists but cannot be used while the live file is absent leave it unread, and the
201
+ replacement is refused, naming that store.
202
+
203
+ `memory { action: "history", target: "project-long" }` and `/mind history project-long` list compact
204
+ metadata. For detail, provide `receiptId` and an explicit target; `offset` pages 12,000 UTF-16 units
205
+ of serialized before/after JSON. `/mind history show <receiptId> <target> [offset]` is the command
206
+ equivalent. Targets are `project` (working memory), `project-long`, `persona` and `shared`; listing
207
+ defaults to `project`. `/mind optimize history` uses the same compact discovery view.
208
+
209
+ Only the modifying persona can inspect its receipts, with persisted-content scanning on reads.
210
+ Historical values remain outside active recall and injection. Ordinary replacement receipts are
211
+ read-only: optimizer undo refuses them. Consolidation receipts retain their guarded undo path.
212
+ Retention and interrupted-write behavior are the same for both origins, as described below.
213
+ `/mind reset` does not delete these receipts; history follows its own bounded retention policy.
214
+ Ordinary saves and replacements recheck the accepting session/branch/persona at admission and under
215
+ the store lock. A source or replacement that expires while awaiting commit is refused. Revocation
216
+ after a completed write reports possible persistence in the original scope without exposing stale
217
+ record content or claiming rollback.
218
+
219
+ ## Explicit consolidation
220
+
221
+ 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.
222
+
223
+ The manual workflow is inspect → stage exact replacements → apply plan ID. An omitted replacement tag
224
+ list inherits the normalized union from selected sources; an explicit empty list clears tags. Lexical
225
+ rules never approve semantic changes. Learned decay rates, recall counters and age-based LTM deletion
226
+ remain outside the contract.
227
+
228
+ Inspection reads a strict store snapshot without recovery/quarantine writes. It returns at most 100
229
+ safe entries (20 by default), an exact raw-byte fingerprint, omission counts and at most 12 lexical
230
+ candidate pairs. Similarity is advisory: negation can preserve nearly all words while reversing meaning.
231
+ Inspection exposes offset/matched/nextOffset so old facts remain reachable in bounded pages;
232
+ fingerprint changes invalidate a paginated inspection's snapshot. Pairs compare one page only.
233
+ The foreground agent must inspect full text and current evidence before proposing replacements.
234
+
235
+ Each plan affects one store: `project` STM, `project-long` durable repository memory, persona LTM,
236
+ or shared LTM. Both project tiers require the current persona's ownership. One source rewrites a fact;
237
+ multiple sources consolidate facts. Explicit deletion remains memory forget. Operations specify exact
238
+ persisted source IDs; ambiguous/overlapping IDs, unsafe content, mixed ownership, replacement collisions,
239
+ expired sources, malformed stores and provenance overflow refuse the plan.
240
+
241
+ A replacement keeps earliest recording time, all bounded source origins and lineage. Project replacements
242
+ keep the earliest source expiry; consolidation cannot revive or extend stale working context.
243
+ Unselected entries are preserved. No capacity-enforcing truncation is allowed.
244
+
245
+ At most four plans per session/scope owner, ten-minute lifetime. Preview is immutable to callers.
246
+ Invalidation during an asynchronous preview read also refuses that preview; it cannot stage a new
247
+ plan belonging to the invalidated owner after the read returns.
248
+ Apply rechecks raw-byte fingerprint, lifetime, source expiry and owner invalidation under the store lock
249
+ and Mind's mutation lock. Even a same-sequence external file replacement invalidates the fingerprint.
250
+ Concurrent apply cannot commit twice. Session/scope changes and native branch navigation discard plans;
251
+ appending ordinary turn entries does not invalidate an owner. Applying never spawns a model.
252
+
253
+ Before replacement, persist a scoped before/after receipt to `<store>.optimize-history.json`, under
254
+ its transaction lock and the memory mutation lock. Maximum 32 receipts / 2 MiB per target, plus the
255
+ standard backup. Evict settled receipts only; refuse the replacement if unresolved prepared receipts
256
+ or the new receipt exceed capacity. A capacity error, a conflict, a callback refusal,
257
+ or any other failure after which the memory store still holds the bytes the receipt was prepared
258
+ against settles the receipt rejected: the replacement is not in effect, whether it never landed or
259
+ backup recovery rolled it back, so there is nothing to undo. Only a changed or unreadable store leaves
260
+ the receipt prepared with outcome uncertainty. Receipts record the store fingerprint they were
261
+ prepared against (history detail omits it, like the store path). At history capacity, prepared
262
+ receipts of the same store, owner and target whose recorded fingerprint equals the current one are
263
+ resolved as rejected and become evictable; receipts without a fingerprint (written before 0.9.4),
264
+ prepared against other bytes, or belonging to another owner stay protected. Finalization failure after a successful memory commit returns success with a warning.
265
+
266
+ History/undo survive optimizer recreation. History is bounded, owner-filtered and scanner-filtered.
267
+ Undo restores only exact affected facts, preserving unrelated current records; it refuses changed
268
+ replacements, source collisions, expired facts and owner revocation. Check the lifecycle generation
269
+ inside the store mutation callback. An ambiguous interrupted receipt is never presumed applied or
270
+ discarded; unresolved IO failures can require manual recovery. This is consolidation recovery,
271
+ not rollback of arbitrary user edits or a claim of semantic correctness.
272
+
273
+ These are authorization mechanics, not truth verification: an explicit memory tool call has the same
274
+ mutation authority as existing remember/forget. The LLM chooses the destination by meaning and context;
275
+ users need not provide API scope names or a literal “global” keyword, and no new per-save confirmation
276
+ loop is imposed. Truly portable preferences remain eligible for persona/shared memory. Background
277
+ review eligibility does not restrict ordinary model-facing saves, updates or staged curation. The
278
+ runtime does not silently invent operator approval.
279
+ The full proposal is reviewable before application; no additional mandatory confirmation loop is added.
280
+
281
+ ## Automatic semantic review
282
+
283
+ The user-authorized automatic path uses the same validation and fingerprint-checked mutation boundary.
284
+ It is session-scoped, on by default unless `PI_PERSONA_MIND_OPTIMIZE=off`; `/mind optimize auto
285
+ [status|on|off]` reads or changes that session's setting. Off cancels running review and clears queued
286
+ targets/retry permissions; saves while off do not queue work. On waits for the next successful save.
287
+ Doctor reports the scheduler's current status. No persistent preference is silently written.
288
+
289
+ A successful remember/promotion marks its eligible tier dirty. The first eligible burst needs no
290
+ token minimum. Later attempts require dirty memories and 1,000,000 main-session input tokens since
291
+ the preceding actual launch, including an explicit review; output, cache read/write and worker tokens are excluded. Usage alone
292
+ cannot dirty a tier. Rapid additions coalesce, and dirty tiers left after a review wait for the same
293
+ token gate rather than launching in a cleanup loop. Token counters restart at zero on activation;
294
+ the native session's attempt records preserve whether the first attempt already happened.
295
+ Requests coalesce for two seconds after native `agent_settled`, while idle and without queued work.
296
+ Actual worker attempts have a five-minute cooldown and only one may be in flight per Mind instance.
297
+ Explicit commands bypass automatic admission gates but record their actual launches and settled
298
+ digests. They never receive automatic retry permission when interrupted. Failed attempt persistence
299
+ cancels and joins the admitted worker before releasing the active slot.
300
+ Separate started/settled receipts preserve the attempt target and cooldown without treating an
301
+ interrupted review as completed. Restore considers only the latest attempt for each target, so an
302
+ older interrupted input cannot reappear after its changed-input retry has settled. A semantic digest
303
+ skips unchanged settled inputs, including terminal refusals. Only a retry of the interrupted attempt
304
+ bypasses the token gate, at most once per unchanged input digest; it still requires a later native
305
+ settled event and cooldown. Cancellation alone never rearms it. Two consecutive interrupted automatic
306
+ launches of the same tier and digest (a stop, a foreground interruption, or a host that reports its
307
+ worker deadline as stopped) park that window: rotation bypasses it without recording it as reviewed or
308
+ settled, bypasses it again whenever it returns to it unchanged, and reviews it again once its records
309
+ change. Parking is derived from the persisted attempt receipts (the last 64), so turning automatic
310
+ review off, in-memory retry state and a restart all give the same answer; turning it off removes the
311
+ permission to retry, never the fact that the retry was used. A pending retry whose own window, at the
312
+ cursor it was launched from, no longer yields its input is dropped without a receipt. A retry whose
313
+ position cannot be verified (after a restart, or when another run moved the cursor) stays owed as one
314
+ token-free admission for that tier, used by the next dirty write and superseded by any launch on the
315
+ tier. Neither records the interrupted input as settled. A worker result with status `failed`
316
+ (including Persona's 180-second deadline) is terminal for that input and never earns a token-free
317
+ retry. Explicit reviews are unaffected. Unexpected current-owner failures persist terminal suppression without advancing
318
+ the page cursor; a warning asks for inspection when an apply may have completed. If persistence itself
319
+ fails, durable retry suppression cannot be guaranteed and the failure remains visible.
320
+ Incoming input, `agent_start`, native branch navigation, off,
321
+ session/persona/workspace changes and shutdown cancel and invalidate pending plans. Native branch
322
+ navigation preserves session identity but interrupts the old consolidation generation: its worker cannot
323
+ apply or report on the new branch. Explicit work never earns an automatic retry; automatic work retains
324
+ the documented later-settled/cooldown retry policy through a fresh worker, not reuse of an old proposal. Delegated legs
325
+ do not recursively schedule automatic workers. Shared memories are excluded.
326
+
327
+ Persona hosts a real asynchronous Mind worker, visible in its standard agent view. The exact current
328
+ session model is the only allowed selection: no alternate provider/model or fallback. The worker has
329
+ no arbitrary tools, a 180-second deadline, and at most 12 full source records within 24,000 JSON
330
+ characters, with explicit IDs and provenance. Selection normally reserves the newest eligible
331
+ record. If it would crowd out the next full record or separate a same-kind pair that fits without
332
+ it, that window gives the older records priority. Selection rotates within and across pages.
333
+ Each tier keeps the current page's
334
+ ordered IDs in memory (up to 100). The next page follows a recording-time and ID boundary, so new
335
+ writes and changes to last-seen time cannot push older facts continually out of reach. The next
336
+ sweep can include records restored behind an already traversed boundary. Reactivation starts from
337
+ the first page. Progress is session/scope-local and
338
+ advances only for completed reviews or explicitly ineligible/already-reviewed sets; cancelled work
339
+ does not count as reviewed. Byte-excluded records remain eligible on later passes. Coverage requires
340
+ further admitted triggers, never an unbounded autonomous sweep. Its output is strict JSON with at most four replacement
341
+ operations and at most 12 source IDs per operation, never direct storage writes. Automatic application
342
+ requires at least two compatible supplied source IDs in every operation. A proposal containing a
343
+ single-record rewrite is not staged or applied automatically; the completed attempt is settled without
344
+ an automatic retry loop. Single-record correction remains available through explicit workflows. A
345
+ selected automatic window with no same-kind pair starts no worker and consumes no actual-attempt
346
+ allowance. A merge count alone still does not establish semantic truth; conflicting conclusions must
347
+ not be adjudicated by the background reviewer.
348
+
349
+ A foreground settle observed while cancelled work finishes still counts toward the next eligible
350
+ retry. New foreground input invalidates that idle signal. Competing sessions may review the same
351
+ tier, and the fingerprint check prevents a stale proposal from overwriting newer facts.
352
+
353
+ The parent rejects malformed, unsafe, unattributed, stale or foreign-owner changes and applies accepted
354
+ replacements through the existing plan/CAS boundary. Kind does not change lifetime: consolidating
355
+ owned short-term objectives stays in project STM and preserves the earliest expiry. Unrelated rows
356
+ survive, and semantic deletion by age is not introduced.
357
+
358
+ Before apply, the complete automatic proposal is appended to an unrendered native audit entry; append
359
+ failure still prevents application. Durable store before images and guarded undo remain unchanged.
360
+ An actual automatic change produces one lowercase `mind` information toast using the scheduler's
361
+ existing structured target and summary, without adding a routine transcript result card.
362
+ Automatic no-ops settle silently while retaining attempt/digest/status evidence. Failures, refusals and
363
+ uncertain receipt finalization remain visible with an important warning. Explicit/manual reports keep
364
+ their detailed cards. The unrendered proposal audit preserves worker/model/effort and result reference;
365
+ `/mind optimize history <target>` exposes durable changes and undo provenance. The real worker's
366
+ normal Persona row uses lowercase `mind` and terminates through the same tracked lifecycle.
367
+ No semantic-quality guarantee or invented token savings follows from execution.
368
+
369
+ ## Durable files and recovery
370
+
371
+ Under <agentDir>/persona-mind/:
372
+
373
+ - memory/ltm/<persona>.json and memory/ltm/_shared.json
374
+ - memory/project/<project>.json
375
+ - memory/stm/<project>.json
376
+ - backlog/<project>.json
377
+
378
+ Stores carry version, sequence, updatedAt and entries. Mutations use same-directory temporary writes,
379
+ fsync, atomic rename, exclusive lockfiles and ownership checks. Directory fsync is best-effort on
380
+ Windows. A live/foreign/malformed lock holder is never stolen merely for being old. Corruption is
381
+ recovered or quarantined with diagnostics, never silently treated as an empty valid store.
382
+ Backup recovery re-reads the live file after acquiring its exclusive lock: a writer that committed
383
+ while recovery waited takes precedence over the previously observed backup. Recovery never overwrites
384
+ that new live state or replaces a healthy backup with the damaged/missing state it is repairing.
385
+ Windows sharing conflicts during recovery-gate acquisition return to the existing bounded lock
386
+ wait; they never authorize entering the protected callback or deleting another recovery gate.
387
+ Ordinary memory stores default to 10,000 entries and 4 MiB; writes over capacity fail without truncating
388
+ existing facts. Backlog terminal retention and optimizer history have their own bounds. Retrieval and
389
+ injection remain bounded independently of archive size.
390
+ Third-party attribution and license notices are retained in [LICENSE](../LICENSE).
391
+
392
+ Multi-store memory decisions serialize through one profile-wide memory transaction lock, anchored
393
+ beside shared LTM. A project-only lock is insufficient: persona/shared facts are visible across
394
+ projects, and another Pi could otherwise invalidate an ambiguity check before deletion. Lock order
395
+ is memory transaction → target history transaction → individual store; backlog remains independently
396
+ serialized. This is local same-profile coordination, not cross-host replication. Exocom scope aliases
397
+ do not change Mind's actual workspace identity or import another Pi's memory. Intercom/Exocom reports
398
+ remain untrusted material for explicit supervisor curation.
399
+
400
+ Ordinary recovery and migrations preserve user data. Imports scan bounded historical layouts,
401
+ deduplicate by semantic identity and reconcile the later record; originals are not removed.
402
+ A background import is bounded per turn and may finish after the turn continues. Incomplete import
403
+ means imported facts may not yet be available; it does not by itself prove corruption.
404
+ While import is pending, startup/injection defer disk expiry cleanup instead of waiting again on
405
+ the import's transaction lock. Read-time expiry filtering stays active; a later ordinary turn resumes
406
+ disk cleanup. Progress is informational, shown once per import and cleared when the import settles.
407
+
408
+ Expiry cleanup operates on the current entries under the mutation lock. Never compute a retained
409
+ backlog snapshot before acquiring the write lock: a concurrent add would otherwise be erased.
410
+ Promotion writes LTM before removing STM, so interruption leaves a duplicate rather than data loss.
411
+ Promotion rechecks persisted source text, tags, origin and persona through the same content guard
412
+ used by full reads, consolidation and undo. An unsafe out-of-band record stays in its original tier;
413
+ it is not copied to durable/shared memory or removed from working memory.
414
+ Backlog cleanup retains active items and bounded terminal history.
415
+
416
+ ## Capture, injection and UI
417
+
418
+ Persona exposes pi-persona:companion:v1 as a synchronous local capability query. Exactly one
419
+ valid loaded provider is required; disabled, absent, ambiguous or incompatible responses refuse
420
+ Mind access. Tools remain guarded even through programmatic executeTool. Real delegated legs
421
+ receive memory capability for lean injection, not write tools or activity publishing.
422
+
423
+ Local explicit optimization publishes pi-persona:activity:v1 only for actual inspect/stage/apply work. The closed
424
+ payload contains session identity, activity identity, phase, state and target, never memory text,
425
+ paths, model or token claims. Persona projects it as a Mind activity row, separate from agents and
426
+ wake sources. It cannot be steered, stopped as a worker, counted as an agent or exported as agent
427
+ telemetry. Pending proposals are staged, not running. Native owner and scope changes suppress
428
+ late events; terminal rows have bounded retention. This is cooperative UI, not task authority.
429
+
430
+ In AUTO mode, strong direct-user persistence cues may be captured deterministically before the model
431
+ starts, but every such capture is provisional and writes only a native active-branch session note—never
432
+ external project/persona/shared memory, migration destinations, or optimizer dirty state. This includes
433
+ “remember”, “from now on”, and explicitly durable/permanent wording. The receipt says session-only, says
434
+ no durable store was written, and invites a separate deliberate scoped memory call if broader retention
435
+ matches actual user intent; it does not forbid deliberate durable curation. A session append failure
436
+ has no durable fallback. Prompt mode remains nudge-only and off disables detection/capture. Quoted,
437
+ fenced, peer, worker, extension-follow-up and unattributed content are not direct-user capture input.
438
+ Leading negation such as “Never remember that …” is not stripped into a positive capture request.
439
+ Decision extraction also rejects negation in a premise it would discard before `:`. Negative wording
440
+ inside an affirmative fact (“Remember that I never …” or “We decided …: never …”) remains valid.
441
+ No-cue input skips migration waits. Lifecycle/current-input/owner generations prevent stale capture
442
+ notices; accepted notes stay with the original native owner and are never copied to a replacement session.
443
+ Asynchronous status reads use that same owner guard: results and failures from a previous owner
444
+ cannot replace the current owner's counts or display a stale storage warning after shutdown.
445
+
446
+ Normal injection uses entry caps (8 persona/shared LTM, 4 project LTM, 5 STM, 6 backlog), plus a
447
+ combined 2,400-token planning estimate across all memory blocks, including session notes (up to 600),
448
+ wrappers and omission notices. The estimate is UTF-8 bytes / 3, not a provider tokenizer or billing
449
+ guarantee. Whole excerpts are admitted, with bounded objective/invariant priority; they never bypass
450
+ the cap. Full reads are
451
+ explicit; no whole worker report is inserted as a memory merely because it exists. Scanner checks
452
+ run on admission and resurfacing, including new full-read source/tags. Scanning/fencing mitigates
453
+ unsafe content but cannot prove semantic truth or provide a security boundary against same-process code.
454
+
455
+ Nested report provenance follows Pi parentToolCallId, never guessed ID syntax. Only a visible relayed
456
+ blocked report from delegate/council/flow can suggest backlog capture. Discarded nested reports do not.
457
+ Bound and clear relay state at settlement.
458
+
459
+ Wakes are display-only appendEntry plus a short toast, never sendUserMessage/triggerTurn. Acknowledged
460
+ due reminders are not replayed. Newly due reminders are armed immediately and cancel on closure.
461
+ Keep pending/delivered deadline identity across maintenance re-arms. Persistence acknowledges only
462
+ the exact `(id, dueAtEpochMs)` shown to the user, compared under the backlog write lock; an old
463
+ acknowledgement cannot consume a concurrent renewal. It clears that deadline, not the backlog item.
464
+
465
+ Standalone cards use Persona's single `createCardFrame` implementation through the synchronous local
466
+ `pi-persona:card-frame:v1` presentation query. Mind mirrors the small structural contract and queries
467
+ at each renderer invocation, without hard-importing an optional package or caching a factory across
468
+ reload. Missing, incompatible, ambiguous or throwing providers use a minimal sanitized full-text
469
+ history fallback, not a second styled card engine. This port conveys no memory, scheduling or
470
+ security authority. Presentation models carry title, semantic state, full body, width-aware preview,
471
+ optional metadata and Markdown; the frame owns theme, truncation, expansion and padding. Custom-entry
472
+ renderers pass their original stable entry object as optional `CardFrameContext.expansionKey`; the
473
+ shared frame owns any click/keyboard synchronization, keyed weakly without retaining entry text. A
474
+ missing key is presentation-only (native tool renderers retain their host-owned interaction shell).
475
+
476
+ Entry cards read the current public `pi.getSettings().outputPad` (native 0/1, default 1) because entry
477
+ render options omit it, and use host-provided expand hints. Native memory/backlog tool results retain
478
+ Pi's shell and receive no duplicate padding or standalone frame. Saved-memory receipts use a compact
479
+ summary with an expand hint; expansion reveals the original receipt, including its addressable ID,
480
+ without rewriting the tool payload or repeating the call title. A session read is not a save receipt. Optimization previews must retain their
481
+ selected-window qualification and never imply every record was reviewed; expansion retains worker,
482
+ model/effort and terminal-reference provenance. Commands retain reports in custom-entry history;
483
+ warnings/toasts stay short and are not duplicate durable cards. Display callbacks must still belong
484
+ to their accepting session and scope after asynchronous reads.
485
+
486
+ ## Read-only memory inspector
487
+
488
+ F10 and `/mind browse [memories|context|timeline]` open one native TUI inspector; `/mind timeline`
489
+ selects its timeline tab. Existing bare `/mind` and `/mind session` reports remain unchanged. RPC,
490
+ print and JSON modes do not open custom TUI. Delegated legs do not receive the shortcut or browse
491
+ access. Entry points require compatible Persona and the actual current native session owner.
492
+
493
+ F10 obtains Persona's stateless frame through the synchronous local
494
+ `pi-persona:inspector-frame:v1` query when opening. Both inspectors use the same width, row
495
+ allocation, gutters and theme `border` role. Mind mirrors only the structural service contract,
496
+ not a second painter; if the service is unavailable, opening reports a compatible-Persona/reload
497
+ diagnostic while memory operations remain unchanged. Selection, tabs, sources, data admission and
498
+ lifecycle remain Mind-owned. Page movement uses the actual rendered list/detail/source/help
499
+ capacity, and narrow layouts shorten controls before hiding the selected record. The native search
500
+ Input receives focus only during search.
501
+
502
+ The inspector is a query/view layer, not a new memory engine. Its explicit `a` action launcher closes
503
+ the overlay before opening native action/approval dialogs. Consolidation calls the existing bounded
504
+ explicit optimizer for the chosen nonshared scope; the launcher does not create a second merge path.
505
+ Knowledge review is a separate proposal workflow described below. Browsing alone remains read-only. Durable browsing reuses strict optimizer
506
+ inspection (including safe/owned admission and pagination); opening it never repairs, migrates, saves,
507
+ schedules, or starts a model call. Session browsing reuses native note replay. Home suppresses project
508
+ scopes. Searches are literal browsing filters, not a replacement for the runtime retrieval ranker.
509
+
510
+ Source metadata (`source`, `derivedFrom`, `supersedes`) remains literal, never an instruction to open
511
+ paths, URLs or private worker archives. Successful explicit `memory remember` results carry a versioned
512
+ native `recording` descriptor with the accepting persona, repository identity and target. A recording
513
+ link requires an exact matching successful tool call/result, current fact content and scope identity
514
+ within the bounded active branch. Old receipts without that attribution cannot establish such a link.
515
+ Session-note links refer to validated native save events. These are recording provenance, not evidence
516
+ that the assertion is true, nor automatic citations of a preceding user message. No store schema,
517
+ retention policy, cross-session access grant or independent transcript archive is introduced.
518
+
519
+ The timeline is an on-demand view of at most 2,000 newest native active-branch entries, with 40 results
520
+ per page and explicit older-entry omissions. It includes user/assistant text and validated session-note
521
+ save/forget events, never reasoning, image bytes, arbitrary custom reports or tool-result bodies.
522
+ Message details are bounded to 32,000 characters with clipping disclosed. Search counts describe only
523
+ that bounded window, not the user's complete conversation history. Tombstones remain historical events.
524
+
525
+ Context inspection holds only the last block prepared by Mind in memory, including session notes,
526
+ capture hints and omission notices. It never reconstructs a supposedly historical selection from today's
527
+ stores, and never claims to observe the provider payload. The existing UTF-8-bytes/3 planning estimator
528
+ and injection policy remain unchanged. A new process has no prior prepared-context snapshot.
529
+
530
+ Native session/branch changes, owner revocation and persona/project changes clear that snapshot and
531
+ abort the open inspector. Every asynchronous page read checks the accepting owner before and after IO;
532
+ revoked results cannot repaint a different owner. UI content is sanitized, width-bounded and navigable
533
+ without executing links or sending model messages. The user can explicitly refresh the view.
534
+
535
+ ## Evidence-grounded knowledge review
536
+
537
+ `/mind review [project|project-long|persona]` and F10's action menu run an explicit knowledge review.
538
+ The default is durable project memory (persona at home). F10 can review a selected fact or a bounded
539
+ scope window. Session/shared are not model-review write targets. The current Persona companion protocol
540
+ admits only the exact active session model/thinking level; Mind does not infer a better model from names,
541
+ change providers, or silently choose a fallback. The real visible `mind` worker still has no tools.
542
+
543
+ The parent inspects safe, owned facts and admits at most six complete records within 12,000 JSON
544
+ characters. The user explicitly selects up to six repository-relative text files. Trusted-workspace,
545
+ containment, symlink, regular-file, size, secret and content checks gate reads; no recursive search,
546
+ source-string path resolution, network access or private worker archive is used. Native user-role text
547
+ is sampled only from a bounded active-branch window. A stored user role is not authenticated human
548
+ intent: quotations, hypotheticals and programmatic messages must be critically assessed. Evidence
549
+ snapshots carry IDs, labels, excerpts, hashes and coverage; omissions cannot establish absence.
550
+
551
+ The task requires one classified finding per supplied fact: supported, proposed correction, conflict,
552
+ insufficient evidence, or proposed retirement. The parent rejects unknown records/citations, duplicate
553
+ findings, malformed fields and unsafe replacement text. Corrective operations preserve kind and scope;
554
+ source lineage and bounded evidence references survive consolidation. These checks establish attribution
555
+ and structural validity, not factual truth. Local repository evidence must not turn a repository-specific
556
+ rule into a universal persona preference; age and latest mention alone are not obsolescence evidence.
557
+
558
+ There is NO automatic application. A complete native proposal report shows reasons, cited evidence,
559
+ coverage and before/after corrections. `/mind review show` reopens it; `/mind review apply` displays it
560
+ and asks for explicit approval. The staged plan lives in a dedicated optimizer instance, not the generic
561
+ memory-tool plan cache, so `/mind optimize apply` cannot bypass evidence validation. Approval reacquires
562
+ maintenance admission, checks evidence freshness and applies through the same CAS/history/undo boundary.
563
+ A synchronous parent evidence guard runs again inside the guarded store callback. This verifies source
564
+ state at the check, not a transaction locking arbitrary repository files against external writers.
565
+
566
+ Retirement is deliberately recommendation-only: the reviewer cannot delete a standalone memory.
567
+ A deliberate scoped `memory forget` remains available for a separately judged retirement, with its
568
+ existing semantics (not consolidation undo). No delete-shaped optimizer plan, new durable schema or
569
+ unbounded history is introduced. `/mind review discard` cancels/discards pending work; an applied change
570
+ requires the ordinary history/undo workflow.
571
+
572
+ A parent review reservation prevents automatic and explicit consolidation from overlapping collection
573
+ or worker execution. Only actual review launches reset automatic usage/cooldown accounting and persist
574
+ explicit attempt markers; interruptions never create an automatic retry entitlement. Staging releases
575
+ the worker reservation rather than holding it while waiting for a human. Apply must acquire a new one;
576
+ concurrent writes or expired plans are refused. New input, agent/model/branch changes, owner revocation
577
+ and shutdown cancel workers/dialogs and invalidate pending review plans. Shutdown joins admitted apply
578
+ work through approval, guarded persistence, receipt finalization and lease cleanup; it bounds only the
579
+ wait for a Persona worker's completion (5 s), and a wait that reaches the bound is treated as an
580
+ interruption. Revocation blocks new
581
+ admission and guarded writes, but does not roll back an already committed replacement or relabel it as
582
+ cancelled; its finalization is still awaited and stale completion UI is suppressed. Completion uses display-only
583
+ native entries/toasts and never triggers a supervisor turn.
584
+
585
+ ## Verification boundaries
586
+
587
+ The source-checkout `eval:memory` command reports individual paired sentinel ranks and actual bounded
588
+ injection outcomes, retaining historical queries and corruption/removed-fact negative controls.
589
+ Token diagnostics compare the unchanged UTF-8-bytes/3 estimate to pinned published reference vectors,
590
+ with exact input/token-ID hashes and source provenance. All inputs use the same calculation: no
591
+ language detector, language-specific factor, local tokenizer execution or runtime network request.
592
+ The reference encoding is not the current model's billing counter, and eight curated vectors do not
593
+ establish broad language coverage or justify automatic budget tuning. The runtime budget is unchanged.
594
+
595
+ Tests isolate PI_PERSONA_* and use a throwaway profile, the actual Pi 1.7.0 SDK/tool pipeline and
596
+ offline providers, and join session_shutdown before SDK disposal. Native session tests cover persisted
597
+ reopen, branch/fork, in-memory behavior and owner revocation. Store tests cover lost writes, stale plans,
598
+ invalid inputs and concurrent apply. Installed-host/package qualification complements source tests.
599
+
600
+ The [post-release source audit](https://github.com/AeonDave/pi-persona-mind/blob/main/docs/reviews/2026-11-12-post-release-audit.md)
601
+ records the qualified snapshots, large-store checks, concurrent-writer stress tests and real-provider
602
+ smokes, with their evidence and platform limits.
603
+
604
+ Passing these checks proves tested behavior, not perfect memory, semantic compression quality, external
605
+ provider authentication or every operating system. CI provides separate Windows/Linux/macOS evidence.