opencode-self-improvement 0.14.15 → 0.14.17
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/README.md +12 -8
- package/package.json +1 -1
- package/src/gates.ts +5 -0
- package/src/index.ts +137 -28
- package/src/inject.ts +9 -3
- package/src/state.ts +35 -0
- package/src/status.ts +19 -2
package/README.md
CHANGED
|
@@ -99,20 +99,24 @@ Injection, recall, the frontier block, compaction, `memory_forget` and decay onl
|
|
|
99
99
|
|
|
100
100
|
## Token cost and caching
|
|
101
101
|
|
|
102
|
-
- **
|
|
102
|
+
- **Section-frozen injection.** The whole memory section — standing digest, open-thread frontier, relevance block — is computed once per epoch and delivered byte-identically until something the model actually needs changes. The epoch's authority is the **rendered bytes**, not the store fingerprint: a promoted row that changes nothing visible costs no cache bust.
|
|
103
|
+
- **A session never pays for bytes it is not riding.** A memory *you* saved in this session is a fact you already produced — it is in your own transcript — so it never busts your cache. The test is not "did the store change" but "would the frozen bytes still have been produced from the same inputs, minus the rows this session authored since": a correction, blocklisting, redaction or supersession of a row you are riding, and anything another session, the viewer or an import wrote, all still land on your next request.
|
|
103
104
|
- **Two-concept threshold.** A free-text prompt must share at least two distinct concepts with a memory for it to be injected; keyword-length queries (one or two words) need only one. Silence on single-word coincidences is deliberate; `memory_recall` still reaches them on the pull path.
|
|
104
105
|
- **Hard budgets.** Relevance block and each pull are capped at `injectBudget` characters, the frontier at `frontierBudget`, trimmed at whole-memory boundaries.
|
|
106
|
+
- **Nothing volatile on the cached prefix.** The standing digest carries no row count and no latest timestamp. Both used to ride the very front of the system prompt, so every saved memory rewrote the prefix and made the next request re-bill the whole conversation; the exact numbers now live where they are free — the footer badge, `/memory`, `memory_status`, the viewer.
|
|
105
107
|
- **Evidence is never injected**, and the standing system digest is two lines.
|
|
106
108
|
- **Measured, not claimed.** The plugin reads each turn's `tokens.cache` accounting and displays the actual hit rate next to the badge.
|
|
107
109
|
|
|
108
|
-
Deterministic workload (50 memories, 20 prompts, 3 mid-session store writes) through the plugin's real injection code:
|
|
110
|
+
Deterministic workload (50 memories, 20 prompts, 3 mid-session store writes made *by the measured session*) through the plugin's real injection code. Every column is measured on the full memory section — the bytes a request actually sends — because prompt caching is a property of those bytes:
|
|
109
111
|
|
|
110
|
-
| Policy | Recomputes | Injected chars (20 turns) | Avg/turn | Worst
|
|
111
|
-
| --- | ---: | ---: | ---: | ---: |
|
|
112
|
-
| A — recompute per prompt, uncapped | 20 |
|
|
113
|
-
| B —
|
|
112
|
+
| Policy | Recomputes | Cache busts | Injected chars (20 turns) | Avg/turn | Worst section |
|
|
113
|
+
| --- | ---: | ---: | ---: | ---: | ---: |
|
|
114
|
+
| A — recompute per prompt, uncapped (naive) | 20 | 19 | 60996 | 3049.8 | 3404 |
|
|
115
|
+
| B — block frozen on store fingerprint, digest rebuilt per turn | 4 | 3 | 55478 | 2773.9 | 2867 |
|
|
116
|
+
| C — section frozen on rendered bytes | 4 | 3 | 55258 | 2762.9 | 2856 |
|
|
117
|
+
| D — C + riding bytes (shipped) | 1 | 0 | 53500 | 2675.0 | 2675 |
|
|
114
118
|
|
|
115
|
-
|
|
119
|
+
A "cache bust" is a turn whose memory-section bytes differ from the turn before — each one re-bills the entire conversation as fresh input. All three synthetic writes change what the session is shown, so B and C each pay for them; D pays nothing, because the session wrote them itself. What D still pays for is a riding row being corrected, blocklisted or redacted, or another session writing a row — that half of the contract is pinned by `test/epoch.test.ts` rather than by this table, since a benchmark that only writes never exercises it. D also injects 12.3% fewer characters than the naive policy — the denominator here is the whole section, not the relevance block alone, so it is not comparable with the block-only figure this README quoted before. Reproduce (byte-identical output):
|
|
116
120
|
|
|
117
121
|
```sh
|
|
118
122
|
bun run bench
|
|
@@ -229,7 +233,7 @@ Same data behind each one (`memory_status`; no model call).
|
|
|
229
233
|
**Terminal (opencode CLI)** — the plugin ships a TUI half (`@opencode/plugin/tui`) that loads automatically:
|
|
230
234
|
|
|
231
235
|
- **Footer badge** — `● mem 1157/1200c · cache 96%`: the injected block against its budget, plus the measured session prompt-cache hit rate. The dot is green (stable and warm), yellow (recent recompute, or 50–90% reads) or red (last turn served almost nothing from cache); `—` until the first assistant turn.
|
|
232
|
-
- **`/memory`** — session panel: **CONTEXT** (chars and estimated tokens riding now, % of budget, requests this epoch has ridden, session totals, abstentions), **CACHE** (busts this session and the measured cache-served share of prompt tokens), **INJECTED BLOCK** (the verbatim block, or an explicit abstention), **RECENT BLOCKED WRITES** (with gate reasons), **STORE** (active / superseded / open / scopes, plus `malformed` when a row's `ts` is not a valid ISO instant — those rows are skipped by every reader). Keys: `r` refresh, `f` fullscreen.
|
|
236
|
+
- **`/memory`** — session panel: **CONTEXT** (chars and estimated tokens riding now, % of budget, the full memory section riding the prompt — digest + frontier + block — requests this epoch has ridden, session totals, abstentions), **CACHE** (busts this session and the measured cache-served share of prompt tokens), **INJECTED BLOCK** (the verbatim block, or an explicit abstention), **RECENT BLOCKED WRITES** (with gate reasons), **STORE** (active / superseded / open / scopes, plus `malformed` when a row's `ts` is not a valid ISO instant — those rows are skipped by every reader). Keys: `r` refresh, `f` fullscreen.
|
|
233
237
|
- **Block toast** when a write is refused (`"notifyBlocked": false` to silence).
|
|
234
238
|
|
|
235
239
|
**Desktop / web / IDE** — the terminal slots do not exist there, so use the self-installed **`/memory-report`** chat command: the same sections rendered in the conversation.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.14.
|
|
3
|
+
"version": "0.14.17",
|
|
4
4
|
"description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
|
|
5
5
|
"main": "index.ts",
|
|
6
6
|
"exports": {
|
package/src/gates.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
type SupersedeFields,
|
|
16
16
|
} from "./memory.ts";
|
|
17
17
|
import { chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
|
|
18
|
+
import { noteAuthored } from "./state.ts";
|
|
18
19
|
import { flattenMemoryText } from "./sanitize.ts";
|
|
19
20
|
import { containsSecret, redactSecrets } from "./secrets.ts";
|
|
20
21
|
import { readerForSession } from "./memory.ts";
|
|
@@ -662,6 +663,10 @@ export async function runWriteGate(
|
|
|
662
663
|
// The write carries the CALLER's session, not whatever current says after
|
|
663
664
|
// the gate's own awaits - capture's stamp must follow the captured session.
|
|
664
665
|
const ts = await appendMemory({ ...candidate, sessionID: ctx.sessionID });
|
|
666
|
+
// #165: remember who made this row, so the writing session is not billed a
|
|
667
|
+
// prompt-cache bust to be shown its own thought. Only promoted writes are
|
|
668
|
+
// attributed — a blocked candidate created nothing.
|
|
669
|
+
noteAuthored(ctx.sessionID, ts);
|
|
665
670
|
await rec("write_promoted", {
|
|
666
671
|
gate: 4,
|
|
667
672
|
op: "write",
|
package/src/index.ts
CHANGED
|
@@ -81,7 +81,7 @@ import {
|
|
|
81
81
|
markTurn,
|
|
82
82
|
onCompacting,
|
|
83
83
|
} from "./triggers.ts";
|
|
84
|
-
import { getCurrent, setCurrent } from "./state.ts";
|
|
84
|
+
import { authoredFor, getCurrent, setCurrent } from "./state.ts";
|
|
85
85
|
import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir, sessionDirFirm, bindSessionProvisional, writeTarget } from "./repokey.ts";
|
|
86
86
|
import { parseLine, readLines } from "./logfmt.ts";
|
|
87
87
|
import { buildCapturePrompt, flattenTranscript, lagSince, parseCandidates, parseModelRef } from "./capture.ts";
|
|
@@ -1066,15 +1066,44 @@ const impl = {
|
|
|
1066
1066
|
}));
|
|
1067
1067
|
});
|
|
1068
1068
|
|
|
1069
|
-
// Per-session frozen injection epochs: the
|
|
1070
|
-
//
|
|
1071
|
-
// tracked session, when injectable rows
|
|
1072
|
-
// the prompt/context/compaction hooks)
|
|
1073
|
-
//
|
|
1074
|
-
//
|
|
1069
|
+
// Per-session frozen injection epochs: the whole memory section (digest +
|
|
1070
|
+
// frontier + relevance) plus the store fingerprint it was rendered from.
|
|
1071
|
+
// Recomputed on the first prompt of a tracked session, when injectable rows
|
|
1072
|
+
// change, or after a compaction (see the prompt/context/compaction hooks).
|
|
1073
|
+
// The RENDERED BYTES, not the fingerprint, decide whether the epoch moved
|
|
1074
|
+
// (issue #162): a write that changes nothing the model is shown must not
|
|
1075
|
+
// cost the next request a full re-prefill. And a pure addition the session
|
|
1076
|
+
// wrote itself does not move them either (#165) — see refreshEpoch. The
|
|
1077
|
+
// shared LRU below may evict the whole session state; a later prompt starts
|
|
1078
|
+
// it fresh.
|
|
1075
1079
|
const epoch = new Map<
|
|
1076
1080
|
string,
|
|
1077
|
-
{
|
|
1081
|
+
{
|
|
1082
|
+
version: string;
|
|
1083
|
+
/** Frozen standing digest + frontier + convergence parts, in push order. */
|
|
1084
|
+
parts: string[];
|
|
1085
|
+
/** The budgeted relevance block the surfaces report against injectBudget. */
|
|
1086
|
+
block: string;
|
|
1087
|
+
/** Comparison key: every byte of the memory section, joined. */
|
|
1088
|
+
prefix: string;
|
|
1089
|
+
/**
|
|
1090
|
+
* Rows THIS session had already authored when these bytes were rendered
|
|
1091
|
+
* (#165). The riding-bytes test subtracts everything authored after this
|
|
1092
|
+
* snapshot; if what remains renders identically, the whole difference is
|
|
1093
|
+
* the session's own additions and the bytes keep riding.
|
|
1094
|
+
*/
|
|
1095
|
+
ownRows: Set<string>;
|
|
1096
|
+
/**
|
|
1097
|
+
* The prompt these bytes were scored against. The counterfactual below
|
|
1098
|
+
* has to re-score the SAME inputs, or a topic change between the freeze
|
|
1099
|
+
* and the next write would look like a content change — and the epoch
|
|
1100
|
+
* would pay for a refresh it deliberately refuses to do on a prompt.
|
|
1101
|
+
*/
|
|
1102
|
+
prompt: string;
|
|
1103
|
+
at: string;
|
|
1104
|
+
reason: "first" | "store_changed";
|
|
1105
|
+
refs: MemoryRefs;
|
|
1106
|
+
}
|
|
1078
1107
|
>();
|
|
1079
1108
|
// Latest user prompt per tracked session. A changed store is re-scored
|
|
1080
1109
|
// against it even when the change happened during a tool loop with no new
|
|
@@ -1121,6 +1150,7 @@ const impl = {
|
|
|
1121
1150
|
recomputes: epochRecomputes,
|
|
1122
1151
|
block: ep.block,
|
|
1123
1152
|
blockChars: ep.block.length,
|
|
1153
|
+
sectionChars: ep.prefix.length,
|
|
1124
1154
|
budget,
|
|
1125
1155
|
store: {
|
|
1126
1156
|
active: act.length,
|
|
@@ -1161,32 +1191,101 @@ const impl = {
|
|
|
1161
1191
|
for (const m of rows) for (const t of sharedTerms(query, m)) if (!terms.includes(t)) terms.push(t);
|
|
1162
1192
|
await recordHits(src, sid, rows, terms);
|
|
1163
1193
|
};
|
|
1194
|
+
// Render the COMPLETE memory section for one request: the standing digest,
|
|
1195
|
+
// the open-thread frontier and the convergence line (all from systemDigest),
|
|
1196
|
+
// followed by this epoch's relevance block. The parts are exactly what gets
|
|
1197
|
+
// pushed onto `event.system`; their join is the byte key the epoch compares
|
|
1198
|
+
// against, so "did the cache-critical prefix change?" is answered by the
|
|
1199
|
+
// bytes the model would actually see and never by a proxy (issue #162).
|
|
1200
|
+
const buildMemorySection = async (
|
|
1201
|
+
sid: string | undefined,
|
|
1202
|
+
mems: Memory[],
|
|
1203
|
+
promptOverride?: string,
|
|
1204
|
+
): Promise<{ parts: string[]; block: string; prefix: string; rode: Memory[]; refs: MemoryRefs }> => {
|
|
1205
|
+
const parts: string[] = [];
|
|
1206
|
+
await systemDigest(
|
|
1207
|
+
{ sessionID: sid },
|
|
1208
|
+
{ system: parts },
|
|
1209
|
+
{ rows: mems, frontierBudget: openBudget },
|
|
1210
|
+
);
|
|
1211
|
+
const prompt = promptOverride ?? (sid === undefined ? "" : latestPrompt.get(sid) ?? "");
|
|
1212
|
+
// Widen the candidate pool, then cap: the budget decides what rides.
|
|
1213
|
+
const sel = await selectRelevant(prompt, 5, mems, await useSignals());
|
|
1214
|
+
const block = sel.block ? capToBudget(sel.block, budget) : "";
|
|
1215
|
+
// Refs the ACTUALLY-injected rows assert (paths + commands), the join key
|
|
1216
|
+
// for attribution. Derived from the budget-surviving rows, not the wider
|
|
1217
|
+
// candidate pool — crediting paths the model never saw would overclaim.
|
|
1218
|
+
const rode = injectedRows(block, sel.selected);
|
|
1219
|
+
const prefix = [...parts, block].join("\u0000");
|
|
1220
|
+
return { parts, block, prefix, rode, refs: deriveMemoryRefs(rode) };
|
|
1221
|
+
};
|
|
1164
1222
|
const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
|
|
1165
1223
|
if (!latestPrompt.has(sid)) return;
|
|
1166
1224
|
const mems = rows ?? (await injectableRows(sid));
|
|
1167
1225
|
const version = await storeVersion(mems);
|
|
1168
1226
|
const cached = epoch.get(sid);
|
|
1227
|
+
// Cheap pre-check: no injectable row moved, so the frozen bytes still
|
|
1228
|
+
// stand. Skips re-scoring and the use-ledger write on ordinary turns.
|
|
1169
1229
|
if (cached?.version === version) return;
|
|
1230
|
+
const built = await buildMemorySection(sid, mems);
|
|
1231
|
+
// The store moved. A write that changes nothing RENDERED — a row that is
|
|
1232
|
+
// not relevant to this prompt, supersession elsewhere, a scope the reader
|
|
1233
|
+
// never sees rendered identically — must not cost this session a prompt
|
|
1234
|
+
// cache. Adopt the new fingerprint, keep riding the same bytes, emit
|
|
1235
|
+
// nothing: an invalidation has to mean bytes actually moved.
|
|
1236
|
+
if (cached && cached.prefix === built.prefix) {
|
|
1237
|
+
epoch.set(sid, { ...cached, version });
|
|
1238
|
+
return;
|
|
1239
|
+
}
|
|
1240
|
+
// Riding bytes (#165): a pure addition this session wrote itself is
|
|
1241
|
+
// information it already has — the model produced it, it is in the
|
|
1242
|
+
// transcript. Re-render the section with every row authored SINCE these
|
|
1243
|
+
// bytes were frozen taken back out: if it comes back byte-identical, the
|
|
1244
|
+
// entire difference is attributable to the session's own additions and
|
|
1245
|
+
// the frozen bytes keep riding. Everything else survives into that render
|
|
1246
|
+
// and still busts — a riding row removed or rewritten (blocklist,
|
|
1247
|
+
// hand-redaction, forget, supersession, decay), another session's row, a
|
|
1248
|
+
// viewer edit, an import, a moved convergence line.
|
|
1249
|
+
if (cached) {
|
|
1250
|
+
const mine = authoredFor(sid);
|
|
1251
|
+
const extra = mems.filter((m) => mine.has(m.ts) && !cached.ownRows.has(m.ts));
|
|
1252
|
+
if (extra.length) {
|
|
1253
|
+
const back = await buildMemorySection(
|
|
1254
|
+
sid,
|
|
1255
|
+
mems.filter((m) => !extra.some((e) => e.ts === m.ts)),
|
|
1256
|
+
cached.prompt,
|
|
1257
|
+
);
|
|
1258
|
+
if (back.prefix === cached.prefix) {
|
|
1259
|
+
epoch.set(sid, { ...cached, version });
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1170
1264
|
const prompt = latestPrompt.get(sid) ?? "";
|
|
1171
|
-
const sel = await selectRelevant(prompt, 5, mems, await useSignals()); // widen candidate pool
|
|
1172
|
-
const block = sel.block ? capToBudget(sel.block, budget) : "";
|
|
1173
|
-
// Refs the ACTUALLY-injected rows assert (paths + commands), the join key
|
|
1174
|
-
// for attribution. Derived from the budget-surviving rows, not the wider
|
|
1175
|
-
// candidate pool — crediting paths the model never saw would overclaim.
|
|
1176
|
-
const rode = injectedRows(block, sel.selected);
|
|
1177
|
-
const refs = deriveMemoryRefs(rode);
|
|
1178
1265
|
// Use ledger (#42): the rows that actually rode the block, credited with
|
|
1179
1266
|
// the terms the prompt and those rows shared (never the prompt itself).
|
|
1180
|
-
|
|
1267
|
+
// Only once the build is ADOPTED — a discarded rebuild must not credit
|
|
1268
|
+
// rows that were already offered under the frozen epoch.
|
|
1269
|
+
await noteHits("inject", sid, built.rode, prompt);
|
|
1181
1270
|
const at = new Date().toISOString();
|
|
1182
1271
|
const reason: "first" | "store_changed" = cached ? "store_changed" : "first";
|
|
1183
|
-
epoch.set(sid, {
|
|
1272
|
+
epoch.set(sid, {
|
|
1273
|
+
version,
|
|
1274
|
+
parts: built.parts,
|
|
1275
|
+
block: built.block,
|
|
1276
|
+
prefix: built.prefix,
|
|
1277
|
+
ownRows: new Set(mems.filter((m) => authoredFor(sid).has(m.ts)).map((m) => m.ts)),
|
|
1278
|
+
prompt,
|
|
1279
|
+
at,
|
|
1280
|
+
reason,
|
|
1281
|
+
refs: built.refs,
|
|
1282
|
+
});
|
|
1184
1283
|
await record(
|
|
1185
1284
|
"epoch_recompute",
|
|
1186
1285
|
{
|
|
1187
1286
|
session: sid,
|
|
1188
1287
|
reason,
|
|
1189
|
-
chars: block.length,
|
|
1288
|
+
chars: built.block.length,
|
|
1190
1289
|
},
|
|
1191
1290
|
false,
|
|
1192
1291
|
);
|
|
@@ -1270,16 +1369,26 @@ const impl = {
|
|
|
1270
1369
|
if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
|
|
1271
1370
|
const mems = await injectableRows(sid);
|
|
1272
1371
|
if (typeof sid === "string") await refreshEpoch(sid, mems);
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
);
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1372
|
+
// Deliver the FROZEN memory section. Every byte pushed onto the system
|
|
1373
|
+
// prompt comes from the epoch, so between busts the provider sees an
|
|
1374
|
+
// identical prefix and serves the conversation from cache (issue #162).
|
|
1375
|
+
// A session with no epoch yet (no prompt recorded, or evicted from the
|
|
1376
|
+
// LRU) still gets the standing digest, built fresh and uncached.
|
|
1377
|
+
const ep = typeof sid === "string" ? epoch.get(sid) : undefined;
|
|
1378
|
+
if (ep) {
|
|
1379
|
+
for (const text of ep.parts) event?.system?.push?.({ type: "text", text });
|
|
1380
|
+
} else {
|
|
1381
|
+
const parts: string[] = [];
|
|
1382
|
+
await systemDigest(
|
|
1383
|
+
{ sessionID: event?.sessionID },
|
|
1384
|
+
{ system: parts },
|
|
1385
|
+
{ rows: mems, frontierBudget: openBudget },
|
|
1386
|
+
);
|
|
1387
|
+
for (const text of parts) event?.system?.push?.({ type: "text", text });
|
|
1388
|
+
}
|
|
1389
|
+
// This epoch's relevance-ranked memory, also on the system channel —
|
|
1390
|
+
// the UI never renders system parts, unlike appended prompt text.
|
|
1391
|
+
const knowledge = ep?.block;
|
|
1283
1392
|
if (knowledge) event?.system?.push?.({ type: "text", text: knowledge });
|
|
1284
1393
|
// Count AT THE INJECTION DECISION so badge/panel numbers match exactly
|
|
1285
1394
|
// what rode this request (a later abort still rode the bytes — known
|
package/src/inject.ts
CHANGED
|
@@ -291,11 +291,17 @@ export async function systemDigest(
|
|
|
291
291
|
// after the loadAll await.
|
|
292
292
|
const mems = opts.rows ?? visibleTo((await loadAll()).filter(isActive), readerFromSid(sid));
|
|
293
293
|
if (!mems.length) return;
|
|
294
|
-
|
|
294
|
+
// CACHE-STABLE BY CONSTRUCTION (issue #162): this line carries no row count
|
|
295
|
+
// and no latest-ts. Both change on every promoted write, and the digest rides
|
|
296
|
+
// the FRONT of the system prompt, so one volatile byte invalidated the whole
|
|
297
|
+
// cached prefix — every memory write cost the next request a full re-prefill.
|
|
298
|
+
// The exact numbers belong on surfaces where they are free and never ride a
|
|
299
|
+
// prompt: the footer badge, /memory, memory_status, the viewer.
|
|
295
300
|
output.system.push(
|
|
296
301
|
"\n## Persistent memory (opencode-self-improvement)\n" +
|
|
297
|
-
|
|
298
|
-
"
|
|
302
|
+
"Durable memories exist for this repository. Check memory_recall BEFORE grepping or " +
|
|
303
|
+
"reading, for build/test/lint commands, decisions, and conventions. Relevant memories " +
|
|
304
|
+
"are also auto-injected when your message matches.",
|
|
299
305
|
);
|
|
300
306
|
|
|
301
307
|
const open = mems
|
package/src/state.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Per-session in-memory state shared by the hooks and the gate pipeline.
|
|
2
2
|
// Deterministic: only tool results and tool invocations mutate it, never the
|
|
3
3
|
// model. Reset between scenario runs with resetState().
|
|
4
|
+
import { SESSION_CAP, SessionLru } from "./sessions.ts";
|
|
4
5
|
|
|
5
6
|
export interface ToolResult {
|
|
6
7
|
call: string;
|
|
@@ -43,6 +44,39 @@ export interface SessionState {
|
|
|
43
44
|
finalized: boolean;
|
|
44
45
|
}
|
|
45
46
|
|
|
47
|
+
// Rows this session promoted, for the riding-bytes rule (#165): a session must
|
|
48
|
+
// not pay a prompt-cache bust to be shown a fact it wrote itself, because that
|
|
49
|
+
// fact is already in its transcript. Filled where a write is promoted (the one
|
|
50
|
+
// place a row is created ON behalf of a named session — the viewer's own writes
|
|
51
|
+
// are deliberately not attributed), read by the epoch refresh.
|
|
52
|
+
//
|
|
53
|
+
// In-process on purpose. Persisting an author field would need a store
|
|
54
|
+
// migration and a privacy review (it records which session wrote what) to cover
|
|
55
|
+
// only the server-restart edge case, and a lost entry degrades to today's
|
|
56
|
+
// behavior — one bust — never to a wrong freeze. Bounded by the same cap as
|
|
57
|
+
// every other session-keyed ledger, so a resident server cannot grow it.
|
|
58
|
+
const authoredRows = new Map<string, Set<string>>();
|
|
59
|
+
const authoredOrder = new SessionLru(SESSION_CAP, (sid) => {
|
|
60
|
+
authoredRows.delete(sid);
|
|
61
|
+
});
|
|
62
|
+
const NO_ROWS: ReadonlySet<string> = new Set();
|
|
63
|
+
|
|
64
|
+
export function noteAuthored(sid: string | undefined, ts: string): void {
|
|
65
|
+
if (!sid || sid === "?") return;
|
|
66
|
+
let rows = authoredRows.get(sid);
|
|
67
|
+
if (!rows) {
|
|
68
|
+
rows = new Set();
|
|
69
|
+
authoredRows.set(sid, rows);
|
|
70
|
+
}
|
|
71
|
+
rows.add(ts);
|
|
72
|
+
authoredOrder.touch(sid);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function authoredFor(sid: string | undefined): ReadonlySet<string> {
|
|
76
|
+
if (!sid) return NO_ROWS;
|
|
77
|
+
return authoredRows.get(sid) ?? NO_ROWS;
|
|
78
|
+
}
|
|
79
|
+
|
|
46
80
|
// Newest message-bearing session seen this process. Opening a session finalizes
|
|
47
81
|
// the previous one (there is no session-end hook on the host surface).
|
|
48
82
|
let lastSeenSidVar: string | null = null;
|
|
@@ -88,6 +122,7 @@ export function getCurrent(): { sid: string; call: string; tool: string } {
|
|
|
88
122
|
|
|
89
123
|
export function resetState(): void {
|
|
90
124
|
sessions.clear();
|
|
125
|
+
authoredRows.clear();
|
|
91
126
|
current = { sid: "?", call: "?", tool: "?" };
|
|
92
127
|
lastSeenSidVar = null;
|
|
93
128
|
}
|
package/src/status.ts
CHANGED
|
@@ -160,6 +160,12 @@ export interface StatusPayload {
|
|
|
160
160
|
/** exact injected block ("" = abstained: no vocabulary overlap). */
|
|
161
161
|
block: string;
|
|
162
162
|
blockChars: number;
|
|
163
|
+
/**
|
|
164
|
+
* Every memory byte riding the system prompt: digest + frontier + block.
|
|
165
|
+
* Optional for backward-compatible reads of status files written before the
|
|
166
|
+
* distinction existed — the panel only prints it when present.
|
|
167
|
+
*/
|
|
168
|
+
sectionChars?: number;
|
|
163
169
|
budget: number;
|
|
164
170
|
store: StoreCounts;
|
|
165
171
|
/** optional for backward-compatible reads of pre-v2 files. */
|
|
@@ -350,6 +356,15 @@ export function contextLines(p: StatusPayload): string[] {
|
|
|
350
356
|
const pct = p.budget > 0 ? Math.round((p.blockChars / p.budget) * 100) : 0;
|
|
351
357
|
return [
|
|
352
358
|
` injected now ${p.blockChars}c ≈ ${estTok(p.blockChars)} tok · ${pct}% of ${p.budget}c budget`,
|
|
359
|
+
// The budget caps the RELEVANCE BLOCK; the standing digest and the frontier
|
|
360
|
+
// ride the system prompt too. Quoting only the budgeted slice would
|
|
361
|
+
// understate what the request actually carries.
|
|
362
|
+
...(p.sectionChars === undefined
|
|
363
|
+
? []
|
|
364
|
+
: [
|
|
365
|
+
` memory section ${p.sectionChars}c ≈ ${estTok(p.sectionChars)} tok riding the prompt` +
|
|
366
|
+
` (digest + frontier + the ${p.blockChars}c block above)`,
|
|
367
|
+
]),
|
|
353
368
|
` this epoch ${p.reason} epoch since ${p.at} (${ago(p.at)}) · rode ${st.epochRequests} request(s)`,
|
|
354
369
|
` session ${st.requests} request(s) · ${fmtCount(st.cumChars)}c ≈ ${fmtCount(estTok(st.cumChars))} tok rode · abstained ${st.abstained}`,
|
|
355
370
|
];
|
|
@@ -367,8 +382,10 @@ export function cacheLines(p: StatusPayload): string[] {
|
|
|
367
382
|
` cache busts ${st.invalidations} this session · last ${
|
|
368
383
|
st.lastInvalidation ? `${st.lastInvalidation.at.slice(11, 19)} (${st.lastInvalidation.reason})` : "-"
|
|
369
384
|
}`,
|
|
370
|
-
"
|
|
371
|
-
"
|
|
385
|
+
" a memory YOU saved in this session never costs one — you",
|
|
386
|
+
" already said it (#165). A correction, a removal, or a row",
|
|
387
|
+
" another session wrote costs exactly one, and the prefix",
|
|
388
|
+
" re-warms on the following turn",
|
|
372
389
|
];
|
|
373
390
|
const rate = cacheRate(p.measured);
|
|
374
391
|
const receipts = rate
|