Repository navigation
Expand file tree
/
Copy pathSPEC.html
More file actions
497 lines (495 loc) · 38.8 KB
/
Copy pathSPEC.html
File metadata and controls
497 lines (495 loc) · 38.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mega-smart-context - behavior spec</title>
<meta name="generator" content="html-as-doc">
<meta name="doc-source" content="docs/SPEC.md">
<style>
:root{color-scheme:light dark;--fg:#1d2433;--muted:#5b6475;--bg:#fff;--panel:#f7f9fc;--line:#d8dee9;--accent:#0b6e99;--code:#f4f6fa;--warn:#8a5a00}
@media (prefers-color-scheme:dark){:root{--fg:#e6eaf2;--muted:#9aa4b8;--bg:#11151c;--panel:#161c25;--line:#2b3342;--accent:#6cc4e8;--code:#1a202a;--warn:#e0b25c}}
*{box-sizing:border-box}
body{margin:0 auto;max-width:54rem;padding:2.5rem 1.25rem 5rem;background:var(--bg);color:var(--fg);font:16px/1.65 system-ui,-apple-system,"Segoe UI",sans-serif;-webkit-text-size-adjust:100%}
main{display:block}
h1,h2,h3,h4{line-height:1.25;margin:2.2rem 0 .8rem;scroll-margin-top:1rem}
section{scroll-margin-top:1rem}
h1{font-size:1.95rem;border-bottom:2px solid var(--line);padding-bottom:.45rem;margin-top:0}
h2{font-size:1.4rem;border-bottom:1px solid var(--line);padding-bottom:.3rem}
h3{font-size:1.12rem}
h4{font-size:1rem;color:var(--muted)}
p,ul,ol,table,pre,blockquote{margin:.8rem 0}
a{color:var(--accent);text-decoration-thickness:.06em;text-underline-offset:.15em}
a:hover{text-decoration-style:dotted}
code{background:var(--code);padding:.12em .34em;border-radius:.25rem;font:0.9em/1.4 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
pre{position:relative;background:var(--code);border:1px solid var(--line);border-radius:.45rem;padding:.85rem 1rem;overflow:auto}
pre code{background:none;padding:0;font-size:.875rem;line-height:1.55}
pre.code[data-lang]::before{content:attr(data-lang);position:absolute;top:0;right:0;padding:.15rem .5rem;border-left:1px solid var(--line);border-bottom:1px solid var(--line);border-radius:0 .45rem 0 .45rem;background:var(--panel);color:var(--muted);font:600 .68rem/1.4 ui-monospace,monospace;text-transform:lowercase;letter-spacing:.03em}
pre.verbatim{border-left:4px solid var(--warn)}
pre.verbatim::before{content:"verbatim — " attr(data-why);display:block;color:var(--warn);font:600 .76rem/1.4 ui-monospace,monospace;margin-bottom:.5rem;white-space:pre-wrap}
pre.mermaid{background:var(--bg);border:1px dashed var(--line)}
table{border-collapse:collapse;width:100%;display:block;overflow:auto}
th,td{border:1px solid var(--line);padding:.45rem .7rem;text-align:left;vertical-align:top}
th{background:var(--code);font-weight:600}
blockquote{margin-left:0;padding:.1rem 0 .1rem 1rem;border-left:3px solid var(--line);color:var(--muted)}
blockquote>:first-child{margin-top:0}
blockquote>:last-child{margin-bottom:0}
hr{border:0;border-top:1px solid var(--line);margin:2.4rem 0}
ul,ol{padding-left:1.6rem}
li{margin:.25rem 0}
li>ul,li>ol{margin:.25rem 0}
li.task{list-style:none;margin-left:-1.35rem}
li.task input{margin-right:.5rem}
img{max-width:100%;height:auto}
.doc-header{color:var(--muted);font-size:.82rem;margin-bottom:2rem;display:flex;flex-wrap:wrap;gap:.4rem .75rem;align-items:baseline}
.doc-header .doc-kicker{margin:0}
.doc-header code{font-size:.95em}
.doc-footer{margin-top:3.5rem;padding-top:1rem;border-top:1px solid var(--line);color:var(--muted);font-size:.8rem}
.doc-footer p{margin:.25rem 0}
.skip-link{position:absolute;left:-999px}
.skip-link:focus{left:1rem;top:1rem;background:var(--panel);padding:.5rem;border-radius:.3rem;z-index:9}
@media print{:root{--bg:#fff;--fg:#000}body{max-width:none;padding:0}.doc-header,.doc-footer{color:#444}pre,table,blockquote{break-inside:avoid}}
</style>
</head>
<body>
<a class="skip-link" href="#content">Skip to content</a>
<header class="doc-header">
<p class="doc-kicker">Rendered from <code>docs/SPEC.md</code></p>
</header>
<main id="content">
<h1 id="mega-smart-context-behavior-spec">mega-smart-context - behavior spec</h1>
<p>User-visible behavior only: what the product does and what a user sees, readable without knowing the code. Behavior belongs here even when the code is where the reason for it lives. The reason, the mechanism and the traps live in <code>docs/features/</code>; process and hard rules live in <code>AGENTS.md</code>.</p>
<section id="scope">
<h2>Scope</h2>
<p><code>mega-smart-context</code> is an OpenCode 2.0 CLI plugin that hands context management to the model. Instead of replaying the append-only transcript, every model request is rebuilt from three parts:</p>
<ol>
<li>the <strong>memory document</strong> the model wrote;
</li>
<li>a short <strong>working window</strong> of the newest turns, verbatim;
</li>
<li>the <strong>current turn</strong>.
</li>
</ol>
<p>The model is told what it owns and how to use it. It folds durable facts, decisions, files and open threads into memory, archives a turn it wants to keep, or purges one it does not. The plugin enforces the caps, keeps the current turn intact, and never edits the durable transcript.</p>
<p>It is for long agent sessions where replaying history grows without bound.</p>
<p>It deliberately does <strong>not</strong>:</p>
<ul>
<li>edit the durable transcript; it rewrites only the request the host is about to send;
</li>
<li>run a private model to summarize; there is no automatic semantic fold;
</li>
<li>seed files, facts or a plan from observed tool calls; the model writes them;
</li>
<li>protect the first user message; <code>goal</code> is the only guaranteed record of the request after the first turn leaves the window;
</li>
<li>share memory between a parent and a subagent; every session is independent;
</li>
<li>replace the host's compactor when memory is empty;
</li>
<li>use a real tokenizer; every number is an estimate at <code>charsPerToken</code>.
</li>
</ul>
</section>
<section id="what-the-model-sees">
<h2>What the model sees</h2>
<p>Every request starts with a <code><smart-context></code> block:</p>
<pre class="code"><code>goal: "..."
## Plan
- [active] 1. ...
## Facts
- "key": "value"
## Files
- "path": "what was done there"
## Decisions
- "name": "decision and why"
## Open
- "..."
## Refs
- docs/features/x.html#how-why - "gist" (~38 est; feature_map page:"x.html" section:"how-why")
## Notes
"..."
## Pending eviction
- u12 · "mechanical gist" · ~2.1k est
-> smart_context action:"archive" turn:"u12" gist:"..." (or action:"purge" turn:"u12")</code></pre>
<p>An empty <code>goal</code> renders an explicit warning. Values are JSON-quoted so a newline or a delimiter inside a model-written note cannot change the shape. The block is data, not instructions; the standing policy lives in the system message. It carries no live counters either: the running numbers are read on demand with <code>smart_context { action:"stats" }</code> or <code>/context</code>, so the block changes only when memory itself does.</p>
<p>The working window follows the block, verbatim, newest turns first in budget terms. The current turn is always kept, including every tool call and result the model just asked for.</p>
<p>Nothing the plugin does to a message in the window depends on a newer turn. An oversized tool result is shortened by a pure function of its own bytes, and reasoning is passed through exactly as the host sent it. A message therefore keeps the same bytes on every later pass, so a provider's prefix cache above it stays warm.</p>
<p>With <code>contextLayout:"append"</code> the first block is a checkpoint and a patch does not rewrite it. The request carries the checkpoint, the turns, a <code><smart-context-update></code> block after each completed turn that wrote memory, the current turn, and a <code><smart-context-state></code> note after it. The update block carries only the accepted delta; the state note carries the live mode, the pool usage and any pending eviction. The note prints the pool cap only when the model's real context window is really small (< 300k, <code>SMALL_WINDOW_MAX</code>), so a big-window model is never told it has a small one. The note trails the turn because its live numbers change on every pass, and a byte that changes before the current turn would make the provider re-read the whole turn on each tool loop. <code>read</code> still returns the merged document.</p>
<p>Host <strong>notices</strong> - the Plan/Build reminders the host injects as synthetic user messages, and the nudge it appends when a reply is cut off at the output-token limit - are not replayed as turns. The plugin strips them from the working window and pins them into the system prompt under "## Pinned host notices", newest first - every distinct text except the mode pair, where only the mode the host announced last is pinned (a Plan and a Build reminder cannot both be in force, and pinning both left the superseded "do not implement" text reading as the live instruction). "Newest" is recency of emission: a text the host re-emits moves to the end, so the refusal lands on the instruction that is actually live. A mode switch therefore cannot evict a turn, and the standing instruction survives every pass until a newer notice replaces it. The model may retire a superseded notice with <code>smart_context { action:"notice", remove:"<id>" }</code>; the newest is the live instruction and a removal of it is refused. A retirement outlives the pass that recorded it - the text stays retired while the host's window still holds a copy - and clears when the host emits the same text again under a new id.</p>
<p>Host messages split into a second class. A background job's completion (a <code><shell></code> or <code><subagent></code> block) arrives the same way a notice does, but it belongs to the turn that launched it: the plugin leaves it in the window, counts its bytes toward that turn, and starts no turn of its own, so a job finishing cannot age a pending eviction or show up as a working turn. The host's fixed one-sentence "The previous response was interrupted" continuation is a <em>cue</em>: the same tail treatment, but never pinned, because it is stale once the model has continued and is not a standing instruction.</p>
<p>What the plugin never counts is the host's own instruction set. Its <code>core/instructions</code> and neighbouring blobs ride in the request's system parts beside the policy, and no budget includes them: <code>/context</code> reports them as <code>host system ~X est (N parts)</code> for display only, and the line is absent when the host supplies no such part. When the build's debug option is on, the context pass also logs the count and the head of each such part, which is how the shape of <code>event.system</code> is checked.</p>
</section>
<section id="the-first-turn-and-goal">
<h2>The first turn and <code>goal</code></h2>
<p>On the first turn the current user message is visible. Once it leaves the working window it is gone; only <code>goal</code> survives. The policy tells the model to write the request into <code>goal</code> on the first turn, and the block shows <code>goal: (empty ...)</code> until it does. There is no protected first message and no automatic seed.</p>
</section>
<section id="budgets">
<h2>Budgets</h2>
<table>
<thead>
<tr>
<th>Budget</th>
<th>Default</th>
<th>What it measures</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>memoryTokens</code></td>
<td>100,000</td>
<td>the rendered memory document, estimated</td>
</tr>
<tr>
<td><code>workingTokens</code></td>
<td>200,000</td>
<td>the verbatim working window, estimated</td>
</tr>
<tr>
<td><code>compactKeepTokens</code></td>
<td>20,000</td>
<td>the verbatim turns an append-layout compaction keeps, estimated</td>
</tr>
<tr>
<td><code>rebuildOnCompaction</code></td>
<td>false</td>
<td>rebuild the retained tail's bytes at a fold</td>
</tr>
<tr>
<td><code>charsPerToken</code></td>
<td>4</td>
<td>the divisor that turns characters into estimated tokens</td>
</tr>
<tr>
<td><code>maxResultChars</code></td>
<td>4,000</td>
<td>one tool result larger than this is shortened head/tail</td>
</tr>
</tbody>
</table>
<p>A tool result is shortened by keeping a head, a tail and a marker with the number of missing characters. The tool call and its result keep their ids and their order. A turn that alone exceeds the working budget is still kept; <code>/context</code> and <code>action:"stats"</code> report <code>OVER CAP</code> and the policy asks the model to fold sooner.</p>
<p>In the append layout <code>memoryTokens</code> and <code>workingTokens</code> form one shared pool. When the rendered checkpoint, log and turns exceed the pool, the state note says compaction is due and lists the turns that will leave. The fold waits for the next prompt — the current turn keeps its full context, and the model is expected to write what matters from the leaving turns into memory first — or runs sooner on <code>action:"compact"</code>. It then keeps the newest <code>compactKeepTokens</code> of turns and archives the rest with their raw messages.</p>
<p>When the host reports a model context size, the plugin also warns when memory plus working would exceed 90% of it. It does not silently shrink either side.</p>
</section>
<section id="profiles">
<h2>Profiles</h2>
<p>A profile is a named bundle of the session-level settings - the budgets above, the erosion, the archive bounds, <code>contextLayout</code>, <code>refs</code> and <code>charsPerToken</code> - defined in the same <code>~/.config/opencode/mega-smart-context.json</code>. It applies to one session at a time and never covers the install keys: <code>enabled</code>, <code>subagents</code>, <code>manualCommand</code>, <code>updateCheck</code>, <code>sidebar</code> and <code>debug</code> cannot be set by a profile.</p>
<p>A session runs on the first of: a manual pin, a <code>modelProfiles</code> entry for the model in use (<code>provider/model#variant</code>, then <code>provider/model</code>, then a bare model id), <code>defaultProfile</code>, or the base config. A manual pin stays in force until the user picks <strong>auto</strong>; changing the model does not clear it. Choosing a profile changes the real caps from the next pass, and <code>/context</code>, the status dialog, the sidebar and the panel all report the profile in force with the caps it sets.</p>
<p>The block shows <code>profile lean · auto</code> (or <code>pinned</code>/<code>default</code>/<code>base</code>) under its header and carries a <strong>[profile]</strong> target; the dialog offers <strong>Switch profile…</strong> with <code>auto</code>, <code>base</code> and every named profile; the panel shows the profile and model read-only. <code>/context profile</code> prints the inventory and <code>/context profile auto|base|<name></code> sets the pin without a TUI. A pin that names a profile the config no longer defines leaves the session on the base and says so.</p>
</section>
<section id="eviction-and-the-archive">
<h2>Eviction and the archive</h2>
<p>A turn that leaves the working window becomes <strong>pending</strong>. The model sees it under "Pending eviction" and chooses one of:</p>
<ul>
<li><code>archive { turn, gist, keepRaw? }</code> - store a one-line gist, and optionally the raw messages, in the cold archive;
</li>
<li><code>purge { turn }</code> - discard it permanently;
</li>
<li>do nothing.
</li>
</ul>
<p>With <code>autoArchive</code> on (the default), an unhandled pending turn is archived after <code>evictionLead</code> new user turns, under a mechanical gist (120 characters from the head of its user message, the last 40, and its tools) and with its raw messages kept. The model can purge it later. With <code>autoArchive</code> off, an unhandled turn is dropped when the lead expires.</p>
<p>A pending turn is readable before it is archived: <code>expand</code> resolves a turn id in the archive first and then in the eviction queue, and says when the raw came from the queue. <code>archive</code> without <code>keepRaw:true</code> reports that the raw was discarded and that <code>expand</code> will now return only the gist.</p>
<p>The archive is cold storage, not a second working set. <code>smart_context</code> with <code>action:"recall"</code> refuses unless the call includes <code>lost:true</code>; without it, the tool returns an instruction instead of results. <code>recall</code> matches every term of the query against the gist and the whole rendered turn, and each match carries short snippets with the character offset they sit at. <code>expand { turn }</code> returns the raw turn in pages of <code>expandDigestChars</code> characters (clamped by <code>maxResultChars</code>), ending with the exact range and <code>continue with offset:N</code> or <code>end of turn</code>; a negative <code>offset</code> counts from the end. <code>mode:"outline"</code> lists each part of the turn with its offset and size instead, which is how a reader finds the page worth opening. Without raw messages, <code>expand</code> returns the gist and says it is gist only. The archive is capped by <code>archiveMaxTurns</code> and <code>archiveMaxChars</code>, newest wins.</p>
<p>A delegate can read the archive of the session that spawned it: <code>recall</code> and <code>expand</code> accept <code>from:"parent"</code> (on by default, <code>parentArchive:false</code> turns it off). The field is read-only - every writing action refuses it - and the schema offers no other value. A delegated read ends by naming the reply budget: the caller keeps at most <code>maxResultChars</code> characters of the child's reply, so a long report must be written to a file and cited rather than returned.</p>
</section>
<section id="subagents">
<h2>Subagents</h2>
<p>Every session - top-level or child - has its own memory, working window, pending turns and archive, keyed by session id. A child is detected by <code>parentID</code>. There is no inheritance in either direction; the only write bridge is the normal tool result when the child finishes, which the parent can fold into its own memory. The one read bridge is explicit: a child may pass <code>from:"parent"</code> to <code>recall</code> or <code>expand</code> to search the spawning session's archive, which it cannot write.</p>
<p><code>subagents: true</code> (the default) applies the same transform to child sessions. <code>subagents: false</code> leaves child sessions untouched and passes their requests through unchanged.</p>
</section>
<section id="stored-state">
<h2>Stored state</h2>
<p>Each session's memory, pinned host notices, retired notices, pending turns and archive live in OpenCode's plugin storage, keyed by session id, and survive a restart. An append-layout record also keeps its checkpoint, its accepted update log, the first turn of the current era and a pending compaction mark. Deleting a session at <code>/sessions</code> does not notify the plugin, so the record would outlive it; on the next start the plugin asks the host whether each record's session still exists and removes the ones that are gone. A lookup that fails for any other reason keeps the record, and storage is shared by every project, so a record belonging to another project is left for that project's instance. The archive and the transcript text inside it are reclaimed when the record is removed.</p>
</section>
<section id="compaction">
<h2>Compaction</h2>
<p>When the host asks for a checkpoint summary, the plugin returns the rendered memory document and skips the host's summarizer. If memory is empty, it declines and lets the host summarize; returning an empty block would erase the checkpoint in the name of owning it. The summary is the same block the model reads, so it too carries no live counters.</p>
<p>In the append layout there is a second, plugin-owned checkpoint: <code>smart_context { action:"compact" }</code> folds the update log into the checkpoint immediately, and a full shared pool raises a "compaction due" line that lists the turns about to leave. The due mark is a commit window: the fold waits for the next prompt so the model can write what matters into memory first, and a routine compact is still a loss - it moves the checkpoint and makes the provider re-read it, so the tool description reserves it for a due note. The fold keeps the newest <code>compactKeepTokens</code> of turns and archives the rest immediately, raw kept, rather than leaving them in a pending queue. With <code>rebuildOnCompaction</code> on, the fold also rebuilds the retained tail's bytes: completed-turn reasoning is dropped, a successful write/edit text result becomes <code><path> ok</code>, a long successful shell output keeps its last 20 lines, and error results, content/json shapes, user text and the current turn are untouched; <code>rebuildSaved</code> records the characters removed. The host hook still returns the merged document.</p>
</section>
<section id="undo">
<h2>Undo</h2>
<p><code>/undo</code> in the terminal reverts the latest user message (or an earlier one) and the work that followed it: OpenCode stages the rollback, <code>/redo</code> cancels it, and the next prompt commits it by deleting the transcript from the boundary message onward. This plugin follows that commit. When the host emits <code>session.revert.committed</code>, the session record is rolled back on the next context pass: memory written in the undone turn is undone (the tool keeps an inverse journal of previous values), notices the model retired during it are pinned again, turns it purged are restored, pending turns created or auto-archived during it are dropped or pulled back, and the undone turns leave <code>seenTurns</code>, the archive and the pass history.</p>
<p>What the rollback cannot restore is stated so nothing is guessed at: an archive entry the caps trimmed, a pending turn whose raw messages are gone, and writes from turns older than the journal (the last eight turns, newest kept) are not reversible; <code>/context</code> reports <code>last undo</code> with a <code>not restorable</code> count when any applied. The memory block carries a <code>## Undo</code> section for the turn after a rollback so the model distrusts its own pre-undo writes, and <code>/context</code> adds <code>last undo</code> and <code>undo journal</code> lines. A host without an event bus, and a transcript shortened by compaction, roll nothing back.</p>
</section>
<section id="feature-map-references">
<h2>Feature-map references</h2>
<p><code>smart_context { action:"ref", page, section, gist }</code> stores a pointer plus the model's own one-liner. It reads the section from <code>docs/features/<page></code> - the HTML page first, the Markdown page as a fallback - reports the gist and section costs, and tells the model which is shorter. The reference counts toward <code>memoryTokens</code>. A section that cannot be read is reported, but the pointer is still stored.</p>
</section>
<section id="the-update-check">
<h2>The update check</h2>
<p>At most once every 24 hours the terminal half of the plugin compares the version it loaded with this repository's published <code>package.json</code>. When the published number is newer it shows one toast - <code>0.1.22 is available (installed 0.1.21) - git pull && npm run plugin:install</code> - and stays quiet about that release until a newer one exists. Nothing about the check reaches the model: it adds no request part, no policy and no tokens, and every failure is silent. <code>updateCheck: false</code> in the config file stops both the request and the toast. A <em>first</em> install may need a restart before the terminal half is loaded.</p>
</section>
<section id="the-status-dialog">
<h2>The status dialog</h2>
<p>The terminal half registers a palette command, <strong>Context status</strong> (id <code>mega-smart-context.status</code>; the id is the keybind key, and no default binding is claimed). Running it asks the server half for that session's numbers and opens a dialog: memory and working usage against their caps (a long turn is kept past the working cap by design, and the row says so), turns kept and dropped, pending/archive/reference counts, and the host system size when the last pass measured one. The status rows are not selectable, so the selection lands on the actions. A profile row reports the bundle in force (for example <code>profile deep · pinned</code>).</p>
<p><strong>Resume</strong> sends the same cue as <code>/context resume</code> through the host's synthetic channel: no user message, no new turn, and no pending eviction aged. <strong>Purge a turn…</strong> lists the pending and then the archived turns with their ids, asks for confirmation, and removes the chosen one from the record; the transcript is not touched, and the removal is journaled so <code>/undo</code> restores it. The list is re-read before it is shown, so a pass that archived or purged something in the meantime cannot leave a stale entry behind. <strong>Switch profile...</strong> offers <code>auto</code>, <code>base</code> and every named profile with its overrides; the choice is saved on that session only and applies from the next pass.</p>
<p>The numbers cross a process boundary: the terminal half's durable store is its own JSON file, not the server's KV, so the dialog reads the record over the host's plugin RPC (<code>stats</code>, <code>purge</code> and <code>notice</code>). The pull happens when the command runs, never from a render path. With no open session the dialog says to open one; on a host without the RPC bridge, and on an RPC error, it says which of the two is missing instead of throwing. <code>updateCheck:false</code> does not remove the command.</p>
</section>
<section id="the-sidebar-block">
<h2>The sidebar block</h2>
<p>The terminal half also appends to <code>sidebar.content</code> - last inside the sidebar's scrollable list, not the panel's bottom edge - and draws the same reply as a short block: a header of the plugin's name with its version against the block's right edge, a memory bar, a working-window bar, turns kept and dropped, pending/archive/reference counts, and how old the numbers are (<code>measured 6m ago</code>). The age line took the slot the host system size used to occupy: a size outside this plugin's budget is not something the glance can act on, while an old number is. Each bar is eighteen cells long and its numbers ride the same right edge as the version, so a wider sidebar widens the gap rather than the bar. The two bars' numbers are right-aligned to a shared column, and an over-cap working line carries a <code>*</code> in the gutter before its value. The block's title is bold, matching the host's own section headers - the panel uses the same bold for its header and section titles - and the numbers stay plain. Gists, notice text and the archive list are deliberately absent: the block never grows with the session, and the dialog is where those are asked for.</p>
<p>Under the header the block names the profile in force (<code>profile lean · auto</code>, <code>pinned</code> for a manual pick), and under the numbers are four words that act: <strong>[status]</strong> opens the dialog, <strong>[profile]</strong> opens the profile picker, <strong>[resume]</strong> asks and then sends the resume cue, and <strong>[purge]</strong> opens the purge list and its confirmation. Mouse clicks are optional: every action is still reachable from the palette command.</p>
<p>The block renders from an ephemeral per-session mirror that a pull fills: once when the session is shown, once after each idle pass, and again after a purge. At most one pull per session is in flight, a pull inside fifteen seconds is skipped, and the mirror keeps the thirty-two most recently read sessions. The render path never calls the RPC. Every pull reads the session record from storage rather than from the answering instance's cache, and a write refuses to overwrite a record another instance wrote later, so a block cannot paint a number that a different instance has already replaced; when a write is refused twice in a row, the action reports the conflict instead of silently doing nothing. A host without the slot API or without the JSX runtime keeps the dialog and reports <code>sidebar: unavailable</code> in it; <code>sidebar:false</code> turns the block off but leaves the panel's shared mirror available.</p>
</section>
<section id="the-session-panel">
<h2>The session panel</h2>
<p>A second palette command, <strong>Context panel</strong> (id <code>mega-smart-context.panel</code>, unbound by default), opens the full report in the host's session panel. It appends to <code>session.panel</code> and draws only for its own panel name, so it coexists with other plugins' panels. The report is everything the block leaves out: both budgets, the request's own system-prompt size when the last pass measured one, the goal, a sparkline of the last forty passes, every pending and archived turn with its size and a <strong>[purge]</strong> action, the pinned host notices with <strong>[retire]</strong> on the superseded ones, and the undo state. The newest notice is the live instruction and offers no retire action; the server refuses it anyway.</p>
<p>Clicking a purge or a retire asks first, then writes through the same RPC as the dialog and refreshes the mirror. The footer offers <strong>[refresh]</strong>, <strong>[resume]</strong>, <strong>[dialog]</strong> (the status select) and <strong>[close]</strong>. Like the block, the panel renders only from the mirror and never pulls from a render path. A host without the panel API or the JSX runtime reports <code>panel: unavailable</code> in the dialog; the dialog and the block still work.</p>
</section>
<section id="the-model-surface">
<h2>The model surface</h2>
<p><code>smart_context</code> actions:</p>
<table>
<thead>
<tr>
<th>Action</th>
<th>Effect</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>read { key? }</code></td>
<td>print one memory key, or the whole document</td>
</tr>
<tr>
<td><code>patch { patch }</code></td>
<td>merge a patch; maps merge, lists replace, <code>null</code> resets a key or deletes one map entry</td>
</tr>
<tr>
<td><code>stats</code></td>
<td>memory, working, pending and archive usage; in append mode it adds the update count and the shared pool</td>
</tr>
<tr>
<td><code>compact</code></td>
<td>fold the append-only update log into a new checkpoint and reset the window; refused when <code>contextLayout</code> is <code>"snapshot"</code>. Not routine: it rewrites the checkpoint and costs the provider prefix cache</td>
</tr>
<tr>
<td><code>ref { page, section, gist }</code></td>
<td>store a feature-map pointer and compare costs</td>
</tr>
<tr>
<td><code>archive { turn, gist, keepRaw? }</code></td>
<td>move a pending turn to the archive</td>
</tr>
<tr>
<td><code>purge { turn? | query? }</code></td>
<td>delete a pending or archived turn, or matching entries</td>
</tr>
<tr>
<td><code>recall { query, lost:true, limit?, from? }</code></td>
<td>search the cold archive; refuses without <code>lost:true</code>. Every term must match, and each match carries snippets with their char offsets. <code>from:"parent"</code> searches the spawning session's archive instead, read-only, and names the caller's reply budget</td>
</tr>
<tr>
<td><code>expand { turn, mode?, offset?, limit?, from? }</code></td>
<td>read an archived turn back as one honest page ending in its char range and how to continue; <code>mode:"outline"</code> lists each part with its offset and size. <code>from:"parent"</code> reads the spawning session's</td>
</tr>
<tr>
<td><code>notice { remove? }</code></td>
<td>list the pinned host notices - a mode switch or an output-limit nudge - or retire a superseded one by id; the newest is refused, and a retirement holds until the host emits that text again under a new id</td>
</tr>
</tbody>
</table>
<p>The <code>/context</code> command prints the same state for the user:</p>
<table>
<thead>
<tr>
<th>Command</th>
<th>Effect</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>/context</code> or <code>/context status</code></td>
<td>the product name and the loaded build's version on its first line, then memory, working, pending, archive, goal, the host system size and how old the numbers are</td>
</tr>
<tr>
<td><code>/context now</code></td>
<td>archive every pending turn now</td>
</tr>
<tr>
<td><code>/context resume</code></td>
<td>start a model turn with the plugin's resume cue through the host's synthetic channel - no user message, no new turn, and no pending eviction aged</td>
</tr>
<tr>
<td><code>/context memory <key></code></td>
<td>print one memory key</td>
</tr>
<tr>
<td><code>/context recall <query></code></td>
<td>search the archive as the user</td>
</tr>
<tr>
<td><code>/context purge <turn></code></td>
<td>delete a pending or archived turn</td>
</tr>
</tbody>
</table>
<p><code>/context resume</code> is the one command that starts a model turn instead of printing: it admits <code>RESUMED_TEXT</code> as a synthetic user message with <code>resume: true</code>, and the context pass classifies that sentence as a cue, so it stays in the window, counts toward the turn it continues, and ages no pending eviction.</p>
<p>The same output reports a rollback when one has been applied - <code>last undo: before <turn> · N memory key(s) restored, M turn(s) dropped</code>, with a <code>not restorable</code> count when the journal could only do part of the job - and the journal itself as <code>undo journal: N turn(s), oldest <turn> · /undo rolls these back</code>.</p>
<p>The version is <code>MAJOR.MINOR.PATCH</code>: MAJOR.MINOR is the released line, and PATCH is the number of commits since the base recorded in <code>package.json</code>, so it advances with every commit and the README version badge follows the same field. What <code>/context</code> prints is the loaded build's own version, which lags the repository until the install is re-synced.</p>
</section>
<section id="settings">
<h2>Settings</h2>
<p>Every setting is read from four layers, most specific last: built-in defaults, the package <code>options.json</code>, the plugin <code>options</code>, and <code>~/.config/opencode/mega-smart-context.json</code>. The user file is created with every default on first run and never overwritten. A source replaces only the keys it sets. An unknown key or a wrong type is an error: the plugin refuses to load rather than silently keeping a default the user believes they replaced.</p>
<table>
<thead>
<tr>
<th>Setting</th>
<th>Default</th>
<th>Range</th>
<th>Where</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>enabled</code></td>
<td><code>true</code></td>
<td>bool - master switch</td>
<td>config file</td>
</tr>
<tr>
<td><code>contextLayout</code></td>
<td><code>"snapshot"</code></td>
<td><code>"snapshot"</code> or <code>"append"</code> - rewrite one memory block, or keep a checkpoint and append deltas</td>
<td>config file</td>
</tr>
<tr>
<td><code>memoryTokens</code></td>
<td><code>20000</code></td>
<td>>= 1000 - memory cap, estimated</td>
<td>config file</td>
</tr>
<tr>
<td><code>workingTokens</code></td>
<td><code>20000</code></td>
<td>>= 500 - working window cap, estimated</td>
<td>config file</td>
</tr>
<tr>
<td><code>charsPerToken</code></td>
<td><code>4</code></td>
<td>2..8 - estimation divisor</td>
<td>config file</td>
</tr>
<tr>
<td><code>subagents</code></td>
<td><code>true</code></td>
<td>bool - manage child sessions independently</td>
<td>config file</td>
</tr>
<tr>
<td><code>evictionLead</code></td>
<td><code>1</code></td>
<td>0..20 - new user turns a pending turn is shown before auto-archive/drop</td>
<td>config file</td>
</tr>
<tr>
<td><code>autoArchive</code></td>
<td><code>true</code></td>
<td>bool - archive unhandled evictions</td>
<td>config file</td>
</tr>
<tr>
<td><code>archiveMaxTurns</code></td>
<td><code>200</code></td>
<td>0..5000 - archived turns per session</td>
<td>config file</td>
</tr>
<tr>
<td><code>archiveMaxChars</code></td>
<td><code>400000</code></td>
<td>>= 10000 - archived characters per session</td>
<td>config file</td>
</tr>
<tr>
<td><code>parentArchive</code></td>
<td><code>true</code></td>
<td>bool - allow <code>from:"parent"</code> on <code>recall</code>/<code>expand</code></td>
<td>config file</td>
</tr>
<tr>
<td><code>expandDigestChars</code></td>
<td><code>4000</code></td>
<td>>= 500 - characters per <code>expand</code> page, clamped by <code>maxResultChars</code></td>
<td>config file</td>
</tr>
<tr>
<td><code>refs</code></td>
<td><code>true</code></td>
<td>bool - offer the <code>ref</code> action</td>
<td>config file</td>
</tr>
<tr>
<td><code>maxResultChars</code></td>
<td><code>4000</code></td>
<td>>= 200 - per-result erosion limit</td>
<td>config file</td>
</tr>
<tr>
<td><code>manualCommand</code></td>
<td><code>true</code></td>
<td>bool - register <code>/context</code></td>
<td>config file</td>
</tr>
<tr>
<td><code>updateCheck</code></td>
<td><code>true</code></td>
<td>bool - ask GitHub once a day for a newer published version and toast once per release; no request and no toast when false</td>
<td>config file</td>
</tr>
<tr>
<td><code>sidebar</code></td>
<td><code>true</code></td>
<td>bool - draw the block in the terminal's sidebar; when false its claim is skipped but the panel still shares the mirror</td>
<td>config file</td>
</tr>
<tr>
<td><code>debug</code></td>
<td><code>false</code></td>
<td>bool - log pass decisions to stderr</td>
<td>config file</td>
</tr>
<tr>
<td><code>profiles</code></td>
<td><code>{}</code></td>
<td>object - named bundles of the session keys (budgets, erosion, archive bounds, <code>refs</code>, <code>charsPerToken</code>); the install keys are refused</td>
<td>config file</td>
</tr>
<tr>
<td><code>modelProfiles</code></td>
<td><code>{}</code></td>
<td>object - <code>provider/model#variant</code>, <code>provider/model</code> or a bare model id to a profile name; auto selects it</td>
<td>config file</td>
</tr>
<tr>
<td><code>defaultProfile</code></td>
<td><code>""</code></td>
<td>string - the profile an auto session falls back to; empty runs the base config</td>
<td>config file</td>
</tr>
</tbody>
</table>
<p>The environment overrides are for tests and unusual installs: <code>MEGA_SMART_CONTEXT_CONFIG</code> points at a different user file, and <code>MEGA_SMART_CONTEXT_NO_USER_CONFIG=1</code> skips the user layer entirely.</p>
</section>
<section id="out-of-scope">
<h2>Out of scope</h2>
<ul>
<li>No cross-session or shared memory.
</li>
<li>No automatic semantic summarization, file seeding or plan seeding.
</li>
<li>No protected first user message.
</li>
<li>No exact tokenizer or per-model token accounting; the caps are estimates.
</li>
<li>No transcript edits; a checkpoint is written by the host's compaction hook or by the append layout's <code>compact</code> action, and the plugin owns the host checkpoint only when memory is non-empty.
</li>
</ul>
</section>
</main>
<footer class="doc-footer">
<p>Generated by <code>html-as-doc</code> from <code>docs/SPEC.md</code>.</p>
<p>The Markdown file is a pointer; this HTML page is the source of truth. Edit it directly and re-run <code>html-docs.mjs verify</code>.</p>
</footer>
</body>
</html>