@aeondave/pi-persona-mind 0.8.5 → 0.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -44,7 +44,7 @@ coupled through a versioned local companion handshake to
44
44
  not a boolean. Existing persona facts are not automatically reassigned. STM/backlog auto-delete after ~48h. Explicit session notes live
45
45
  in Pi's native active branch, survive compaction/resume, and stay absent from delegated workers.
46
46
  A non-persistent host session reports in-memory storage; forget is a branch-local tombstone.
47
- - `/mind optimize [project|project-long|persona]` starts one bounded real Persona-hosted LLM review NOW, bypassing automatic dirty/token/cooldown and auto-off gates but not owner, busy, validation or CAS safeguards. It uses the existing worker/prompt/strict JSON/provenance/preview/apply/receipt pipeline, exact current model only, no fallback/tools, and reports bounded coverage/no-op honestly. Shared is refused with a pointer to `/mind optimize inspect shared`; it is excluded from all LLM automatic and explicit writes. `/mind optimize inspect [target]` stays read-only. Do not publish a separate persistent activity row for full optimization; let Persona's normal worker row terminate. Interrupted/stale explicit runs never apply, report across owner change, or arm an automatic retry.
47
+ - Bare `/mind optimize` (also `/mind optimize all`) reviews one bounded window for each currently allowed nonshared target, sequentially, at most three workers; home allows persona only. Named `/mind optimize project|project-long|persona` stays single-target. All explicit work bypasses automatic dirty/token/cooldown and auto-off gates but not owner, busy, validation or CAS safeguards; retain the real Persona worker, strict JSON/provenance/preview/apply/receipt path, exact session model, no fallback/tools, per-tier outcomes, and honest bounded no-op/skip diagnostics. A skipped page is not proof the whole target is empty. Stop a batch on cancellation, owner change or failed/refused/uncertain work. Shared is refused with a pointer to `/mind optimize inspect shared`; it is excluded from all LLM automatic and explicit writes. Inspect/history defaults stay unchanged. Do not publish a separate persistent activity row for full optimization; let Persona's normal worker row terminate. Interrupted/stale explicit runs never apply, report across owner change, or arm an automatic retry.
48
48
  - Optimization inspect/stage exact replacements/apply a short-lived plan ID remains available through explicit inspect/show/apply commands and the memory tool. Similarity
49
49
  is advisory. Compare the original raw store fingerprint under its lock; reject stale/expired
50
50
  plans, invalid stores, ownership mixing, provenance overflow and extended STM expiry.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.8.7](https://github.com/AeonDave/pi-persona-mind/releases/tag/v0.8.7) - 2026-10-27
4
+
5
+ - Interrupted explicit optimization batches identify the tiers not yet reviewed. Worker failures
6
+ and invalid proposals retain the worker's model/effort and terminal-report reference without
7
+ echoing malformed model output. Invalid proposals never reach application.
8
+ - Setup failures report that no tier was reviewed; cleanup failures cannot overwrite completed
9
+ results or retain the active-work slot. Migration-warning tests wait for background completion,
10
+ and the live smoke checks proposal order, confirmed application counts and durable undo receipts;
11
+ refused or uncertain writes cannot pass as successful application.
12
+
13
+ ## [0.8.6](https://github.com/AeonDave/pi-persona-mind/releases/tag/v0.8.6) - 2026-10-26
14
+
15
+ - Allow bare `/mind optimize` and `/mind optimize all` to review one bounded window per currently
16
+ allowed nonshared tier sequentially; home sessions allow persona only. Named targets remain
17
+ single-target, and shared remains excluded from LLM review.
18
+ - Report target-local skip reasons and visible batch outcomes. Skips and reviewed no-ops can continue;
19
+ cancellation, owner changes, and failed, refused, or uncertain work stop later tiers. Prevent
20
+ overlapping batch work; add regression coverage for these behaviors.
21
+
3
22
  ## [0.8.5](https://github.com/AeonDave/pi-persona-mind/releases/tag/v0.8.5) - 2026-10-26
4
23
 
5
24
  - Add `/mind optimize [project|project-long|persona]` for an immediate, bounded review by a visible Persona-hosted worker using the current session model. Changes pass Mind's validation, provenance and compare-and-swap checks; successful writes retain receipts and support guarded undo.
package/README.md CHANGED
@@ -1,241 +1,89 @@
1
1
  <h1 align="center">pi-persona-mind</h1>
2
2
 
3
3
  <p align="center">
4
- <img src="https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.8.5/assets/banner.png" alt="pi-persona-mind — durable memory for Pi">
4
+ <img src="https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.8.7/assets/banner.png" alt="pi-persona-mind — durable memory for Pi">
5
5
  </p>
6
6
 
7
7
  [![CI](https://github.com/AeonDave/pi-persona-mind/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/AeonDave/pi-persona-mind/actions/workflows/test.yml) [![npm version](https://img.shields.io/npm/v/@aeondave/pi-persona-mind?logo=npm)](https://www.npmjs.com/package/@aeondave/pi-persona-mind) [![License](https://img.shields.io/github/license/AeonDave/pi-persona-mind)](LICENSE)
8
8
 
9
- Local memory for [Pi](https://github.com/earendil-works/pi): durable facts, session notes and
10
- unfinished work. Bounded excerpts enter each turn; the agent can retrieve full entries when needed.
9
+ Local memory for [Pi](https://github.com/earendil-works/pi): durable persona and project facts,
10
+ short-term context, session notes and deferred work. Requires a loaded compatible
11
+ [pi-persona](https://github.com/AeonDave/pi-persona); a settings file or installed package alone
12
+ is not sufficient. Saved claims are not automatically verified facts.
11
13
 
12
- Requires a compatible loaded [pi-persona](https://github.com/AeonDave/pi-persona). The current
13
- release pair is Mind 0.8.5 with Persona 1.17.5 or later.
14
- Stores use local files and Pi's session history, without embeddings, a database or a separate service.
15
- Automatic consolidation uses a visible Mind worker on your current session model. Memory injection and
16
- worker review consume normal model tokens. A saved claim is not automatically a verified fact.
14
+ ## Requirements
17
15
 
18
- ## Install
16
+ - Latest stable Pi (currently 1.4.0)
17
+ - Node.js 22.19.0 or newer
18
+ - pi-persona 1.17.5 or newer, loaded in the same Pi instance
19
19
 
20
- Requires the **latest stable Pi (currently 1.4.0)** and **Node.js 22.19.0+**. Historical Pi releases
21
- are not maintained. Windows, Linux and macOS are supported.
20
+ ## Install or update
22
21
 
23
22
  ```bash
24
23
  pi install npm:@aeondave/pi-persona
25
24
  pi install npm:@aeondave/pi-persona-mind
26
25
  ```
27
26
 
28
- Keep both extensions on a compatible release pair. Restart Pi or run `/reload` after installing or
29
- updating them. Mind stays inactive when the compatible Persona companion is missing or incompatible,
30
- with no memory capture, writes, injection or reminders.
31
-
32
- | Install option | Command |
33
- |---|---|
34
- | This project only | `pi install -l npm:@aeondave/pi-persona-mind` |
35
- | Pin Mind 0.8.5 | `pi install npm:@aeondave/pi-persona-mind@0.8.5` |
36
- | Update the unpinned pair | `pi update npm:@aeondave/pi-persona`<br>`pi update npm:@aeondave/pi-persona-mind` |
37
-
38
- When switching either extension from a Git install to npm, remove its exact Git source first (use
39
- your pinned source if applicable):
27
+ For existing installations, update both extensions:
40
28
 
41
29
  ```bash
42
- pi remove git:github.com/AeonDave/pi-persona
43
- pi remove git:github.com/AeonDave/pi-persona-mind
30
+ pi update npm:@aeondave/pi-persona
31
+ pi update npm:@aeondave/pi-persona-mind
44
32
  ```
45
33
 
46
- Keep only one source configured for each extension to avoid loading it twice.
34
+ Restart Pi or run `/reload`. Keep only one source (npm or Git) for each extension; remove the
35
+ existing source before switching to avoid loading duplicates. If Persona is absent or incompatible,
36
+ Mind remains inactive.
47
37
 
48
- ## Choose the right memory
38
+ ## Memory tiers
49
39
 
50
- | Kind | Scope | Lifetime |
40
+ | Tier | Contains | Lifetime |
51
41
  |---|---|---|
52
- | Long-term facts | Active persona, plus an explicit shared tier | Until explicitly changed or forgotten |
53
- | Durable project facts | Current repository, with author persona recorded | Until explicitly changed or forgotten |
54
- | Short-term facts | Current project, with author persona recorded | 48 hours by default |
55
- | Session notes | Active Pi session branch | Follows that session's history |
56
- | Backlog | Current project's deferred work | 48 hours by default; later reminders extend it |
57
-
58
- Session notes survive compaction and resume of a persisted session. A new session starts without
59
- them; a fork inherits its selected history and keeps each note's original session ID. With
60
- `--no-session` or an in-memory SDK session, notes last only as long as that session. Forgetting a
61
- note hides it on the current branch; it does not erase old transcript bytes.
62
-
63
- Promote project knowledge that must outlive its expiry: promotion defaults to durable project memory,
64
- keeping repository decisions out of other projects. Explicit `scope: persona|shared` broadens the
65
- destination. Existing persona facts are not automatically moved or guessed to belong to a project.
66
- Mind never imports private worker archives:
67
- the supervisor reads a result through Intercom, checks it, then saves the useful fact and optional
68
- source reference. A result reference is provenance, not permission to read another session.
42
+ | `project` | Working facts for this repository | 48 hours by default |
43
+ | `project-long` | Durable facts for this repository | Until changed or forgotten |
44
+ | `persona` | Durable facts for the active persona across projects | Until changed or forgotten |
45
+ | `shared` | Explicitly shared durable facts | Until changed or forgotten |
46
+ | `session` | Notes in the active Pi history branch | Follows that session's history |
47
+
48
+ Backlog items are project-scoped and expire after 48 hours by default. Promotion defaults to
49
+ durable project memory; choose `persona` or `shared` explicitly when broader scope is intended. Session notes
50
+ are not available to delegated workers. Project injection and reminders are suppressed from home.
69
51
 
70
52
  ## Commands
71
53
 
72
- `/mind` is an alias of `/persona-mind`; both execute the same handler.
54
+ `/mind` and `/persona-mind` are aliases.
73
55
 
74
- | Command | Effect |
56
+ | Command | Purpose |
75
57
  |---|---|
76
- | `/persona-mind` | Project/persona memory snapshot |
77
- | `/persona-mind help` | Command reference |
78
- | `/persona-mind doctor` | Scope, capture policy, paths and recovery warnings |
79
- | `/persona-mind session` | Bounded list of active-branch session notes |
80
- | `/persona-mind reset` | Clear this project's short-term facts and backlog |
81
- | `/persona-mind reset workspace` | Same explicit workspace reset |
82
- | `/persona-mind migrate-persona` | Recover an ambiguous historical persona-data alias |
83
- | `/persona-mind optimize [project\|project-long\|persona]` | Request one visible Persona-hosted LLM review; defaults to `project` |
84
- | `/persona-mind optimize inspect [project\|project-long\|persona\|shared]` | Read-only bounded inspection |
85
- | `/persona-mind optimize show <planId>` | Display an already staged plan |
86
- | `/persona-mind optimize apply <planId>` | Apply that exact plan if still current |
87
- | `/persona-mind optimize history [target]` | Review retained before/after receipts; default `project` |
88
- | `/persona-mind optimize undo <receiptId> [target]` | Restore unchanged affected facts; default `project` |
89
- | `/persona-mind optimize auto [status\|on\|off]` | Inspect or switch automatic review for this session |
90
-
91
- Reset preserves long-term facts and session notes. `reset all` and unexpected extra arguments are
92
- refused. Reports use expandable cards and short status notifications. Tool results have compact
93
- previews with Pi's expand key, usually `ctrl+o`.
94
-
95
- ## Agent tools
96
-
97
- - `memory remember`: `term: long|short|session`, `kind`, `text`. Long/short facts also support tags,
98
- source, lineage and supersession. For long facts choose `scope: project|persona|shared`; default
99
- is persona. The old `shared` boolean is removed: use `scope: shared`.
100
- - `memory recall`: lexical/path/tag discovery with `query`, `max`, and
101
- `scope: long|short|both|project|persona|shared|session`. Project includes its durable and working
102
- facts; long includes all durable tiers; both includes all active archives. Session is separate.
103
- - `memory read`: full text and provenance by ID, including `session:<UUID>` notes.
104
- - `memory forget`: remove a fact by ID, optionally restricted by scope, or tombstone a session note.
105
- - `memory promote`: make an owned short-term fact durable in this project, unless another scope is explicit.
106
- - `memory optimize`: inspect, stage, apply, history and undo; undo requires `receiptId` and explicit `target`.
107
- - `backlog add|list|take|done|drop`: defer, inspect, claim or close work; reminders are optional.
108
-
109
- Prefer declarative facts such as “The project uses Node 22.” An `objective` is prioritized in
110
- durable injection; a session objective stays in its session.
111
-
112
- Injection ranks current-task words, explicit tags and repository paths, with a small priority core
113
- for objectives/invariants. Persona/shared, project, working context, backlog and session notes share
114
- a **2,400-token planning estimate** (UTF-8 bytes / 3), including wrappers and omission notices.
115
- Session notes use up to 600 of that estimate. This is not a provider tokenizer or a billing guarantee.
116
- Whole excerpts are admitted under the budget, omitted facts are counted, and full reads remain available.
117
- The retrieval is deterministic; it does not infer arbitrary synonyms or establish factual truth.
118
-
119
- ## Review and consolidate
120
-
121
- `/mind optimize [project|project-long|persona]` requests one bounded review in the real visible Persona worker; the command returns before inspection and worker admission. It bypasses automatic preference/token/cooldown gates, but refuses busy sessions, overlap and stale owners. It uses the session model and the validated preview/CAS/apply/undo pipeline. Use `/mind optimize inspect [target]` for explicitly read-only inspection. `shared` is excluded from LLM optimization and must be inspected and handled through a manually reviewed workflow.
122
-
123
- 1. `memory {action:"optimize", mode:"inspect", target:"project"}` returns IDs and a fingerprint.
124
- 2. Read full facts, then stage explicit replacements with that fingerprint and
125
- `operations: [{sourceIds, kind, text, tags?, source?}]`.
126
- 3. Review the before/after plan and apply its `planId` through the tool or slash command.
127
-
128
- One source rewrites a fact; several sources merge them. Each transaction affects one tier.
129
- `project` changes only the active persona's short-term rows; `project-long` changes that persona's
130
- durable repository facts; `persona` targets that persona's
131
- durable store across projects; `shared` targets shared durable facts. Inspect further pages through
132
- `offset`/`nextOffset`; restart if the fingerprint changes. Similarity compares the current page,
133
- so absence from its candidate list does not prove the store is duplicate-free.
134
-
135
- Plans last ten minutes, at most four per active owner. Session/persona/workspace changes invalidate
136
- them. Concurrent writes refuse application. Consolidation preserves origins and lineage, never
137
- extends short-term expiry, and never trims unrelated records to fit storage limits. Lineage IDs
138
- alone are not a full archive of removed text. Each applied consolidation now has a durable before/after
139
- receipt written before replacement. History retains at most 32 receipts / 2 MiB per target, plus the
140
- store's recovery backup. Undo preserves unrelated later writes and refuses altered replacements,
141
- collisions, foreign ownership or expired source facts. A `prepared` receipt means an interrupted
142
- intent whose commit may or may not have happened; it is kept rather than guessing. Ambiguous IO
143
- failures can therefore require manual recovery if unresolved receipts fill the history budget.
144
-
145
- Exact deduplication and expiry cleanup already run automatically. Lexical similarity only suggests
146
- comparisons; it cannot distinguish agreement from contradiction. Age never deletes a durable fact.
147
- See [research and decisions](docs/MEMORY-RESEARCH.md).
148
-
149
- Local inspect/stage/apply activity uses Mind activity rows. Full `/mind optimize` runs appear as ordinary Persona worker rows; the host removes those rows on terminal completion. The full review does not create a separate sticky activity row.
150
-
151
- Automatic review is on by default. Successful saves/promotions mark project or persona memories
152
- for review; shared memories are excluded. The first eligible burst can run after the main agent
153
- settles. Every later attempt requires both new pending memories and **1,000,000 main-session input
154
- tokens since the preceding attempt**. Output, cache and worker tokens do not count. Token usage
155
- alone never schedules a review, and rapid additions stay queued together instead of launching a
156
- worker for every save. This is a cost-control policy, not a research-derived optimum.
157
- Requests coalesce for two seconds after the main agent settles, with no queued work, and actual
158
- attempts have a five-minute cooldown. Only one review can run at a time; unchanged completed reviews
159
- are skipped. New input cancels it; that interrupted attempt may retry after a later settled turn and
160
- the cooldown without waiting for another million tokens. `/mind optimize auto off` cancels and clears
161
- pending review; saves while off do not queue automatic work. Turning it on waits for the next save.
162
- `on` and `off` apply immediately to this session. Set `PI_PERSONA_MIND_OPTIMIZE=off` for the initial
163
- session default, and use `/mind doctor` to inspect the current state.
164
-
165
- This is a real asynchronous Mind subagent with its own Persona view. It uses exactly the session's
166
- model, without a substitute or fallback, and has no arbitrary tools. It receives at most 12 full memory
167
- records within 24,000 JSON characters. Repeated admitted reviews rotate within inspection pages and
168
- through older pages, reserving room for the newest eligible fact. Rotation resets with its owner;
169
- it does not launch an unbounded cleanup loop or claim the whole store has been reviewed. It has a
170
- three-minute deadline and proposes at most four strict
171
- JSON replacements. The parent validates provenance, owner, freshness and the store fingerprint before
172
- applying anything. A durable operator card records the before/after proposal before application;
173
- rejected or stale proposals do not alter their target store. Automatic review does not authorize age-based
174
- deletion, shared-memory editing or inference that an old fact is false.
175
-
176
- ## Capture, reminders and collaboration
177
-
178
- Explicit direct-user requests such as “remember that I prefer small changes” are saved before
179
- the model starts, with a visible receipt. Casual cues suggest capture instead.
180
-
181
- | Setting | Effect |
182
- |---|---|
183
- | `PI_PERSONA_MIND_CAPTURE=auto` | Capture explicit direct-user cues; default |
184
- | `PI_PERSONA_MIND_CAPTURE=prompt` | Suggest a tool call without automatic writes |
185
- | `PI_PERSONA_MIND_CAPTURE=off` | Disable cue detection and capture |
186
- | `PI_PERSONA_MIND_NUDGE=off` | Disable suggestions, not explicit automatic capture |
187
-
188
- The same preferences appear in pi-persona's settings panel. Environment overrides win; Mind refreshes
189
- its capture/nudge preferences on session start. The loaded Persona runtime supplies the actual active
190
- persona, including with selection persistence disabled. Changing council models does not switch memory
191
- scope. Mind does not infer the active persona from old files or saved selection.
192
-
193
- Quoted text, worker reports and Intercom/Exocom messages are not direct user input.
194
- The reserved `pi-persona-deferred-input` replay preserves queued direct-user requests. This is
195
- a convention between trusted extensions, not protection from arbitrary code in the same process.
196
-
197
- Workers marked `PI_PERSONA_LEG` or `PI_PERSONA_CHILD` receive only durable identity/objectives:
198
- their memory scope stays on the persona that launched them, even if the parent switches later.
199
- They receive no project notes, session notes, backlog, memory tools or wakes. Blocked delegate/council/flow
200
- reports can suggest backlog capture; they never write it automatically. Discarded nested reports
201
- do not create invisible reminders.
202
-
203
- A due backlog item creates one display-only card and a short toast, never an agent turn.
204
- Opening Pi from the home directory suppresses project injection and wakes.
205
-
206
- ## Storage and development
207
-
208
- Under `<agentDir>/persona-mind/`: persona/shared facts in `memory/ltm/`, durable repository facts
209
- in `memory/project/`, working facts in `memory/stm/`,
210
- deferred work in `backlog/`. Session notes live in Pi's session file. Writes use exclusive locks,
211
- ownership checks, atomic rename and a last-known-good backup. Imports of old memory data remain
212
- non-destructive. Scanning and escaped injection reduce unsafe-content exposure; they do not
213
- prove saved facts true or arbitrary text harmless.
214
-
215
- An import exceeding the turn's wait budget continues in the background with a temporary information
216
- notice. That alone does not mean data loss; older entries may become available later. Use
217
- `/persona-mind doctor` for its state and actual warnings. After fixing a reported import problem,
218
- `/reload` rechecks the retained original files.
219
-
220
- ```bash
221
- npm ci
222
- npm run typecheck
223
- npm test
224
- npm run eval:memory
225
- npm audit --audit-level=low
226
- ```
227
-
228
- Tests isolate profile/environment and exercise the real Pi 1.4 SDK with an offline provider.
229
- Qualify an installed host with current pi-persona and optionally an extracted Mind tarball:
230
-
231
- ```bash
232
- node --import tsx scripts/qualify-host.mjs <pi-package-root> <pi-persona-extension> [<packed-mind-extension>]
233
- node --import tsx scripts/qualify-package.ts <extracted-package>/src/index.ts <pi-persona-extension>
234
- ```
235
-
236
- The evaluation reports deterministic retrieval on a small synthetic corpus, including a prior
237
- substring baseline and context estimates. It does not measure model merge quality or cloud cost.
238
- These checks verify host integration, not provider authentication or semantic memory quality. Pi supplies
239
- runtime peers. Development security overrides do not patch a separately installed Pi.
240
-
241
- [Design and limits](docs/DESIGN.md) · [Changes](CHANGELOG.md) · [MIT license](LICENSE)
58
+ | `/mind` | Show a memory snapshot |
59
+ | `/mind help` | List commands |
60
+ | `/mind doctor` | Show scope, preferences and recovery warnings |
61
+ | `/mind session` | List active-branch notes |
62
+ | `/mind reset` | Clear this project's working facts and backlog |
63
+ | `/mind optimize` or `/mind optimize all` | Review one bounded window for each currently allowed nonshared tier, sequentially; at most three workers (home allows persona only) |
64
+ | `/mind optimize project\|project-long\|persona` | Review that single tier |
65
+ | `/mind optimize inspect [target]` | Read-only inspection without an LLM call; includes shared |
66
+ | `/mind optimize history [target]` | Review prior changes (default: project) |
67
+ | `/mind optimize undo <receiptId> [target]` | Guardedly undo a prior change |
68
+ | `/mind optimize auto [status\|on\|off]` | Check or change automatic review for this session |
69
+
70
+ Batch review excludes `shared`. Skipped targets report why no worker started; a skipped page does not
71
+ mean the entire tier is empty. Cancellation, owner changes, or failed, refused, or uncertain work
72
+ stop later tiers. Successful changes can be reviewed and undone with the corresponding history and
73
+ undo commands. Optimization uses a visible Persona-hosted worker on the current session model.
74
+
75
+ ## Memory tools
76
+
77
+ The `memory` tool supports `remember`, `recall`, `read`, `forget`, `promote` and `optimize`;
78
+ `backlog` supports adding, listing, taking, completing and dropping deferred work. Use
79
+ `/mind help` for command details and the docs below for scope and optimization behavior.
80
+
81
+ Capture preferences can be set with `PI_PERSONA_MIND_CAPTURE=auto|prompt|off`; capture suggestions
82
+ can be disabled with `PI_PERSONA_MIND_NUDGE=off`. See `/mind doctor` for effective session settings.
83
+
84
+ ## Further reading
85
+
86
+ - [Design and operational limits](docs/DESIGN.md)
87
+ - [Memory research and decisions](docs/MEMORY-RESEARCH.md)
88
+ - [Release history](CHANGELOG.md)
89
+ - [MIT license](LICENSE)
package/docs/DESIGN.md CHANGED
@@ -6,6 +6,8 @@ the user workflow is in [README](../README.md). Evidence behind consolidation de
6
6
 
7
7
  ## Host and module boundaries
8
8
 
9
+ This design contract describes release 0.8.7.
10
+
9
11
  Target the latest stable Pi only, currently 1.4.0, and Node >=22.19. All four development Pi packages
10
12
  are pinned together; runtime host/typebox packages remain optional wildcard peers. No second host
11
13
  runtime or historical hook-shape adapter is bundled. A development-only security override does not
@@ -14,7 +16,7 @@ patch an installed host.
14
16
  Mind requires a loaded compatible pi-persona through its versioned local companion handshake.
15
17
  Missing/incompatible presence leaves tools inactive and suppresses capture, storage/import,
16
18
  injection and reminders. A settings file or installed npm package is not proof of an active
17
- companion. Mind 0.8.5 requires Persona 1.17.5 or later for these paired contracts. Its optional npm
19
+ companion. Mind 0.8.7 requires Persona 1.17.5 or later for these paired contracts. Its optional npm
18
20
  peer declares that requirement without auto-installing or activating another extension.
19
21
 
20
22
  The node-only core has no Pi imports. The factory wires native Pi hooks, tools, scope, scheduling
@@ -109,7 +111,7 @@ An in-memory session is not advertised as restart-durable.
109
111
 
110
112
  ## Explicit consolidation
111
113
 
112
- `/mind optimize [project|project-long|persona]` launches one real visible Persona-hosted LLM review pass using the exact session model and existing worker admission, prompt, strict JSON validation, provenance, preview, CAS apply and durable receipt pipeline. It bypasses automatic dirty/token/cooldown/auto-off gates, but honors the one-worker-per-instance and current owner checks. The command returns after scheduler acceptance, before store inspection or worker admission; the toast says the review was requested and is preparing. Completion is handled in the background and displayed as ordinary Mind result cards, without a separate activity row. A pass is bounded to one selected record window; reports state bounded coverage/no-op and never claim whole-store review. 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]`; default optimize target remains project.
114
+ 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.
113
115
 
114
116
  The manual workflow is inspect → stage exact replacements → apply plan ID. An omitted replacement tag
115
117
  list inherits the normalized union from selected sources; an explicit empty list clears tags. Lexical
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aeondave/pi-persona-mind",
3
- "version": "0.8.5",
3
+ "version": "0.8.7",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Local memory for Pi with pi-persona — durable project and persona facts, session notes, bounded retrieval, and supervised automatic consolidation.",
@@ -57,7 +57,7 @@
57
57
  }
58
58
  },
59
59
  "pi": {
60
- "image": "https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.8.5/assets/banner.png",
60
+ "image": "https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.8.7/assets/banner.png",
61
61
  "extensions": [
62
62
  "./src/index.ts"
63
63
  ]
@@ -15,12 +15,11 @@ export interface AutoOptimizeInput {
15
15
  entries: MemoryEntry[];
16
16
  }
17
17
 
18
- export interface AutoInputPage {
19
- input?: AutoOptimizeInput;
20
- eligibleCount: number;
21
- nextRotation: number;
22
- pageComplete: boolean;
23
- }
18
+ export type AutoInputSkipReason = "invalid-input" | "empty-page" | "no-safe-owned-facts" | "single-short-record" | "input-budget";
19
+
20
+ export type AutoInputPage =
21
+ | { input: AutoOptimizeInput; eligibleCount: number; nextRotation: number; pageComplete: boolean }
22
+ | { input?: never; eligibleCount: number; nextRotation: number; pageComplete: boolean; reason: AutoInputSkipReason };
24
23
 
25
24
  export type AutoProposalResult = { ok: true; operations: OptimizeOperation[] } | { ok: false; reason: string };
26
25
 
@@ -52,11 +51,17 @@ export function selectAutoInput(inspection: OptimizeInspection, persona: string,
52
51
 
53
52
  /** Selects one bounded rotating slice and reports cursor progress even when the page has no work. */
54
53
  export function selectAutoInputPage(inspection: OptimizeInspection, persona: string, rotation = 0, newestInspection?: OptimizeInspection): AutoInputPage {
55
- const empty = (eligibleCount = 0): AutoInputPage => ({ eligibleCount, nextRotation: 0, pageComplete: true });
54
+ const empty = (reason: AutoInputSkipReason, eligibleCount = 0): AutoInputPage => ({ eligibleCount, nextRotation: 0, pageComplete: true, reason });
56
55
  if (!isReviewTarget(inspection?.target) || typeof persona !== "string" || persona.length < 1 || persona.length > 128 ||
57
- typeof inspection.fingerprint !== "string" || inspection.fingerprint.length < 1 || inspection.fingerprint.length > 256 || !Array.isArray(inspection.entries)) return empty();
56
+ typeof inspection.fingerprint !== "string" || inspection.fingerprint.length < 1 || inspection.fingerprint.length > 256 || !Array.isArray(inspection.entries) ||
57
+ !Number.isSafeInteger(inspection.offset) || inspection.offset < 0 || !Number.isSafeInteger(inspection.total) || inspection.total < 0 ||
58
+ !Number.isSafeInteger(inspection.matched) || inspection.matched < 0) return empty("invalid-input");
58
59
  const eligible = eligibleEntries(inspection, persona);
59
60
  const pageEntries = eligible;
61
+ if (pageEntries.length === 0) {
62
+ const hasExcludedRows = inspection.entries.length > 0 || (inspection.total > 0 && inspection.matched === 0);
63
+ return empty(hasExcludedRows ? "no-safe-owned-facts" : "empty-page");
64
+ }
60
65
  let newest: MemoryEntry | undefined;
61
66
  if (inspection.offset === 0) newest = pageEntries[0];
62
67
  else if (newestInspection && newestInspection.target === inspection.target && newestInspection.offset === 0 && newestInspection.fingerprint === inspection.fingerprint) {
@@ -86,8 +91,10 @@ export function selectAutoInputPage(inspection: OptimizeInspection, persona: str
86
91
  const start = Number.isSafeInteger(rotation) && rotation > 0 ? Math.min(rotation, ordered.length) : 0;
87
92
  const capacity = Math.max(0, AUTO_OPTIMIZE_MAX_ENTRIES - (newest ? 1 : 0));
88
93
  const window = ordered.slice(start, start + capacity);
94
+ if (window.length === 0 && !newest) return empty("empty-page", pageEntries.length);
89
95
  const selected: MemoryEntry[] = [];
90
96
  const selectedIds = new Set<string>();
97
+ let budgetBlocked = false;
91
98
  function tryAdd(entry: MemoryEntry): boolean {
92
99
  if (selectedIds.has(entry.id) || selected.length >= AUTO_OPTIMIZE_MAX_ENTRIES) return false;
93
100
  if (JSON.stringify([...selected, entry]).length > AUTO_OPTIMIZE_MAX_INPUT_CHARS) return false;
@@ -95,19 +102,20 @@ export function selectAutoInputPage(inspection: OptimizeInspection, persona: str
95
102
  selected.push(entry);
96
103
  return true;
97
104
  }
98
- if (newest) tryAdd(newest);
105
+ if (newest && !tryAdd(newest)) budgetBlocked = true;
99
106
  let suppliedFromWindow = 0;
100
107
  for (const entry of window) {
101
108
  // Keep the rotation contiguous: when the next row will not fit alongside the pinned newest
102
109
  // row, leave that row at the cursor for the next admitted pass. Skipping it here would make
103
110
  // the cursor claim coverage for data the worker never received.
104
- if (!tryAdd(entry)) break;
111
+ if (!tryAdd(entry)) { budgetBlocked = true; break; }
105
112
  suppliedFromWindow++;
106
113
  }
107
114
  const admittedPosition = start + suppliedFromWindow;
108
115
  const pageComplete = admittedPosition >= ordered.length;
109
116
  if (selected.length === 0 || (selected.length === 1 && selected[0]!.text.length < MIN_SINGLE_ENTRY_CHARS)) {
110
- return { eligibleCount: pageEntries.length, nextRotation: pageComplete ? 0 : admittedPosition, pageComplete };
117
+ const reason: AutoInputSkipReason = budgetBlocked ? "input-budget" : "single-short-record";
118
+ return { eligibleCount: pageEntries.length, nextRotation: pageComplete ? 0 : admittedPosition, pageComplete, reason };
111
119
  }
112
120
  const digest = semanticDigest(inspection.target, selected);
113
121
  return { input: { target: inspection.target, fingerprint: inspection.fingerprint, digest, entries: selected }, eligibleCount: pageEntries.length, nextRotation: pageComplete ? 0 : admittedPosition, pageComplete };
@@ -40,7 +40,8 @@ export interface AutoOptimizeSession {
40
40
  memoryAdded(ctx: ExtensionContext, target: AutoOptimizeTarget): void;
41
41
  status(): string;
42
42
  setEnabled(enabled: boolean): void;
43
- startExplicit(target: AutoOptimizeTarget): boolean;
43
+ targets(): readonly AutoOptimizeTarget[];
44
+ startExplicit(target?: AutoOptimizeTarget): boolean;
44
45
  }
45
46
 
46
47
  export function installAutoOptimize(pi: ExtensionAPI, deps: Dependencies): AutoOptimizeSession {
@@ -115,6 +116,7 @@ export function installAutoOptimize(pi: ExtensionAPI, deps: Dependencies): AutoO
115
116
  return { activate, revoke, memoryAdded,
116
117
  status: () => boundContext ? scheduler.status() : "inactive · automatic work requires an interactive Persona session",
117
118
  setEnabled: (enabled) => scheduler.setEnabled(enabled),
119
+ targets: () => scheduler.targets(),
118
120
  startExplicit: (target) => scheduler.startExplicit(target),
119
121
  };
120
122
  }
@@ -1,5 +1,5 @@
1
1
  /** Event-driven maintenance: one visible Persona worker, bounded evidence, existing CAS writes. */
2
- import { buildAutoPrompt, parseAutoProposal, selectAutoInputPage, type AutoOptimizeTarget } from "../core/auto-optimize.ts";
2
+ import { buildAutoPrompt, parseAutoProposal, selectAutoInputPage, type AutoInputPage, type AutoInputSkipReason, type AutoOptimizeTarget } from "../core/auto-optimize.ts";
3
3
  import type { MemoryOptimizer } from "../core/optimize-service.ts";
4
4
  import type { MindWorkerAdmission, MindWorkerResult } from "./mind-worker.ts";
5
5
  import type { OptimizeFailure, OptimizeInspection, OptimizePlan } from "../core/optimize.ts";
@@ -114,16 +114,22 @@ export class AutoOptimizeScheduler {
114
114
  this.work = this.run().catch(() => { this.last = "inspection failed; no automatic retry"; });
115
115
  }, Math.max(AUTO_IDLE_MS, this.lastAttempt + AUTO_COOLDOWN_MS - this.now()));
116
116
  }
117
- /** Start one user-requested bounded pass without automatic gates or preference checks. */
118
- startExplicit(target: Target): boolean {
117
+ /** Current writable tiers, in the order a bare explicit request will review. */
118
+ targets(): readonly Target[] { return this.owner ? [...new Set(this.owner.allowedTargets)].slice(0, 3) : []; }
119
+ /** Start one named pass, or one bounded sequential pass over every allowed nonshared tier. */
120
+ startExplicit(target?: Target): boolean {
119
121
  const owner = this.owner;
120
- if (!owner || !this.safeCurrent(owner) || !this.safeIdle(owner) || !this.allows(owner, target) || this.running) return false;
122
+ if (!owner || !this.safeCurrent(owner) || !this.safeIdle(owner) || this.running || (target !== undefined && !this.allows(owner, target))) return false;
123
+ const targets = target === undefined ? [...this.targets()] : [target];
124
+ if (targets.length === 0) return false;
121
125
  this.timer?.(); this.timer = undefined; this.timerGeneration++;
122
126
  const generation = this.generation;
123
- this.work = this.run(target, true).catch(() => {
124
- if (generation !== this.generation || !this.safeCurrent(owner)) return;
127
+ const qualifyTargets = target === undefined;
128
+ this.work = this.run(targets, true, qualifyTargets).catch(() => {
129
+ if (generation !== this.generation || !this.safeCurrent(owner) || !this.safeIdle(owner)) return;
125
130
  this.last = "explicit review failed; inspect current memory before retrying because apply may have completed";
126
- try { owner.report("Mind optimization result", `Bounded review failed unexpectedly; ${this.last}.`); } catch { /* owner reporting is best-effort */ }
131
+ const label = targets.join(", ");
132
+ try { owner.report(qualifyTargets ? `Mind optimization result — ${targets[0]}` : "Mind optimization result", qualifyTargets ? `Targets ${label} — failed unexpectedly; inspect current memory before retrying because apply may have completed.\n${this.last}.` : `Bounded review failed unexpectedly; ${this.last}.`); } catch { /* owner reporting is best-effort */ }
127
133
  }).finally(() => {
128
134
  if (generation === this.generation && this.safeCurrent(owner) && this.safeIdle(owner) && this.pending.size) this.settled();
129
135
  });
@@ -139,22 +145,45 @@ export class AutoOptimizeScheduler {
139
145
  this.seen.add(digest); while (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!);
140
146
  }
141
147
  }
142
- private async run(explicitTarget?: Target, explicit = false): Promise<void> {
148
+ private async run(explicitTargets?: readonly Target[], explicit = false, qualifyTargets = false): Promise<void> {
143
149
  const owner = this.owner;
144
150
  if (!owner || (!explicit && !this.enabled) || !this.safeCurrent(owner) || !this.safeIdle(owner) || this.running) return;
145
151
  const generation = this.generation;
146
152
  const disabledGeneration = this.disabledGeneration;
147
153
  const current = () => generation === this.generation && (explicit || this.enabled) && this.safeIdle(owner) && this.safeCurrent(owner);
148
154
  const mayRetry = () => !explicit && this.enabled && this.disabledGeneration === disabledGeneration && this.safeCurrent(owner);
149
- const optimizer = owner.optimizer();
155
+ const targets = explicit ? explicitTargets ?? [] : [...this.pending];
156
+ let optimizer: Optimizer;
157
+ try { optimizer = owner.optimizer(); } catch (error) {
158
+ if (!explicit) throw error;
159
+ if (!current()) return;
160
+ this.last = "optimizer setup failed; no worker started, no memory changed";
161
+ const body = `${qualifyTargets ? "Batch stopped; not reviewed" : "Target not reviewed"}: ${targets.join(", ")}.\nBounded review could not start: ${this.last}. See /mind doctor.`;
162
+ try { owner.report(qualifyTargets ? `Mind optimization result — ${targets[0]}` : "Mind optimization result", body); } catch { /* owner reporting is best-effort */ }
163
+ return;
164
+ }
150
165
  const running: NonNullable<AutoOptimizeScheduler["running"]> = { optimizer, explicit };
151
166
  let attemptRecorded = false;
152
167
  let unsettledTarget: Target | undefined;
153
168
  let nextCursor: CoverageCursor | undefined;
154
169
  let retryRequiresSettled = false;
170
+ let activeTarget: Target | undefined;
171
+ const report = (target: Target, title: string, body: string, summary?: string, stopped = false): boolean => {
172
+ if (!current()) return false;
173
+ const remaining = stopped && qualifyTargets ? targets.slice(targets.indexOf(target) + 1) : [];
174
+ const stoppedLine = remaining.length ? `Batch stopped; not reviewed: ${remaining.join(", ")}.\n` : "";
175
+ const outcome = `${summary ?? body.split("\n", 1)[0] ?? "review result"}${remaining.length ? ` · not reviewed: ${remaining.join(", ")}` : ""}`;
176
+ const qualifiedBody = qualifyTargets && !body.startsWith("Target:")
177
+ ? `Target: ${target} — ${outcome}\n${stoppedLine}${body}`
178
+ : body;
179
+ owner.report(qualifyTargets ? `${title} — ${target}` : title, qualifiedBody);
180
+ return true;
181
+ };
155
182
  this.running = running;
156
183
  try {
157
- for (const target of explicit ? [explicitTarget!] : [...this.pending]) {
184
+ for (const target of targets) {
185
+ activeTarget = target;
186
+ if (!current()) return;
158
187
  if (!this.allows(owner, target)) { this.pending.delete(target); this.retryTargets.delete(target); continue; }
159
188
  const retry = this.retryTargets.has(target);
160
189
  const tokenReady = this.lastAttempt === -Infinity || this.inputTokens >= AUTO_INPUT_TOKEN_THRESHOLD;
@@ -169,20 +198,20 @@ export class AutoOptimizeScheduler {
169
198
  const latest = await optimizer.inspect(target, { max: 100, offset: 0 });
170
199
  if (latest.ok && latest.target === target && latest.fingerprint === inspection.fingerprint) newestInspection = latest;
171
200
  else {
172
- if (mayRetry()) this.pending.add(target);
173
- this.last = explicit ? "store changed during bounded inspection; the selected window was not reviewed" : "store changed during bounded inspection; waiting for the next settled event";
174
- if (explicit && current()) owner.report("Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`);
175
- return;
201
+ if (mayRetry()) this.pending.add(target);
202
+ this.last = explicit ? "store changed during bounded inspection; the selected window was not reviewed" : "store changed during bounded inspection; waiting for the next settled event";
203
+ if (explicit) report(target, "Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`, "inspection snapshot changed; no worker started", true);
204
+ return;
176
205
  }
177
206
  }
178
- }
179
- catch {
207
+ } catch {
180
208
  if (!current()) {
181
209
  if (mayRetry()) this.pending.add(target);
182
210
  return;
183
211
  }
184
212
  this.last = "store inspection failed; see /mind doctor";
185
- if (explicit) owner.report("Mind optimization result", `Bounded review could not inspect this record window: ${this.last}.`);
213
+ if (explicit) report(target, "Mind optimization result", `Bounded review could not inspect this record window: ${this.last}.`, "inspection failed; no worker started", true);
214
+ if (explicit) return;
186
215
  continue;
187
216
  }
188
217
  if (!current()) {
@@ -191,8 +220,18 @@ export class AutoOptimizeScheduler {
191
220
  if (mayRetry()) this.pending.add(target);
192
221
  return;
193
222
  }
194
- if (!inspection.ok) { this.last = "store inspection refused; see /mind doctor"; if (explicit) owner.report("Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`); continue; }
195
- if (inspection.target !== target) { this.last = "store inspection returned a different tier; no worker started"; if (explicit) owner.report("Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`); continue; }
223
+ if (!inspection.ok) {
224
+ this.last = "store inspection refused; see /mind doctor";
225
+ if (explicit) report(target, "Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`, "inspection refused; no worker started", true);
226
+ if (explicit) return;
227
+ continue;
228
+ }
229
+ if (inspection.target !== target) {
230
+ this.last = "store inspection returned a different tier; no worker started";
231
+ if (explicit) report(target, "Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`, "inspection returned the wrong target; no worker started", true);
232
+ if (explicit) return;
233
+ continue;
234
+ }
196
235
  const page = selectAutoInputPage(inspection, owner.persona, cursor.withinPage, newestInspection);
197
236
  nextCursor = page.pageComplete
198
237
  ? { offset: inspection.nextOffset ?? 0, withinPage: 0 }
@@ -202,7 +241,7 @@ export class AutoOptimizeScheduler {
202
241
  this.cursors.set(target, nextCursor);
203
242
  this.retryTargets.delete(target);
204
243
  this.last = "no eligible records in this bounded page";
205
- if (explicit) owner.report("Mind optimization result", `Bounded coverage: no eligible records in the selected window; ${this.last}.`);
244
+ if (explicit && !report(target, "Mind optimization result", formatAutoInputSkip(target, inspection, page))) return;
206
245
  continue;
207
246
  }
208
247
  if (!explicit && this.seen.has(input.digest)) {
@@ -211,11 +250,12 @@ export class AutoOptimizeScheduler {
211
250
  this.last = "this bounded record set was already reviewed";
212
251
  continue;
213
252
  }
253
+ if (!current()) return;
214
254
  const worker = owner.launch(buildAutoPrompt(input));
215
255
  if (!worker.ok) {
216
256
  if (!explicit) this.pending.add(target);
217
257
  this.last = worker.reason;
218
- if (explicit && current()) owner.report("Mind optimization result", `Bounded review was not admitted: ${worker.reason}. No memory changed.`);
258
+ if (explicit) report(target, "Mind optimization result", `Bounded review was not admitted: ${worker.reason}. No memory changed.`, "worker admission refused; no memory changed", true);
219
259
  return;
220
260
  }
221
261
  const attemptAt = this.now();
@@ -250,19 +290,37 @@ export class AutoOptimizeScheduler {
250
290
  }
251
291
  unsettledTarget = undefined;
252
292
  this.last = explicit ? "explicit review stopped; memory unchanged" : "review interrupted; waiting for the next settled event";
253
- if (explicit && current()) owner.report("Mind optimization result", this.last);
293
+ if (explicit) report(target, "Mind optimization result", this.last, "worker stopped; memory unchanged", true);
254
294
  return;
255
295
  }
256
- if (!result.ok) { settle(); this.last = "worker failed; memory unchanged"; owner.report(explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded review · ${this.last}${result.error ? `: ${result.error}` : ""}`); return; }
257
- const parsed = parseAutoProposal(result.output, input);
258
- if (!parsed.ok) { settle(); this.last = "proposal refused; memory unchanged"; owner.report(explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded review · ${this.last}: ${parsed.reason}`); return; }
259
296
  const provenance = `Worker ${worker.runId} · ${worker.model} · ${worker.thinking}${result.resultRef ? `\nTerminal report: ${result.resultRef}` : ""}`;
260
- if (!parsed.operations.length) { settle(); this.last = "bounded review found no safe consolidation in this record set"; owner.report(explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded coverage: one selected record window; ${this.last}.\n${provenance}`); return; }
297
+ if (!result.ok) {
298
+ settle(); this.last = "worker failed; memory unchanged";
299
+ report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded review · ${this.last}${result.error ? `: ${result.error}` : ""}\n${provenance}`, "worker failed; memory unchanged", explicit);
300
+ return;
301
+ }
302
+ const parsed = parseAutoProposal(result.output, input);
303
+ if (!parsed.ok) {
304
+ settle(); this.last = "proposal refused; memory unchanged";
305
+ report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded review · ${this.last}: ${parsed.reason}\n${provenance}`, "proposal refused; memory unchanged", explicit);
306
+ return;
307
+ }
308
+ if (!parsed.operations.length) {
309
+ settle(); this.last = "bounded review found no safe consolidation in this record set";
310
+ report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded coverage: one selected record window; ${this.last}.\n${provenance}`, "reviewed no-op; no safe consolidation in this window");
311
+ if (!explicit) return;
312
+ continue;
313
+ }
314
+ if (!current()) return;
261
315
  const plan = await optimizer.preview({ target: input.target, fingerprint: input.fingerprint, operations: parsed.operations });
262
316
  if (!current()) return;
263
- if (!plan.ok) { settle(); this.last = "store or proposal changed; nothing applied"; owner.report(explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded coverage: one selected record window; ${this.last}: ${plan.reason}\n${provenance}`); return; }
264
- owner.report(explicit ? "Mind optimization proposal" : "Mind automatic proposal", `${provenance}\n${formatAutoPlan(plan)}\n${explicit ? "Validated apply pending" : "Automatic apply pending"}; it proceeds only while this owner and snapshot remain current.`);
265
- if (!current()) { optimizer.invalidate(); return; }
317
+ if (!plan.ok) {
318
+ settle(); this.last = "store or proposal changed; nothing applied";
319
+ report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded coverage: one selected record window; ${this.last}: ${plan.reason}\n${provenance}`, "proposal refused or stale; nothing applied", explicit);
320
+ return;
321
+ }
322
+ if (!report(target, explicit ? "Mind optimization proposal" : "Mind automatic proposal", `${provenance}\n${formatAutoPlan(plan)}\n${explicit ? "Validated apply pending" : "Automatic apply pending"}; it proceeds only while this owner and snapshot remain current.`, "proposal staged; validated apply pending")) return;
323
+ if (!current()) return;
266
324
  const applied = await optimizer.apply(plan.planId);
267
325
  if (!current()) return;
268
326
  settle();
@@ -271,11 +329,18 @@ export class AutoOptimizeScheduler {
271
329
  ? applied.receiptId ? `\nUndo: /mind optimize undo ${applied.receiptId} ${applied.target}.` : "\nNo durable undo receipt was returned."
272
330
  : "";
273
331
  const warning = applied.ok && applied.warning ? `\nWarning: ${applied.warning}` : "";
274
- owner.report(explicit ? "Mind optimization result" : "Mind automatic result", `Bounded coverage: one selected record window; ${this.last}\n${provenance}${receipt}${warning}`);
275
- return; // One worker per pass; other dirty tiers wait for the input floor and cooldown.
332
+ const resultSummary = applied.ok
333
+ ? `${applied.changed} replacement${applied.changed === 1 ? "" : "s"} applied${applied.warning ? "; receipt finalization warning" : ""}`
334
+ : `not applied: ${applied.reason}`;
335
+ if (!report(target, explicit ? "Mind optimization result" : "Mind automatic result", `Bounded coverage: one selected record window; ${this.last}\n${provenance}${receipt}${warning}`, resultSummary, explicit && (!applied.ok || Boolean(applied.warning)))) return;
336
+ if (!applied.ok || applied.warning || !explicit) return;
276
337
  }
338
+ } catch (error) {
339
+ if (!explicit) throw error;
340
+ this.last = "explicit review failed unexpectedly; inspect current memory before retrying because apply may have completed";
341
+ if (activeTarget && current()) report(activeTarget, "Mind optimization result", `Bounded review failed unexpectedly; ${this.last}.`, "review failed unexpectedly; inspect current memory before retrying", true);
277
342
  } finally {
278
- optimizer.invalidate();
343
+ try { optimizer.invalidate(); } catch { /* Run-local plan cleanup cannot change completed review/apply results. */ }
279
344
  if (this.running === running) this.running = undefined;
280
345
  if (unsettledTarget !== undefined && !current() && mayRetry()) {
281
346
  this.pending.add(unsettledTarget);
@@ -283,12 +348,37 @@ export class AutoOptimizeScheduler {
283
348
  this.last = "review interrupted; waiting for the next settled event";
284
349
  }
285
350
  // One actual attempt may leave other dirty tiers pending; they need the input floor
286
- // and cooldown. Only the same interrupted target bypasses the token floor.
351
+ // and cooldown. Only the same interrupted tier bypasses the token floor.
287
352
  if (!explicit && attemptRecorded && this.pending.size > 0 && current() && !retryRequiresSettled) this.settled();
288
353
  }
289
354
  }
290
355
  }
291
356
 
357
+ export function formatAutoInputSkip(target: Target, inspection: OptimizeInspection, page: Extract<AutoInputPage, { reason: AutoInputSkipReason }>): string {
358
+ const offset = Number.isSafeInteger(inspection.offset) && inspection.offset >= 0 ? inspection.offset : 0;
359
+ const returned = Array.isArray(inspection.entries) ? inspection.entries.length : 0;
360
+ const matched = Number.isSafeInteger(inspection.matched) && inspection.matched >= 0 ? inspection.matched : 0;
361
+ const total = Number.isSafeInteger(inspection.total) && inspection.total >= 0 ? inspection.total : 0;
362
+ const eligible = Number.isSafeInteger(page.eligibleCount) && page.eligibleCount >= 0 ? page.eligibleCount : 0;
363
+ const coverage = page.pageComplete ? "candidate page covered" : `within-page rotation continues at ${page.nextRotation}`;
364
+ const morePages = inspection.nextOffset === undefined ? "" : `; further inspection page starts at ${inspection.nextOffset}`;
365
+ const reasons = {
366
+ "invalid-input": "the bounded input or owner identity was invalid",
367
+ "empty-page": "the selected page is empty or exhausted; this does not establish that the whole target is empty",
368
+ "no-safe-owned-facts": "this page contains no safe, owned eligible facts",
369
+ "single-short-record": "the only admitted safe, owned fact in this selected window is shorter than the 1,200-character single-record minimum",
370
+ "input-budget": "the 24,000-character input budget cannot admit enough full records in this window; records are not split or truncated",
371
+ } satisfies Record<AutoInputSkipReason, string>;
372
+ const headlines: Record<AutoInputSkipReason, string> = {
373
+ "invalid-input": "invalid input",
374
+ "empty-page": "empty/exhausted page",
375
+ "no-safe-owned-facts": "no safe/owned facts",
376
+ "single-short-record": "single fact under 1,200 characters",
377
+ "input-budget": "full-record input budget too small",
378
+ };
379
+ return `Target: ${target} — skipped: ${headlines[page.reason]}; no worker started, no memory changed.\nSelected page offset ${offset}: ${returned} record(s) returned of ${matched} inspection matches; ${eligible} safe/owned eligible record(s); ${total} active record(s) in this target; ${coverage}${morePages}.\nReason: ${reasons[page.reason]}.`;
380
+ }
381
+
292
382
  function workerWasStopped(result: MindWorkerResult): boolean {
293
383
  return result.status === "stopped";
294
384
  }
@@ -21,7 +21,7 @@ export type MindCommand =
21
21
  | { type: "reset" }
22
22
  | { type: "migrate-persona" }
23
23
  | { type: "session" }
24
- | { type: "optimize-run"; target: Exclude<MindOptimizeTarget, "shared"> }
24
+ | { type: "optimize-run"; target?: Exclude<MindOptimizeTarget, "shared"> }
25
25
  | { type: "optimize-shared-refused" }
26
26
  | { type: "optimize-inspect"; target: MindOptimizeTarget }
27
27
  | { type: "optimize-show"; planId: string }
@@ -32,7 +32,7 @@ export type MindCommand =
32
32
  | { type: "invalid"; message: string };
33
33
 
34
34
  const USAGE =
35
- "usage: /persona-mind [help|doctor|session|reset [workspace]|migrate-persona|optimize [project|project-long|persona]|optimize inspect [project|project-long|persona|shared]|optimize show <planId>|optimize apply <planId>|optimize history [target]|optimize undo <receiptId> [target]|optimize auto [status|on|off]]";
35
+ "usage: /persona-mind [help|doctor|session|reset [workspace]|migrate-persona|optimize [all|project|project-long|persona]|optimize inspect [project|project-long|persona|shared]|optimize show <planId>|optimize apply <planId>|optimize history [target]|optimize undo <receiptId> [target]|optimize auto [status|on|off]]";
36
36
 
37
37
  export interface MindCommandDeps {
38
38
  agentDir: string;
@@ -42,7 +42,7 @@ export interface MindCommandDeps {
42
42
  getSessionMemory(): SessionMemory;
43
43
  getOptimizer(ctx: ExtensionContext): MemoryOptimizer;
44
44
  activity?(ctx: ExtensionContext): MindActivityRunner | undefined;
45
- autoOptimize?: { status(): string; setEnabled(enabled: boolean): void; startExplicit?(target: Exclude<MindOptimizeTarget, "shared">): boolean };
45
+ autoOptimize?: { status(): string; setEnabled(enabled: boolean): void; targets?(): readonly Exclude<MindOptimizeTarget, "shared">[]; startExplicit?(target?: Exclude<MindOptimizeTarget, "shared">): boolean };
46
46
  isCurrent(ctx: ExtensionContext): boolean;
47
47
  ensureLegacyMigrated(ctx: ExtensionContext, includeAmbiguousPersonaAlias?: boolean, awaitCompletion?: boolean): Promise<void>;
48
48
  migrationStatus(): string;
@@ -78,7 +78,7 @@ export function registerMindCommands(pi: ExtensionAPI, deps: MindCommandDeps): v
78
78
  "/persona-mind session — list notes on this active session branch",
79
79
  "/persona-mind reset [workspace] — clear this project's short-term memory and backlog",
80
80
  "/persona-mind migrate-persona — explicitly import an ambiguous historical persona alias",
81
- "/persona-mind optimize [project|project-long|persona] — request one bounded visible Persona-hosted LLM review; project is expiring working memory, project-long is durable repository knowledge",
81
+ "/persona-mind optimize [all|project|project-long|persona] — bare/all reviews each allowed tier in one bounded sequential pass; a named tier stays single-target",
82
82
  "/persona-mind optimize inspect [project|project-long|persona|shared] — read-only inspection; shared changes require a manually reviewed workflow.",
83
83
  "/persona-mind optimize show <planId> — inspect exact staged text; /persona-mind optimize apply <planId> commits that plan only",
84
84
  "/persona-mind optimize history [target] — inspect bounded durable before/after receipts; /persona-mind optimize undo <receiptId> [target] restores unchanged affected facts (target defaults to project)",
@@ -101,8 +101,14 @@ export function registerMindCommands(pi: ExtensionAPI, deps: MindCommandDeps): v
101
101
  ctx.ui.notify("Memory session owner changed; optimization was not started.", "warning");
102
102
  return;
103
103
  }
104
- if (!deps.autoOptimize.startExplicit(command.target)) ctx.ui.notify("Mind is busy, already has a review worker active, or its memory owner is unavailable; no review was accepted.", "warning");
105
- else ctx.ui.notify(`Mind ${command.target} review requested; bounded inspection and worker admission are preparing in the background.`, "info");
104
+ const accepted = command.target === undefined ? deps.autoOptimize.startExplicit() : deps.autoOptimize.startExplicit(command.target);
105
+ if (!accepted) ctx.ui.notify("Mind is busy, already has a review worker active, or its memory owner is unavailable; no review was accepted.", "warning");
106
+ else if (command.target !== undefined) ctx.ui.notify(`Mind ${command.target} review requested; bounded inspection and worker admission are preparing in the background.`, "info");
107
+ else {
108
+ const targets = deps.autoOptimize.targets?.() ?? ["project", "project-long", "persona"];
109
+ const scopes = targets.length ? targets.join(", ") : "currently allowed scopes";
110
+ ctx.ui.notify(`Mind review requested for ${scopes} (currently allowed scopes; at most one bounded inspection window per tier, workers sequentially). Inspection and worker admission are preparing in the background.`, "info");
111
+ }
106
112
  return;
107
113
  }
108
114
  if (command.type === "optimize-auto") {
@@ -339,7 +345,7 @@ export function parseMindCommand(args: string): MindCommand {
339
345
  }
340
346
  if (parts[1] === "inspect" && parts.length === 2) return { type: "optimize-inspect", target: "project" };
341
347
  if (parts[1] === "inspect" && parts.length === 3 && isOptimizeTarget(parts[2])) return { type: "optimize-inspect", target: parts[2] };
342
- if (parts.length === 1) return { type: "optimize-run", target: "project" };
348
+ if (parts.length === 1 || parts.length === 2 && parts[1] === "all") return { type: "optimize-run" };
343
349
  if (parts.length === 2 && parts[1] === "shared") return { type: "optimize-shared-refused" };
344
350
  if (parts.length === 2 && (parts[1] === "project" || parts[1] === "project-long" || parts[1] === "persona")) {
345
351
  return { type: "optimize-run", target: parts[1] };