@aeondave/pi-persona-mind 0.8.4 → 0.8.6
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 +2 -1
- package/CHANGELOG.md +15 -0
- package/README.md +61 -217
- package/docs/DESIGN.md +6 -2
- package/package.json +2 -2
- package/src/core/auto-optimize.ts +19 -11
- package/src/extension/auto-optimize-session.ts +4 -0
- package/src/extension/auto-optimize.ts +152 -40
- package/src/extension/mind-command.ts +36 -8
package/AGENTS.md
CHANGED
|
@@ -44,7 +44,8 @@ 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
|
-
-
|
|
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
|
+
- Optimization inspect/stage exact replacements/apply a short-lived plan ID remains available through explicit inspect/show/apply commands and the memory tool. Similarity
|
|
48
49
|
is advisory. Compare the original raw store fingerprint under its lock; reject stale/expired
|
|
49
50
|
plans, invalid stores, ownership mixing, provenance overflow and extended STM expiry.
|
|
50
51
|
Lifecycle changes invalidate plans. Automatic semantic review is user-authorized and on by default
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.8.6](https://github.com/AeonDave/pi-persona-mind/releases/tag/v0.8.6) - 2026-10-26
|
|
4
|
+
|
|
5
|
+
- Allow bare `/mind optimize` and `/mind optimize all` to review one bounded window per currently
|
|
6
|
+
allowed nonshared tier sequentially; home sessions allow persona only. Named targets remain
|
|
7
|
+
single-target, and shared remains excluded from LLM review.
|
|
8
|
+
- Report target-local skip reasons and visible batch outcomes. Skips and reviewed no-ops can continue;
|
|
9
|
+
cancellation, owner changes, and failed, refused, or uncertain work stop later tiers. Prevent
|
|
10
|
+
overlapping batch work; add regression coverage for these behaviors.
|
|
11
|
+
|
|
12
|
+
## [0.8.5](https://github.com/AeonDave/pi-persona-mind/releases/tag/v0.8.5) - 2026-10-26
|
|
13
|
+
|
|
14
|
+
- 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.
|
|
15
|
+
- Remove the worker row on completion while retaining results in the conversation. Keep reviews bounded, rotate completed windows, and handle busy sessions, cancellation, stale owners and errors safely.
|
|
16
|
+
- **Usage change:** use `/mind optimize inspect [target]` to inspect; `/mind optimize [target]` now starts a review instead.
|
|
17
|
+
|
|
3
18
|
## [0.8.4](https://github.com/AeonDave/pi-persona-mind/releases/tag/v0.8.4) - 2026-10-25
|
|
4
19
|
|
|
5
20
|
- Add durable project memory and scope-preserving promotion; expose project/persona/shared scope
|
package/README.md
CHANGED
|
@@ -1,245 +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.
|
|
4
|
+
<img src="https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.8.6/assets/banner.png" alt="pi-persona-mind — durable memory for Pi">
|
|
5
5
|
</p>
|
|
6
6
|
|
|
7
7
|
[](https://github.com/AeonDave/pi-persona-mind/actions/workflows/test.yml) [](https://www.npmjs.com/package/@aeondave/pi-persona-mind) [](LICENSE)
|
|
8
8
|
|
|
9
|
-
Local memory for [Pi](https://github.com/earendil-works/pi): durable
|
|
10
|
-
|
|
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
|
-
|
|
13
|
-
release pair is Mind 0.8.4 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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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.4 | `pi install npm:@aeondave/pi-persona-mind@0.8.4` |
|
|
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
|
|
43
|
-
pi
|
|
30
|
+
pi update npm:@aeondave/pi-persona
|
|
31
|
+
pi update npm:@aeondave/pi-persona-mind
|
|
44
32
|
```
|
|
45
33
|
|
|
46
|
-
Keep only one source
|
|
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
|
-
##
|
|
38
|
+
## Memory tiers
|
|
49
39
|
|
|
50
|
-
|
|
|
40
|
+
| Tier | Contains | Lifetime |
|
|
51
41
|
|---|---|---|
|
|
52
|
-
|
|
|
53
|
-
|
|
|
54
|
-
|
|
|
55
|
-
|
|
|
56
|
-
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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`
|
|
54
|
+
`/mind` and `/persona-mind` are aliases.
|
|
73
55
|
|
|
74
|
-
| Command |
|
|
56
|
+
| Command | Purpose |
|
|
75
57
|
|---|---|
|
|
76
|
-
| `/
|
|
77
|
-
| `/
|
|
78
|
-
| `/
|
|
79
|
-
| `/
|
|
80
|
-
| `/
|
|
81
|
-
| `/
|
|
82
|
-
| `/
|
|
83
|
-
| `/
|
|
84
|
-
| `/
|
|
85
|
-
| `/
|
|
86
|
-
| `/
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
-
|
|
105
|
-
-
|
|
106
|
-
-
|
|
107
|
-
|
|
108
|
-
Prefer declarative facts such as “The project uses Node 22.” An `objective` is prioritized in
|
|
109
|
-
durable injection; a session objective stays in its session.
|
|
110
|
-
|
|
111
|
-
Injection ranks current-task words, explicit tags and repository paths, with a small priority core
|
|
112
|
-
for objectives/invariants. Persona/shared, project, working context, backlog and session notes share
|
|
113
|
-
a **2,400-token planning estimate** (UTF-8 bytes / 3), including wrappers and omission notices.
|
|
114
|
-
Session notes use up to 600 of that estimate. This is not a provider tokenizer or a billing guarantee.
|
|
115
|
-
Whole excerpts are admitted under the budget, omitted facts are counted, and full reads remain available.
|
|
116
|
-
The retrieval is deterministic; it does not infer arbitrary synonyms or establish factual truth.
|
|
117
|
-
|
|
118
|
-
## Review and consolidate
|
|
119
|
-
|
|
120
|
-
Ask the agent to inspect memories against new evidence and propose a consolidation.
|
|
121
|
-
The slash command alone is a local inspection, not a hidden model request. The agent evaluates
|
|
122
|
-
the evidence during its normal foreground turn.
|
|
123
|
-
|
|
124
|
-
1. `memory {action:"optimize", mode:"inspect", target:"project"}` returns IDs and a fingerprint.
|
|
125
|
-
2. Read full facts, then stage explicit replacements with that fingerprint and
|
|
126
|
-
`operations: [{sourceIds, kind, text, tags?, source?}]`.
|
|
127
|
-
3. Review the before/after plan and apply its `planId` through the tool or slash command.
|
|
128
|
-
|
|
129
|
-
One source rewrites a fact; several sources merge them. Each transaction affects one tier.
|
|
130
|
-
`project` changes only the active persona's short-term rows; `project-long` changes that persona's
|
|
131
|
-
durable repository facts; `persona` targets that persona's
|
|
132
|
-
durable store across projects; `shared` targets shared durable facts. Inspect further pages through
|
|
133
|
-
`offset`/`nextOffset`; restart if the fingerprint changes. Similarity compares the current page,
|
|
134
|
-
so absence from its candidate list does not prove the store is duplicate-free.
|
|
135
|
-
|
|
136
|
-
Plans last ten minutes, at most four per active owner. Session/persona/workspace changes invalidate
|
|
137
|
-
them. Concurrent writes refuse application. Consolidation preserves origins and lineage, never
|
|
138
|
-
extends short-term expiry, and never trims unrelated records to fit storage limits. Lineage IDs
|
|
139
|
-
alone are not a full archive of removed text. Each applied consolidation now has a durable before/after
|
|
140
|
-
receipt written before replacement. History retains at most 32 receipts / 2 MiB per target, plus the
|
|
141
|
-
store's recovery backup. Undo preserves unrelated later writes and refuses altered replacements,
|
|
142
|
-
collisions, foreign ownership or expired source facts. A `prepared` receipt means an interrupted
|
|
143
|
-
intent whose commit may or may not have happened; it is kept rather than guessing. Ambiguous IO
|
|
144
|
-
failures can therefore require manual recovery if unresolved receipts fill the history budget.
|
|
145
|
-
|
|
146
|
-
Exact deduplication and expiry cleanup already run automatically. Lexical similarity only suggests
|
|
147
|
-
comparisons; it cannot distinguish agreement from contradiction. Age never deletes a durable fact.
|
|
148
|
-
See [research and decisions](docs/MEMORY-RESEARCH.md).
|
|
149
|
-
|
|
150
|
-
During inspection, staging and application, **Mind** appears in pi-persona's activity tree and F9
|
|
151
|
-
view. The row distinguishes local work, a prepared proposal and a terminal result.
|
|
152
|
-
It does not invent a worker model, tokens or a cancellable agent. Finished rows are bounded and
|
|
153
|
-
remain visible, so a fast local operation does not disappear before it can be read.
|
|
154
|
-
|
|
155
|
-
Automatic review is on by default. Successful saves/promotions mark project or persona memories
|
|
156
|
-
for review; shared memories are excluded. The first eligible burst can run after the main agent
|
|
157
|
-
settles. Every later attempt requires both new pending memories and **1,000,000 main-session input
|
|
158
|
-
tokens since the preceding attempt**. Output, cache and worker tokens do not count. Token usage
|
|
159
|
-
alone never schedules a review, and rapid additions stay queued together instead of launching a
|
|
160
|
-
worker for every save. This is a cost-control policy, not a research-derived optimum.
|
|
161
|
-
Requests coalesce for two seconds after the main agent settles, with no queued work, and actual
|
|
162
|
-
attempts have a five-minute cooldown. Only one review can run at a time; unchanged completed reviews
|
|
163
|
-
are skipped. New input cancels it; that interrupted attempt may retry after a later settled turn and
|
|
164
|
-
the cooldown without waiting for another million tokens. `/mind optimize auto off` cancels and clears
|
|
165
|
-
pending review; saves while off do not queue automatic work. Turning it on waits for the next save.
|
|
166
|
-
`on` and `off` apply immediately to this session. Set `PI_PERSONA_MIND_OPTIMIZE=off` for the initial
|
|
167
|
-
session default, and use `/mind doctor` to inspect the current state.
|
|
168
|
-
|
|
169
|
-
This is a real asynchronous Mind subagent with its own Persona view. It uses exactly the session's
|
|
170
|
-
model, without a substitute or fallback, and has no arbitrary tools. It receives at most 12 full memory
|
|
171
|
-
records within 24,000 JSON characters. Repeated admitted reviews rotate within inspection pages and
|
|
172
|
-
through older pages, reserving room for the newest eligible fact. Rotation resets with its owner;
|
|
173
|
-
it does not launch an unbounded cleanup loop or claim the whole store has been reviewed. It has a
|
|
174
|
-
three-minute deadline and proposes at most four strict
|
|
175
|
-
JSON replacements. The parent validates provenance, owner, freshness and the store fingerprint before
|
|
176
|
-
applying anything. A durable operator card records the before/after proposal before application;
|
|
177
|
-
rejected or stale proposals do not alter their target store. Automatic review does not authorize age-based
|
|
178
|
-
deletion, shared-memory editing or inference that an old fact is false.
|
|
179
|
-
|
|
180
|
-
## Capture, reminders and collaboration
|
|
181
|
-
|
|
182
|
-
Explicit direct-user requests such as “remember that I prefer small changes” are saved before
|
|
183
|
-
the model starts, with a visible receipt. Casual cues suggest capture instead.
|
|
184
|
-
|
|
185
|
-
| Setting | Effect |
|
|
186
|
-
|---|---|
|
|
187
|
-
| `PI_PERSONA_MIND_CAPTURE=auto` | Capture explicit direct-user cues; default |
|
|
188
|
-
| `PI_PERSONA_MIND_CAPTURE=prompt` | Suggest a tool call without automatic writes |
|
|
189
|
-
| `PI_PERSONA_MIND_CAPTURE=off` | Disable cue detection and capture |
|
|
190
|
-
| `PI_PERSONA_MIND_NUDGE=off` | Disable suggestions, not explicit automatic capture |
|
|
191
|
-
|
|
192
|
-
The same preferences appear in pi-persona's settings panel. Environment overrides win; Mind refreshes
|
|
193
|
-
its capture/nudge preferences on session start. The loaded Persona runtime supplies the actual active
|
|
194
|
-
persona, including with selection persistence disabled. Changing council models does not switch memory
|
|
195
|
-
scope. Mind does not infer the active persona from old files or saved selection.
|
|
196
|
-
|
|
197
|
-
Quoted text, worker reports and Intercom/Exocom messages are not direct user input.
|
|
198
|
-
The reserved `pi-persona-deferred-input` replay preserves queued direct-user requests. This is
|
|
199
|
-
a convention between trusted extensions, not protection from arbitrary code in the same process.
|
|
200
|
-
|
|
201
|
-
Workers marked `PI_PERSONA_LEG` or `PI_PERSONA_CHILD` receive only durable identity/objectives:
|
|
202
|
-
their memory scope stays on the persona that launched them, even if the parent switches later.
|
|
203
|
-
They receive no project notes, session notes, backlog, memory tools or wakes. Blocked delegate/council/flow
|
|
204
|
-
reports can suggest backlog capture; they never write it automatically. Discarded nested reports
|
|
205
|
-
do not create invisible reminders.
|
|
206
|
-
|
|
207
|
-
A due backlog item creates one display-only card and a short toast, never an agent turn.
|
|
208
|
-
Opening Pi from the home directory suppresses project injection and wakes.
|
|
209
|
-
|
|
210
|
-
## Storage and development
|
|
211
|
-
|
|
212
|
-
Under `<agentDir>/persona-mind/`: persona/shared facts in `memory/ltm/`, durable repository facts
|
|
213
|
-
in `memory/project/`, working facts in `memory/stm/`,
|
|
214
|
-
deferred work in `backlog/`. Session notes live in Pi's session file. Writes use exclusive locks,
|
|
215
|
-
ownership checks, atomic rename and a last-known-good backup. Imports of old memory data remain
|
|
216
|
-
non-destructive. Scanning and escaped injection reduce unsafe-content exposure; they do not
|
|
217
|
-
prove saved facts true or arbitrary text harmless.
|
|
218
|
-
|
|
219
|
-
An import exceeding the turn's wait budget continues in the background with a temporary information
|
|
220
|
-
notice. That alone does not mean data loss; older entries may become available later. Use
|
|
221
|
-
`/persona-mind doctor` for its state and actual warnings. After fixing a reported import problem,
|
|
222
|
-
`/reload` rechecks the retained original files.
|
|
223
|
-
|
|
224
|
-
```bash
|
|
225
|
-
npm ci
|
|
226
|
-
npm run typecheck
|
|
227
|
-
npm test
|
|
228
|
-
npm run eval:memory
|
|
229
|
-
npm audit --audit-level=low
|
|
230
|
-
```
|
|
231
|
-
|
|
232
|
-
Tests isolate profile/environment and exercise the real Pi 1.4 SDK with an offline provider.
|
|
233
|
-
Qualify an installed host with current pi-persona and optionally an extracted Mind tarball:
|
|
234
|
-
|
|
235
|
-
```bash
|
|
236
|
-
node --import tsx scripts/qualify-host.mjs <pi-package-root> <pi-persona-extension> [<packed-mind-extension>]
|
|
237
|
-
node --import tsx scripts/qualify-package.ts <extracted-package>/src/index.ts <pi-persona-extension>
|
|
238
|
-
```
|
|
239
|
-
|
|
240
|
-
The evaluation reports deterministic retrieval on a small synthetic corpus, including a prior
|
|
241
|
-
substring baseline and context estimates. It does not measure model merge quality or cloud cost.
|
|
242
|
-
These checks verify host integration, not provider authentication or semantic memory quality. Pi supplies
|
|
243
|
-
runtime peers. Development security overrides do not patch a separately installed Pi.
|
|
244
|
-
|
|
245
|
-
[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.6.
|
|
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.
|
|
19
|
+
companion. Mind 0.8.6 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,9 @@ An in-memory session is not advertised as restart-durable.
|
|
|
109
111
|
|
|
110
112
|
## Explicit consolidation
|
|
111
113
|
|
|
112
|
-
The explicit
|
|
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. 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.
|
|
115
|
+
|
|
116
|
+
The manual workflow is inspect → stage exact replacements → apply plan ID. An omitted replacement tag
|
|
113
117
|
list inherits the normalized union from selected sources; an explicit empty list clears tags. Lexical
|
|
114
118
|
rules never approve semantic changes. Learned decay rates, recall counters and age-based LTM deletion
|
|
115
119
|
remain outside the contract.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aeondave/pi-persona-mind",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.6",
|
|
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.
|
|
60
|
+
"image": "https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.8.6/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
|
|
19
|
-
|
|
20
|
-
|
|
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)
|
|
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
|
|
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
|
-
|
|
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,6 +40,8 @@ export interface AutoOptimizeSession {
|
|
|
40
40
|
memoryAdded(ctx: ExtensionContext, target: AutoOptimizeTarget): void;
|
|
41
41
|
status(): string;
|
|
42
42
|
setEnabled(enabled: boolean): void;
|
|
43
|
+
targets(): readonly AutoOptimizeTarget[];
|
|
44
|
+
startExplicit(target?: AutoOptimizeTarget): boolean;
|
|
43
45
|
}
|
|
44
46
|
|
|
45
47
|
export function installAutoOptimize(pi: ExtensionAPI, deps: Dependencies): AutoOptimizeSession {
|
|
@@ -114,5 +116,7 @@ export function installAutoOptimize(pi: ExtensionAPI, deps: Dependencies): AutoO
|
|
|
114
116
|
return { activate, revoke, memoryAdded,
|
|
115
117
|
status: () => boundContext ? scheduler.status() : "inactive · automatic work requires an interactive Persona session",
|
|
116
118
|
setEnabled: (enabled) => scheduler.setEnabled(enabled),
|
|
119
|
+
targets: () => scheduler.targets(),
|
|
120
|
+
startExplicit: (target) => scheduler.startExplicit(target),
|
|
117
121
|
};
|
|
118
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";
|
|
@@ -39,7 +39,8 @@ export class AutoOptimizeScheduler {
|
|
|
39
39
|
private generation = 0;
|
|
40
40
|
private disabledGeneration = 0;
|
|
41
41
|
private timer: (() => void) | undefined;
|
|
42
|
-
private
|
|
42
|
+
private timerGeneration = 0;
|
|
43
|
+
private running: { optimizer: Optimizer; cancel?: () => void; retryTarget?: Target; explicit?: boolean } | undefined;
|
|
43
44
|
private work: Promise<void> = Promise.resolve();
|
|
44
45
|
private last = "waiting for new memory";
|
|
45
46
|
|
|
@@ -65,8 +66,8 @@ export class AutoOptimizeScheduler {
|
|
|
65
66
|
}
|
|
66
67
|
stop(): void { this.interrupt(); this.owner = undefined; this.pending.clear(); this.retryTargets.clear(); this.cursors.clear(); this.inputTokens = 0; this.seen.clear(); this.lastAttempt = -Infinity; }
|
|
67
68
|
interrupt(): void {
|
|
68
|
-
this.timer?.(); this.timer = undefined; this.generation++;
|
|
69
|
-
if (this.enabled && this.running?.retryTarget) {
|
|
69
|
+
this.timer?.(); this.timer = undefined; this.timerGeneration++; this.generation++;
|
|
70
|
+
if (this.enabled && !this.running?.explicit && this.running?.retryTarget) {
|
|
70
71
|
this.pending.add(this.running.retryTarget);
|
|
71
72
|
this.retryTargets.add(this.running.retryTarget);
|
|
72
73
|
}
|
|
@@ -105,14 +106,38 @@ export class AutoOptimizeScheduler {
|
|
|
105
106
|
const eligiblePending = [...this.pending].some((target) => this.allows(owner, target) && (this.retryTargets.has(target) || tokenReady));
|
|
106
107
|
if (!eligiblePending) return;
|
|
107
108
|
const generation = this.generation;
|
|
109
|
+
const timerGeneration = ++this.timerGeneration;
|
|
108
110
|
this.timer = this.schedule(() => {
|
|
111
|
+
if (timerGeneration !== this.timerGeneration) return;
|
|
109
112
|
this.timer = undefined;
|
|
110
|
-
if (generation !== this.generation) return;
|
|
113
|
+
if (generation !== this.generation || this.running) return;
|
|
111
114
|
this.work = this.run().catch(() => { this.last = "inspection failed; no automatic retry"; });
|
|
112
115
|
}, Math.max(AUTO_IDLE_MS, this.lastAttempt + AUTO_COOLDOWN_MS - this.now()));
|
|
113
116
|
}
|
|
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 {
|
|
121
|
+
const owner = this.owner;
|
|
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;
|
|
125
|
+
this.timer?.(); this.timer = undefined; this.timerGeneration++;
|
|
126
|
+
const generation = this.generation;
|
|
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;
|
|
130
|
+
this.last = "explicit review failed; inspect current memory before retrying because apply may have completed";
|
|
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 */ }
|
|
133
|
+
}).finally(() => {
|
|
134
|
+
if (generation === this.generation && this.safeCurrent(owner) && this.safeIdle(owner) && this.pending.size) this.settled();
|
|
135
|
+
});
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
114
138
|
join(): Promise<void> { return this.work; }
|
|
115
139
|
private safeCurrent(owner: AutoOptimizeOwner): boolean { try { return this.owner === owner && owner.current(); } catch { return false; } }
|
|
140
|
+
private safeIdle(owner: AutoOptimizeOwner): boolean { try { return owner.idle(); } catch { return false; } }
|
|
116
141
|
private allows(owner: AutoOptimizeOwner, target: Target): boolean { return owner.allowedTargets.includes(target); }
|
|
117
142
|
private remember(owner: AutoOptimizeOwner, target: Target, digest: string, state: AutoAttempt["state"], at: number): void {
|
|
118
143
|
owner.recordAttempt({ digest, target, at, state });
|
|
@@ -120,27 +145,39 @@ export class AutoOptimizeScheduler {
|
|
|
120
145
|
this.seen.add(digest); while (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!);
|
|
121
146
|
}
|
|
122
147
|
}
|
|
123
|
-
private async run(): Promise<void> {
|
|
148
|
+
private async run(explicitTargets?: readonly Target[], explicit = false, qualifyTargets = false): Promise<void> {
|
|
124
149
|
const owner = this.owner;
|
|
125
|
-
if (!owner || !this.enabled || !this.safeCurrent(owner) || !
|
|
150
|
+
if (!owner || (!explicit && !this.enabled) || !this.safeCurrent(owner) || !this.safeIdle(owner) || this.running) return;
|
|
126
151
|
const generation = this.generation;
|
|
127
152
|
const disabledGeneration = this.disabledGeneration;
|
|
128
|
-
const current = () => generation === this.generation && this.enabled && this.
|
|
129
|
-
const mayRetry = () => this.enabled && this.disabledGeneration === disabledGeneration && this.safeCurrent(owner);
|
|
153
|
+
const current = () => generation === this.generation && (explicit || this.enabled) && this.safeIdle(owner) && this.safeCurrent(owner);
|
|
154
|
+
const mayRetry = () => !explicit && this.enabled && this.disabledGeneration === disabledGeneration && this.safeCurrent(owner);
|
|
130
155
|
const optimizer = owner.optimizer();
|
|
131
|
-
const running: NonNullable<AutoOptimizeScheduler["running"]> = { optimizer };
|
|
156
|
+
const running: NonNullable<AutoOptimizeScheduler["running"]> = { optimizer, explicit };
|
|
132
157
|
let attemptRecorded = false;
|
|
133
158
|
let unsettledTarget: Target | undefined;
|
|
134
159
|
let nextCursor: CoverageCursor | undefined;
|
|
135
160
|
let retryRequiresSettled = false;
|
|
161
|
+
let activeTarget: Target | undefined;
|
|
162
|
+
const targets = explicit ? explicitTargets ?? [] : [...this.pending];
|
|
163
|
+
const report = (target: Target, title: string, body: string, summary?: string): boolean => {
|
|
164
|
+
if (!current()) return false;
|
|
165
|
+
const qualifiedBody = qualifyTargets && !body.startsWith("Target:")
|
|
166
|
+
? `Target: ${target} — ${summary ?? body.split("\n", 1)[0] ?? "review result"}\n${body}`
|
|
167
|
+
: body;
|
|
168
|
+
owner.report(qualifyTargets ? `${title} — ${target}` : title, qualifiedBody);
|
|
169
|
+
return true;
|
|
170
|
+
};
|
|
136
171
|
this.running = running;
|
|
137
172
|
try {
|
|
138
|
-
for (const target of
|
|
173
|
+
for (const target of targets) {
|
|
174
|
+
activeTarget = target;
|
|
175
|
+
if (!current()) return;
|
|
139
176
|
if (!this.allows(owner, target)) { this.pending.delete(target); this.retryTargets.delete(target); continue; }
|
|
140
177
|
const retry = this.retryTargets.has(target);
|
|
141
178
|
const tokenReady = this.lastAttempt === -Infinity || this.inputTokens >= AUTO_INPUT_TOKEN_THRESHOLD;
|
|
142
|
-
if (!retry && !tokenReady) continue;
|
|
143
|
-
this.pending.delete(target);
|
|
179
|
+
if (!explicit && !retry && !tokenReady) continue;
|
|
180
|
+
if (!explicit) this.pending.delete(target);
|
|
144
181
|
const cursor = this.cursors.get(target) ?? { offset: 0, withinPage: 0 };
|
|
145
182
|
let inspection: OptimizeInspection | OptimizeFailure;
|
|
146
183
|
let newestInspection: OptimizeInspection | undefined;
|
|
@@ -150,18 +187,20 @@ export class AutoOptimizeScheduler {
|
|
|
150
187
|
const latest = await optimizer.inspect(target, { max: 100, offset: 0 });
|
|
151
188
|
if (latest.ok && latest.target === target && latest.fingerprint === inspection.fingerprint) newestInspection = latest;
|
|
152
189
|
else {
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
190
|
+
if (mayRetry()) this.pending.add(target);
|
|
191
|
+
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";
|
|
192
|
+
if (explicit) report(target, "Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`, "inspection snapshot changed; no worker started");
|
|
193
|
+
return;
|
|
156
194
|
}
|
|
157
195
|
}
|
|
158
|
-
}
|
|
159
|
-
catch {
|
|
196
|
+
} catch {
|
|
160
197
|
if (!current()) {
|
|
161
198
|
if (mayRetry()) this.pending.add(target);
|
|
162
199
|
return;
|
|
163
200
|
}
|
|
164
201
|
this.last = "store inspection failed; see /mind doctor";
|
|
202
|
+
if (explicit) report(target, "Mind optimization result", `Bounded review could not inspect this record window: ${this.last}.`, "inspection failed; no worker started");
|
|
203
|
+
if (explicit) return;
|
|
165
204
|
continue;
|
|
166
205
|
}
|
|
167
206
|
if (!current()) {
|
|
@@ -170,8 +209,18 @@ export class AutoOptimizeScheduler {
|
|
|
170
209
|
if (mayRetry()) this.pending.add(target);
|
|
171
210
|
return;
|
|
172
211
|
}
|
|
173
|
-
if (!inspection.ok) {
|
|
174
|
-
|
|
212
|
+
if (!inspection.ok) {
|
|
213
|
+
this.last = "store inspection refused; see /mind doctor";
|
|
214
|
+
if (explicit) report(target, "Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`, "inspection refused; no worker started");
|
|
215
|
+
if (explicit) return;
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
if (inspection.target !== target) {
|
|
219
|
+
this.last = "store inspection returned a different tier; no worker started";
|
|
220
|
+
if (explicit) report(target, "Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`, "inspection returned the wrong target; no worker started");
|
|
221
|
+
if (explicit) return;
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
175
224
|
const page = selectAutoInputPage(inspection, owner.persona, cursor.withinPage, newestInspection);
|
|
176
225
|
nextCursor = page.pageComplete
|
|
177
226
|
? { offset: inspection.nextOffset ?? 0, withinPage: 0 }
|
|
@@ -181,30 +230,40 @@ export class AutoOptimizeScheduler {
|
|
|
181
230
|
this.cursors.set(target, nextCursor);
|
|
182
231
|
this.retryTargets.delete(target);
|
|
183
232
|
this.last = "no eligible records in this bounded page";
|
|
233
|
+
if (explicit && !report(target, "Mind optimization result", formatAutoInputSkip(target, inspection, page))) return;
|
|
184
234
|
continue;
|
|
185
235
|
}
|
|
186
|
-
if (this.seen.has(input.digest)) {
|
|
236
|
+
if (!explicit && this.seen.has(input.digest)) {
|
|
187
237
|
this.cursors.set(target, nextCursor);
|
|
188
238
|
this.retryTargets.delete(target);
|
|
189
239
|
this.last = "this bounded record set was already reviewed";
|
|
190
240
|
continue;
|
|
191
241
|
}
|
|
242
|
+
if (!current()) return;
|
|
192
243
|
const worker = owner.launch(buildAutoPrompt(input));
|
|
193
|
-
if (!worker.ok) {
|
|
244
|
+
if (!worker.ok) {
|
|
245
|
+
if (!explicit) this.pending.add(target);
|
|
246
|
+
this.last = worker.reason;
|
|
247
|
+
if (explicit) report(target, "Mind optimization result", `Bounded review was not admitted: ${worker.reason}. No memory changed.`, "worker admission refused; no memory changed");
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
194
250
|
const attemptAt = this.now();
|
|
195
251
|
running.cancel = worker.cancel;
|
|
196
252
|
running.retryTarget = target;
|
|
197
253
|
this.retryTargets.delete(target);
|
|
198
|
-
this.lastAttempt = attemptAt; this.inputTokens = 0;
|
|
254
|
+
if (!explicit) { this.lastAttempt = attemptAt; this.inputTokens = 0; }
|
|
255
|
+
this.last = "Mind is reviewing memory";
|
|
199
256
|
unsettledTarget = target;
|
|
200
257
|
const settle = (): void => {
|
|
201
|
-
this.remember(owner, target, input.digest, "settled", attemptAt);
|
|
258
|
+
if (!explicit) this.remember(owner, target, input.digest, "settled", attemptAt);
|
|
202
259
|
if (nextCursor) this.cursors.set(target, nextCursor);
|
|
203
260
|
unsettledTarget = undefined;
|
|
204
261
|
};
|
|
205
262
|
try {
|
|
206
|
-
|
|
207
|
-
|
|
263
|
+
if (!explicit) {
|
|
264
|
+
this.remember(owner, target, input.digest, "started", attemptAt);
|
|
265
|
+
attemptRecorded = true;
|
|
266
|
+
}
|
|
208
267
|
} catch {
|
|
209
268
|
try { running.cancel?.(); } catch { /* best-effort stop before apply */ }
|
|
210
269
|
this.last = "attempt could not be saved; worker cancelled before apply";
|
|
@@ -213,22 +272,43 @@ export class AutoOptimizeScheduler {
|
|
|
213
272
|
const result = await worker.completion;
|
|
214
273
|
if (!current()) return;
|
|
215
274
|
if (workerWasStopped(result)) {
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
275
|
+
if (!explicit) {
|
|
276
|
+
retryRequiresSettled = true;
|
|
277
|
+
this.pending.add(target);
|
|
278
|
+
this.retryTargets.add(target);
|
|
279
|
+
}
|
|
219
280
|
unsettledTarget = undefined;
|
|
220
|
-
this.last = "review interrupted; waiting for the next settled event";
|
|
281
|
+
this.last = explicit ? "explicit review stopped; memory unchanged" : "review interrupted; waiting for the next settled event";
|
|
282
|
+
if (explicit) report(target, "Mind optimization result", this.last, "worker stopped; memory unchanged");
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
if (!result.ok) {
|
|
286
|
+
settle(); this.last = "worker failed; memory unchanged";
|
|
287
|
+
report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded review · ${this.last}${result.error ? `: ${result.error}` : ""}`, "worker failed; memory unchanged");
|
|
221
288
|
return;
|
|
222
289
|
}
|
|
223
|
-
if (!result.ok) { settle(); this.last = "worker failed; memory unchanged"; owner.report("Mind automatic optimization", `${this.last}${result.error ? `: ${result.error}` : ""}`); return; }
|
|
224
290
|
const parsed = parseAutoProposal(result.output, input);
|
|
225
|
-
if (!parsed.ok) {
|
|
291
|
+
if (!parsed.ok) {
|
|
292
|
+
settle(); this.last = "proposal refused; memory unchanged";
|
|
293
|
+
report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded review · ${this.last}: ${parsed.reason}`, "proposal refused; memory unchanged");
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
226
296
|
const provenance = `Worker ${worker.runId} · ${worker.model} · ${worker.thinking}${result.resultRef ? `\nTerminal report: ${result.resultRef}` : ""}`;
|
|
227
|
-
if (!parsed.operations.length) {
|
|
297
|
+
if (!parsed.operations.length) {
|
|
298
|
+
settle(); this.last = "bounded review found no safe consolidation in this record set";
|
|
299
|
+
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");
|
|
300
|
+
if (!explicit) return;
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
if (!current()) return;
|
|
228
304
|
const plan = await optimizer.preview({ target: input.target, fingerprint: input.fingerprint, operations: parsed.operations });
|
|
229
305
|
if (!current()) return;
|
|
230
|
-
if (!plan.ok) {
|
|
231
|
-
|
|
306
|
+
if (!plan.ok) {
|
|
307
|
+
settle(); this.last = "store or proposal changed; nothing applied";
|
|
308
|
+
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");
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
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;
|
|
232
312
|
if (!current()) { optimizer.invalidate(); return; }
|
|
233
313
|
const applied = await optimizer.apply(plan.planId);
|
|
234
314
|
if (!current()) return;
|
|
@@ -238,9 +318,16 @@ export class AutoOptimizeScheduler {
|
|
|
238
318
|
? applied.receiptId ? `\nUndo: /mind optimize undo ${applied.receiptId} ${applied.target}.` : "\nNo durable undo receipt was returned."
|
|
239
319
|
: "";
|
|
240
320
|
const warning = applied.ok && applied.warning ? `\nWarning: ${applied.warning}` : "";
|
|
241
|
-
|
|
242
|
-
|
|
321
|
+
const resultSummary = applied.ok
|
|
322
|
+
? `${applied.changed} replacement${applied.changed === 1 ? "" : "s"} applied${applied.warning ? "; receipt finalization warning" : ""}`
|
|
323
|
+
: `not applied: ${applied.reason}`;
|
|
324
|
+
if (!report(target, explicit ? "Mind optimization result" : "Mind automatic result", `Bounded coverage: one selected record window; ${this.last}\n${provenance}${receipt}${warning}`, resultSummary)) return;
|
|
325
|
+
if (!applied.ok || applied.warning || !explicit) return;
|
|
243
326
|
}
|
|
327
|
+
} catch (error) {
|
|
328
|
+
if (!explicit) throw error;
|
|
329
|
+
this.last = "explicit review failed unexpectedly; inspect current memory before retrying because apply may have completed";
|
|
330
|
+
if (activeTarget && current()) report(activeTarget, "Mind optimization result", `Bounded review failed unexpectedly; ${this.last}.`, "review failed unexpectedly; inspect current memory before retrying");
|
|
244
331
|
} finally {
|
|
245
332
|
optimizer.invalidate();
|
|
246
333
|
if (this.running === running) this.running = undefined;
|
|
@@ -250,16 +337,41 @@ export class AutoOptimizeScheduler {
|
|
|
250
337
|
this.last = "review interrupted; waiting for the next settled event";
|
|
251
338
|
}
|
|
252
339
|
// One actual attempt may leave other dirty tiers pending; they need the input floor
|
|
253
|
-
// and cooldown. Only the same interrupted
|
|
254
|
-
if (attemptRecorded && this.pending.size > 0 && current() && !retryRequiresSettled) this.settled();
|
|
340
|
+
// and cooldown. Only the same interrupted tier bypasses the token floor.
|
|
341
|
+
if (!explicit && attemptRecorded && this.pending.size > 0 && current() && !retryRequiresSettled) this.settled();
|
|
255
342
|
}
|
|
256
343
|
}
|
|
257
344
|
}
|
|
258
345
|
|
|
346
|
+
export function formatAutoInputSkip(target: Target, inspection: OptimizeInspection, page: Extract<AutoInputPage, { reason: AutoInputSkipReason }>): string {
|
|
347
|
+
const offset = Number.isSafeInteger(inspection.offset) && inspection.offset >= 0 ? inspection.offset : 0;
|
|
348
|
+
const returned = Array.isArray(inspection.entries) ? inspection.entries.length : 0;
|
|
349
|
+
const matched = Number.isSafeInteger(inspection.matched) && inspection.matched >= 0 ? inspection.matched : 0;
|
|
350
|
+
const total = Number.isSafeInteger(inspection.total) && inspection.total >= 0 ? inspection.total : 0;
|
|
351
|
+
const eligible = Number.isSafeInteger(page.eligibleCount) && page.eligibleCount >= 0 ? page.eligibleCount : 0;
|
|
352
|
+
const coverage = page.pageComplete ? "candidate page covered" : `within-page rotation continues at ${page.nextRotation}`;
|
|
353
|
+
const morePages = inspection.nextOffset === undefined ? "" : `; further inspection page starts at ${inspection.nextOffset}`;
|
|
354
|
+
const reasons = {
|
|
355
|
+
"invalid-input": "the bounded input or owner identity was invalid",
|
|
356
|
+
"empty-page": "the selected page is empty or exhausted; this does not establish that the whole target is empty",
|
|
357
|
+
"no-safe-owned-facts": "this page contains no safe, owned eligible facts",
|
|
358
|
+
"single-short-record": "the only admitted safe, owned fact in this selected window is shorter than the 1,200-character single-record minimum",
|
|
359
|
+
"input-budget": "the 24,000-character input budget cannot admit enough full records in this window; records are not split or truncated",
|
|
360
|
+
} satisfies Record<AutoInputSkipReason, string>;
|
|
361
|
+
const headlines: Record<AutoInputSkipReason, string> = {
|
|
362
|
+
"invalid-input": "invalid input",
|
|
363
|
+
"empty-page": "empty/exhausted page",
|
|
364
|
+
"no-safe-owned-facts": "no safe/owned facts",
|
|
365
|
+
"single-short-record": "single fact under 1,200 characters",
|
|
366
|
+
"input-budget": "full-record input budget too small",
|
|
367
|
+
};
|
|
368
|
+
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]}.`;
|
|
369
|
+
}
|
|
370
|
+
|
|
259
371
|
function workerWasStopped(result: MindWorkerResult): boolean {
|
|
260
372
|
return result.status === "stopped";
|
|
261
373
|
}
|
|
262
374
|
|
|
263
375
|
function formatAutoPlan(plan: OptimizePlan): string {
|
|
264
|
-
return `Staged
|
|
376
|
+
return `Staged proposed change · ${plan.beforeCount} entries → ${plan.afterCount}\n${JSON.stringify(plan.changes, null, 2)}`;
|
|
265
377
|
}
|
|
@@ -21,6 +21,8 @@ export type MindCommand =
|
|
|
21
21
|
| { type: "reset" }
|
|
22
22
|
| { type: "migrate-persona" }
|
|
23
23
|
| { type: "session" }
|
|
24
|
+
| { type: "optimize-run"; target?: Exclude<MindOptimizeTarget, "shared"> }
|
|
25
|
+
| { type: "optimize-shared-refused" }
|
|
24
26
|
| { type: "optimize-inspect"; target: MindOptimizeTarget }
|
|
25
27
|
| { type: "optimize-show"; planId: string }
|
|
26
28
|
| { type: "optimize-apply"; planId: string }
|
|
@@ -30,7 +32,7 @@ export type MindCommand =
|
|
|
30
32
|
| { type: "invalid"; message: string };
|
|
31
33
|
|
|
32
34
|
const USAGE =
|
|
33
|
-
"usage: /persona-mind [help|doctor|session|reset [workspace]|migrate-persona|optimize [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]]";
|
|
34
36
|
|
|
35
37
|
export interface MindCommandDeps {
|
|
36
38
|
agentDir: string;
|
|
@@ -40,7 +42,7 @@ export interface MindCommandDeps {
|
|
|
40
42
|
getSessionMemory(): SessionMemory;
|
|
41
43
|
getOptimizer(ctx: ExtensionContext): MemoryOptimizer;
|
|
42
44
|
activity?(ctx: ExtensionContext): MindActivityRunner | undefined;
|
|
43
|
-
autoOptimize?: { status(): string; setEnabled(enabled: boolean): void };
|
|
45
|
+
autoOptimize?: { status(): string; setEnabled(enabled: boolean): void; targets?(): readonly Exclude<MindOptimizeTarget, "shared">[]; startExplicit?(target?: Exclude<MindOptimizeTarget, "shared">): boolean };
|
|
44
46
|
isCurrent(ctx: ExtensionContext): boolean;
|
|
45
47
|
ensureLegacyMigrated(ctx: ExtensionContext, includeAmbiguousPersonaAlias?: boolean, awaitCompletion?: boolean): Promise<void>;
|
|
46
48
|
migrationStatus(): string;
|
|
@@ -76,16 +78,39 @@ export function registerMindCommands(pi: ExtensionAPI, deps: MindCommandDeps): v
|
|
|
76
78
|
"/persona-mind session — list notes on this active session branch",
|
|
77
79
|
"/persona-mind reset [workspace] — clear this project's short-term memory and backlog",
|
|
78
80
|
"/persona-mind migrate-persona — explicitly import an ambiguous historical persona alias",
|
|
79
|
-
"/persona-mind optimize [project|project-long|persona
|
|
80
|
-
"
|
|
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
|
+
"/persona-mind optimize inspect [project|project-long|persona|shared] — read-only inspection; shared changes require a manually reviewed workflow.",
|
|
81
83
|
"/persona-mind optimize show <planId> — inspect exact staged text; /persona-mind optimize apply <planId> commits that plan only",
|
|
82
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)",
|
|
83
85
|
"/persona-mind optimize auto [status|on|off] — inspect or switch automatic review for this session; off cancels pending work",
|
|
84
|
-
"/mind is an alias.
|
|
86
|
+
"/mind is an alias. Explicit review bypasses automatic gates but not worker/busy/owner safeguards; it reports bounded coverage and applies only validated CAS plans. Automatic review remains idle-gated.",
|
|
85
87
|
].join("\n");
|
|
86
88
|
publish(ctx, deps, "pi-persona-mind help", body, "Command reference is in the expandable card.");
|
|
87
89
|
return;
|
|
88
90
|
}
|
|
91
|
+
if (command.type === "optimize-shared-refused") {
|
|
92
|
+
ctx.ui.notify("Shared memory is excluded from LLM optimization. Use `/mind optimize inspect shared` and a manually reviewed workflow.", "warning");
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (command.type === "optimize-run") {
|
|
96
|
+
if (deps.isDelegatedLeg || !deps.autoOptimize?.startExplicit) {
|
|
97
|
+
ctx.ui.notify("Visible Persona-hosted memory review is unavailable in this session.", "warning");
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (!captureSessionOwner(deps, ctx)()) {
|
|
101
|
+
ctx.ui.notify("Memory session owner changed; optimization was not started.", "warning");
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
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
|
+
}
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
89
114
|
if (command.type === "optimize-auto") {
|
|
90
115
|
if (!captureSessionOwner(deps, ctx)()) {
|
|
91
116
|
ctx.ui.notify("Memory session owner changed; automatic optimization was not changed.", "warning");
|
|
@@ -318,9 +343,12 @@ export function parseMindCommand(args: string): MindCommand {
|
|
|
318
343
|
if (parts.length === 3 && (parts[2] === "status" || parts[2] === "on" || parts[2] === "off")) return { type: "optimize-auto", action: parts[2] };
|
|
319
344
|
return { type: "invalid", message: USAGE };
|
|
320
345
|
}
|
|
321
|
-
if (parts.length ===
|
|
322
|
-
if (parts
|
|
323
|
-
|
|
346
|
+
if (parts[1] === "inspect" && parts.length === 2) return { type: "optimize-inspect", target: "project" };
|
|
347
|
+
if (parts[1] === "inspect" && parts.length === 3 && isOptimizeTarget(parts[2])) return { type: "optimize-inspect", target: parts[2] };
|
|
348
|
+
if (parts.length === 1 || parts.length === 2 && parts[1] === "all") return { type: "optimize-run" };
|
|
349
|
+
if (parts.length === 2 && parts[1] === "shared") return { type: "optimize-shared-refused" };
|
|
350
|
+
if (parts.length === 2 && (parts[1] === "project" || parts[1] === "project-long" || parts[1] === "persona")) {
|
|
351
|
+
return { type: "optimize-run", target: parts[1] };
|
|
324
352
|
}
|
|
325
353
|
if (parts.length === 3 && (parts[1] === "show" || parts[1] === "apply") && isPlanId(args.trim().split(/\s+/)[2])) {
|
|
326
354
|
const planId = args.trim().split(/\s+/)[2]!;
|