opencode-self-improvement 0.23.0 → 0.24.0
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 +20 -2
- package/package.json +1 -1
- package/src/capture/runtime.ts +41 -12
- package/src/core/tags.ts +8 -0
- package/src/events.ts +8 -7
- package/src/identity/host-events.ts +82 -0
- package/src/index.ts +2 -0
- package/src/init/format.ts +45 -4
- package/src/init/retag.ts +186 -0
- package/src/init/run.ts +82 -64
- package/src/init/stamp.ts +306 -0
- package/src/inject/epochs.ts +19 -1
- package/src/recall/relevant.ts +91 -3
- package/src/status/metrics.ts +68 -0
- package/src/status/payload.ts +28 -3
- package/src/status/report.ts +23 -0
- package/src/store/model/predicates.ts +13 -1
- package/src/tools/init.ts +1 -1
- package/src/tools/status-tool.ts +4 -0
package/README.md
CHANGED
|
@@ -19,7 +19,7 @@ Every figure in this README carries a provenance marker: **measured** (read off
|
|
|
19
19
|
|
|
20
20
|
**2. Restart opencode.** It installs the package and its dependencies at startup, and the plugin installs its own slash commands. On desktop, a later config edit needs `opencode service restart`: relaunching the app leaves the background service — and the plugin options it already parsed — alive.
|
|
21
21
|
|
|
22
|
-
**3. Run `/repo-init`** in each repo you work in. It stores the test / build / lint / typecheck commands as memories and
|
|
22
|
+
**3. Run `/repo-init`** in each repo you work in. It stores the test / build / lint / typecheck commands as memories and records an init stamp tied to the current git head. The stamp is plugin bookkeeping under `<memory-root>/init-stamps/`, not a memory row, so no session can forge it (#374). A store left by an older release migrates once: its `init-stamp` row is honoured only when an `init_complete` audit line names it (and at the head that line names), is then retired, and is withheld from recall and injection either way (#376). Rerun `/repo-init force` after a refactor.
|
|
23
23
|
|
|
24
24
|
Needs Bun 1.3.0 or newer in the opencode build (the tested floor); older Bun reports a startup warning.
|
|
25
25
|
|
|
@@ -152,7 +152,8 @@ Gate-authored evidence and its init/capture lifecycle records capture attributio
|
|
|
152
152
|
- **Hard budgets.** Relevance block and each pull are capped at `injectBudget` characters, the frontier at `frontierBudget`, trimmed at whole-memory boundaries.
|
|
153
153
|
- **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.
|
|
154
154
|
- **Evidence is never injected**, and the standing system digest is two lines.
|
|
155
|
-
- **Measured, not claimed.** The plugin reads each turn's `tokens.cache` accounting and displays the actual hit rate next to the badge.
|
|
155
|
+
- **Measured, not claimed.** The plugin reads each turn's `tokens.cache` accounting and displays the actual hit rate next to the badge. The same receipts now carry what the session generated — `output` and `reasoning`, shown split, because on a reasoning-heavy seat the completion side is where the cost actually goes. A host that reports neither shows nothing, never a zero.
|
|
156
|
+
- **Auto-capture bills separately, and it is an estimate.** Capture is its own model call made after the turn, so it appears in no session's usage: read from session numbers, the plugin's own cost is exactly zero. The host exposes no receipt for it — `ctx.generate` has one member, `text`, resolving to `{ text }` with no `usage` — so `memory_status` reports chars/4 with `receipt=none` and the words "estimate, no provider receipt" on the line. Quote that number as an estimate or not at all. A pass disposed during teardown is not billed: its store is already gone, so the count undercounts by one call there.
|
|
156
157
|
|
|
157
158
|
**Bench** — 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:
|
|
158
159
|
|
|
@@ -276,6 +277,8 @@ Every imported row re-enters through the same four gates as `memory_remember` (t
|
|
|
276
277
|
|
|
277
278
|
Import and auto-capture also scan incoming prose for a small set of instruction-override, role-header, and download/execute patterns. Matching rows still face every write gate; a promoted match is tagged `quarantine` and withheld from recall, prompt/frontier injection, compaction anchors, contextual pull, scope/type listings, consolidation proposals, and decay. Decay previews do not quote these rows, and applied decay leaves them in the human review queue. The import reply counts quarantined promotions, gate evidence records pattern identifiers without copying the matched prose, and `/memory-report` lists review IDs for the caller's repository.
|
|
278
279
|
|
|
280
|
+
That screen only covers writes made after it shipped. A store that already holds an untagged poisoned row from an earlier `/repo-init` is repaired by the next one (#375): init scans every row the caller can read (this repository plus global) and, for each hit, writes a tagged twin through the normal gated path and retires the original — nothing is deleted, and each replacement emits its own `write_promoted` audit line. Re-running is safe: a row that already carries the tag is not touched. The reply reports `re-tagged=N`; a hit the gate refused is reported as `blocked=N` instead of passing silently, one run re-tags at most 100 rows and says how many remain, and any row GATE-2 retired along the way is named. A promoted replacement whose audit line itself fell is counted as `N without an audit line` rather than passing as a clean repair. This runs even when init skips on its stamp, because a stamped repository is the common case.
|
|
281
|
+
|
|
279
282
|
Review the full row in the memory viewer's **quarantined** filter. **Release quarantine** requires a reason, snapshots the pre-release row, and removes the quarantine flag and known scanner-reason tags; unrelated user labels such as `quarantine:custom`, repository ownership, row identity, blocklist, and supersession remain intact. Missing and already-released rows produce distinct, audited no-op outcomes. Existing prompt blocks refresh before the next delivery or status report when a row becomes quarantined or is released. Undoing a release can restore the quarantine flag.
|
|
280
283
|
|
|
281
284
|
This is a heuristic review queue, not a complete prompt-injection detector: legitimate documentation or quoted code can match. Markdown-bold role headers and download-then-`&&`-execute forms are recognized, but alternate role delimiters such as `[INST]` / `<<SYS>>`, base64-to-shell pipelines, paraphrased instructions, and indirect execution can evade it. Direct `memory_remember` and human viewer edits are explicit writes and are not automatically scanned: a session with that tool still has a prose channel, mitigated by the existing framing and provenance rather than quarantine. Those defenses still apply to released rows.
|
|
@@ -365,6 +368,21 @@ Run it when you want to know whether the suite still has teeth — after changin
|
|
|
365
368
|
|
|
366
369
|
**Pre-release ritual (decided 2026-11-04, #72):** before pushing a release commit, a human runs `--validate`, then `--selftest`, then `--fail-on-survivors`, and records the mutation score and the survivor list in `bench/RESULTS.md` beside the published evidence. Cadence is pre-release only, run by a person: the sweep is a full suite per mutant and never belongs in CI, where it would cost more than it informs. Survivors become entries on the unpinned-invariant list, not red checks.
|
|
367
370
|
|
|
371
|
+
### Bench artifacts stay out of git
|
|
372
|
+
|
|
373
|
+
Raw sweep output is regenerable measurement data, and it was the largest tracked content in the repository. It is not committed (#232). A clone carries the published summaries — `bench/RESULTS.md`, `bench/recall-results.md`, `bench/test-sweep-results.md`, `bench/capture-trigger-results.md` — and the inputs those summaries are rebuilt from. History is not rewritten: the old blobs stay in earlier revisions, so this shrinks new checkouts, not the archive.
|
|
374
|
+
|
|
375
|
+
| Artifact | How to get it back |
|
|
376
|
+
| --- | --- |
|
|
377
|
+
| `bench/append-publication-198/` | The pinned recipe below. |
|
|
378
|
+
| A mutation sweep log | `bun scripts/test-sweep.ts --log=<path>`. |
|
|
379
|
+
|
|
380
|
+
Regenerating `bench/append-publication-198/`: the runner is `bench/runners/append-cost-198.ts`, invoked once per size, mode and platform as `bun bench/runners/append-cost-198.ts <absolute-source-checkout> <size-MiB> <baseline|candidate> <round>`. It loads `src/memory.ts`, `src/logfmt.ts` and `src/config.ts` from the source root it is given, so it must point at the two pinned checkouts of the #198 measurement — baseline `bf9f4d2` (0.15.0) and candidate `7c1dfc4` (the atomic-publication commit on that same base) — not at a current tree, where the #168 restructure moved those modules. Install locked dependencies in each checkout; use the current runner for both source roots; every invocation creates and cleans its own synthetic store and prints one JSON line. Sizes 0.1, 1, 10, 50 MiB; 3 rounds; baseline-then-candidate in rounds 1 and 3, reversed in round 2; 12 sequential appends per invocation, first 2 discarded as warmups, 30 samples pooled per mode/size/platform. Aggregation: sort `latencyMs` ascending, median = average of positions 15 and 16, p95 = nearest rank `ceil(0.95×30)` = position 29, max = position 30. Every invocation asserts the original byte prefix is unchanged and the parsed row count equals `seedRows + 12`. The full methodology — including the measurement limitations, which are part of the claim — is one command away: `git show c86379e^:bench/append-publication-198/methodology.json`.
|
|
381
|
+
|
|
382
|
+
A script that needs a missing artifact names the file and the command that produces it instead of throwing a stack trace.
|
|
383
|
+
|
|
384
|
+
The `#71` set is the deliberate exception: `bench/test-integrity-71.json`, `bench/test-integrity-71/before.jsonl`, `bench/test-integrity-71/after.jsonl` and `bench/test-integrity-71-verdicts.json` stay tracked. It looks regenerable and is not. `scripts/triage-71.ts` refuses to run unless the verdicts file carries exactly one verdict per CURRENT test file, and the test tree has grown since #71, so the documented rebuild fails on today's tree (`every current test file needs exactly one verdict`, measured on `main` at `f8f42fd`). Deleting the derived JSON would therefore destroy the only copy of a published number.
|
|
385
|
+
|
|
368
386
|
## Troubleshooting
|
|
369
387
|
|
|
370
388
|
| Problem | Fix |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.24.0",
|
|
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/capture/runtime.ts
CHANGED
|
@@ -521,20 +521,23 @@ export function configureAutoCapture(
|
|
|
521
521
|
lessonSet.add(normWs(f.slice(sep + 3)).toLowerCase());
|
|
522
522
|
}
|
|
523
523
|
}
|
|
524
|
+
// Hoisted so its length can be billed below.
|
|
525
|
+
// Redact the COMPLETE transcript, THEN apply the character budget
|
|
526
|
+
// (#132). Cropping first can start the window INSIDE a credential:
|
|
527
|
+
// a PEM body whose BEGIN marker fell off, or a token whose prefix
|
|
528
|
+
// fell off, matches no pattern — buildCapturePrompt's own scrub
|
|
529
|
+
// (kept, defense in depth) cannot recognize a fragment.
|
|
530
|
+
const capturePrompt = buildCapturePrompt(
|
|
531
|
+
redactSecrets(work).slice(-7000),
|
|
532
|
+
captureMax,
|
|
533
|
+
redactSecrets(userProse).slice(-1500),
|
|
534
|
+
knownRows,
|
|
535
|
+
attested,
|
|
536
|
+
);
|
|
537
|
+
const promptChars = capturePrompt.length;
|
|
524
538
|
const out = await generateApi.text({
|
|
525
539
|
model,
|
|
526
|
-
|
|
527
|
-
// (#132). Cropping first can start the window INSIDE a credential:
|
|
528
|
-
// a PEM body whose BEGIN marker fell off, or a token whose prefix
|
|
529
|
-
// fell off, matches no pattern — buildCapturePrompt's own scrub
|
|
530
|
-
// (kept, defense in depth) cannot recognize a fragment.
|
|
531
|
-
prompt: buildCapturePrompt(
|
|
532
|
-
redactSecrets(work).slice(-7000),
|
|
533
|
-
captureMax,
|
|
534
|
-
redactSecrets(userProse).slice(-1500),
|
|
535
|
-
knownRows,
|
|
536
|
-
attested,
|
|
537
|
-
),
|
|
540
|
+
prompt: capturePrompt,
|
|
538
541
|
});
|
|
539
542
|
const text = typeof out === "string" ? out : (out?.text ?? "");
|
|
540
543
|
// #211: disposed while the model call was in flight. Stop here — the
|
|
@@ -543,6 +546,32 @@ export function configureAutoCapture(
|
|
|
543
546
|
// is the ENOENT teardown noise this check exists to eliminate, and
|
|
544
547
|
// the drain in cleanup means the pass is finished, not lost mid-air.
|
|
545
548
|
if (controller.signal.aborted) return;
|
|
549
|
+
// #387: bill our own call. `generate.text` resolves to `{ text }` and
|
|
550
|
+
// nothing else — no `usage`, no `tokens` (probed against the running
|
|
551
|
+
// host) — and capture is not part of any session's event stream, so a
|
|
552
|
+
// meter reading the session reports zero for it. chars/4 is an
|
|
553
|
+
// estimate and the line says `receipt=none` so it can never be quoted
|
|
554
|
+
// as a provider number.
|
|
555
|
+
//
|
|
556
|
+
// Deliberately AFTER the teardown check above: a disposed pass has no
|
|
557
|
+
// store left to write to. Its tokens therefore go unbilled here, which
|
|
558
|
+
// undercounts by one call at teardown rather than throwing ENOENT out
|
|
559
|
+
// of a receipt path that must never break a session.
|
|
560
|
+
await record(
|
|
561
|
+
"capture_cost",
|
|
562
|
+
{
|
|
563
|
+
session: sid,
|
|
564
|
+
trigger,
|
|
565
|
+
prompt_chars: promptChars,
|
|
566
|
+
text_chars: text.length,
|
|
567
|
+
est_tokens: Math.ceil((promptChars + text.length) / 4),
|
|
568
|
+
receipt: "none",
|
|
569
|
+
...(modelTag ? { model: modelTag } : {}),
|
|
570
|
+
},
|
|
571
|
+
true,
|
|
572
|
+
sid,
|
|
573
|
+
captureGate.evidenceContext,
|
|
574
|
+
);
|
|
546
575
|
let candidates = parseCandidates(text, captureMax);
|
|
547
576
|
// Deterministic guided pre-pass (POC, FINDINGS 2026-11-08 §4, option
|
|
548
577
|
// `captureGuidedRules`): the user's own lines decide what is guided —
|
package/src/core/tags.ts
CHANGED
|
@@ -8,5 +8,13 @@ export const AUTO_CAPTURE_TAG = "auto-capture";
|
|
|
8
8
|
*/
|
|
9
9
|
export const CODE_CHECKED_TAG = "code-checked";
|
|
10
10
|
|
|
11
|
+
// The pre-#374 init stamp: a `context` row written by an older release's
|
|
12
|
+
// `/repo-init`. It is plugin bookkeeping that the stamp file replaced, so it is
|
|
13
|
+
// never a fact for a model to read. `src/init/stamp.ts` retires a row once its
|
|
14
|
+
// audit line confirms the migration; the tag keeps every other row — including
|
|
15
|
+
// one whose audit line is gone, which migration cannot reach — out of the
|
|
16
|
+
// prompt (#376 review).
|
|
17
|
+
export const INIT_STAMP_TAG = "init-stamp";
|
|
18
|
+
|
|
11
19
|
// The public write boundaries reserve this same tag (#342/#355).
|
|
12
20
|
export { USER_GUIDED_TAG } from "./guidance.ts";
|
package/src/events.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
import {
|
|
16
16
|
sessionIdentityEvent,
|
|
17
17
|
sessionUsageEvent,
|
|
18
|
+
foldUsage,
|
|
18
19
|
} from "./identity/host-events.ts";
|
|
19
20
|
import {
|
|
20
21
|
afterTool,
|
|
@@ -262,14 +263,14 @@ export async function registerHooks(
|
|
|
262
263
|
}
|
|
263
264
|
const usage = sessionUsageEvent(raw);
|
|
264
265
|
if (!usage) continue;
|
|
265
|
-
const { sessionID
|
|
266
|
+
const { sessionID } = usage;
|
|
266
267
|
sessions.touch(sessionID);
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
268
|
+
// #394 review: fold, do not overwrite — on the compatibility path a
|
|
269
|
+
// receipt is per-message, and the last message is not the session.
|
|
270
|
+
measuredTurns.set(
|
|
271
|
+
sessionID,
|
|
272
|
+
foldUsage(usage, new Date().toISOString()),
|
|
273
|
+
);
|
|
273
274
|
await guarded("status flush (measured)", () =>
|
|
274
275
|
flushStatus(sessionID),
|
|
275
276
|
);
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// Compatibility boundary for host payloads. These adapters only read data;
|
|
2
2
|
// repository binding, ambient fallbacks, clocks, and I/O belong to the caller.
|
|
3
|
+
import type { Measured } from "../status/payload.ts";
|
|
4
|
+
|
|
3
5
|
function fields(value: unknown): Record<string, unknown> {
|
|
4
6
|
return value !== null && typeof value === "object"
|
|
5
7
|
? (value as Record<string, unknown>)
|
|
@@ -87,6 +89,27 @@ export interface SessionUsage {
|
|
|
87
89
|
input: number;
|
|
88
90
|
read: number;
|
|
89
91
|
write: number;
|
|
92
|
+
/**
|
|
93
|
+
* Completion tokens the session generated (#387). Absent from the envelope
|
|
94
|
+
* before this, so the plugin could report what the prompt cache cost but
|
|
95
|
+
* never what the session itself produced — and `input` is only the UNCACHED
|
|
96
|
+
* remainder, so the two together understate a session by most of its size.
|
|
97
|
+
* Zero when the host omits the field, which is why the status surface gates
|
|
98
|
+
* its generation line on a nonzero rather than printing 0.
|
|
99
|
+
*/
|
|
100
|
+
output: number;
|
|
101
|
+
reasoning: number;
|
|
102
|
+
/**
|
|
103
|
+
* The message this receipt belongs to — the `message.updated` compatibility
|
|
104
|
+
* path only. Streaming updates for the same message overwrite each other;
|
|
105
|
+
* they must not overwrite another message's receipt (#394 review).
|
|
106
|
+
*/
|
|
107
|
+
messageID?: string;
|
|
108
|
+
/**
|
|
109
|
+
* True only for `session.usage.updated`: that source is cumulative, so the
|
|
110
|
+
* latest receipt replaces the session total instead of folding into it.
|
|
111
|
+
*/
|
|
112
|
+
cumulative?: boolean;
|
|
90
113
|
}
|
|
91
114
|
|
|
92
115
|
/** V2 session usage, or the assistant-message usage emitted by older hosts. */
|
|
@@ -111,7 +134,66 @@ export function sessionUsageEvent(raw: unknown): SessionUsage | undefined {
|
|
|
111
134
|
input: Number(tokens.input) || 0,
|
|
112
135
|
read: Number(cache.read) || 0,
|
|
113
136
|
write: Number(cache.write) || 0,
|
|
137
|
+
output: Number(tokens.output) || 0,
|
|
138
|
+
reasoning: Number(tokens.reasoning) || 0,
|
|
139
|
+
// The two sources mean different things, and conflating them was the
|
|
140
|
+
// review finding: `session.usage.updated` is cumulative, so its latest
|
|
141
|
+
// receipt IS the session total; `message.updated` carries ONE message's
|
|
142
|
+
// usage, and the total must sum across messages.
|
|
143
|
+
...(event.type === "session.usage.updated" ? { cumulative: true } : {}),
|
|
144
|
+
...(typeof info.id === "string" ? { messageID: info.id } : {}),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// #394 review: on the `message.updated` compatibility path each receipt is
|
|
149
|
+
// ONE message's usage, not the session's. Overwriting the session total with
|
|
150
|
+
// the last message displayed 90 completion tok where two messages produced
|
|
151
|
+
// 160. Streaming updates arrive repeatedly per message, so the latest receipt
|
|
152
|
+
// per message is kept and the session total sums across messages. A
|
|
153
|
+
// genuinely cumulative `session.usage.updated` keeps its replacement
|
|
154
|
+
// semantics. State is module-level and evicted with the session (the epoch
|
|
155
|
+
// controller's LRU calls forgetUsage).
|
|
156
|
+
const messageReceipts = new Map<string, Map<string, Measured>>();
|
|
157
|
+
|
|
158
|
+
/** Fold one usage receipt into the session's measured total. */
|
|
159
|
+
export function foldUsage(usage: SessionUsage, at: string): Measured {
|
|
160
|
+
const receipt: Measured = {
|
|
161
|
+
at,
|
|
162
|
+
input: usage.input,
|
|
163
|
+
read: usage.read,
|
|
164
|
+
write: usage.write,
|
|
165
|
+
output: usage.output,
|
|
166
|
+
reasoning: usage.reasoning,
|
|
114
167
|
};
|
|
168
|
+
if (usage.cumulative || usage.messageID === undefined) return receipt;
|
|
169
|
+
let msgs = messageReceipts.get(usage.sessionID);
|
|
170
|
+
if (!msgs) {
|
|
171
|
+
msgs = new Map();
|
|
172
|
+
messageReceipts.set(usage.sessionID, msgs);
|
|
173
|
+
}
|
|
174
|
+
msgs.set(usage.messageID, receipt);
|
|
175
|
+
const total = {
|
|
176
|
+
at,
|
|
177
|
+
input: 0,
|
|
178
|
+
read: 0,
|
|
179
|
+
write: 0,
|
|
180
|
+
output: 0,
|
|
181
|
+
reasoning: 0,
|
|
182
|
+
};
|
|
183
|
+
for (const r of msgs.values()) {
|
|
184
|
+
total.input += r.input ?? 0;
|
|
185
|
+
total.read += r.read ?? 0;
|
|
186
|
+
total.write += r.write ?? 0;
|
|
187
|
+
total.output += r.output ?? 0;
|
|
188
|
+
total.reasoning += r.reasoning ?? 0;
|
|
189
|
+
if (r.at > total.at) total.at = r.at;
|
|
190
|
+
}
|
|
191
|
+
return total;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Drop a session's per-message ledger when its status entry is evicted. */
|
|
195
|
+
export function forgetUsage(sessionID: string): void {
|
|
196
|
+
messageReceipts.delete(sessionID);
|
|
115
197
|
}
|
|
116
198
|
|
|
117
199
|
/** Session ID envelopes accepted by capture; trigger selection stays separate. */
|
package/src/index.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
// src/command.ts. The default export `{ id, setup(ctx) }` is checked against
|
|
9
9
|
// the SDK's Plugin type using a type-only import (see the note on `plugin`).
|
|
10
10
|
import { registerHooks } from "./events.ts";
|
|
11
|
+
import { forgetUsage } from "./identity/host-events.ts";
|
|
11
12
|
import { guarded, setGuardedFailureReporter } from "./core/hooks.ts";
|
|
12
13
|
import type { PluginCtx } from "./core/host.ts";
|
|
13
14
|
import type { Cleanup, Plugin } from "@opencode/plugin/promise/plugin";
|
|
@@ -207,6 +208,7 @@ const impl = {
|
|
|
207
208
|
// Code-check guided claims by default; explicit false opts out.
|
|
208
209
|
contradictionSurface: ctx.options?.contradictionSurface !== false,
|
|
209
210
|
measuredTurns,
|
|
211
|
+
forgetUsage,
|
|
210
212
|
noteHits: (sid, rows, query) => noteHits("inject", sid, rows, query),
|
|
211
213
|
});
|
|
212
214
|
const flushStatus = sessions.flushStatus;
|
package/src/init/format.ts
CHANGED
|
@@ -4,15 +4,56 @@
|
|
|
4
4
|
import { type InitSummary } from "./run.ts";
|
|
5
5
|
|
|
6
6
|
export function formatInit(s: InitSummary): string {
|
|
7
|
+
// #376 review: a migration whose file write failed is not a migration. The row
|
|
8
|
+
// was honoured, so this run is still idempotent, but nothing was copied — the
|
|
9
|
+
// reply says so instead of claiming a migration that left no file behind.
|
|
10
|
+
const migrated = s.stampMigrated
|
|
11
|
+
? s.stampError
|
|
12
|
+
? " (stamp read from a store row; the copy to the stamp file failed)"
|
|
13
|
+
: " (stamp migrated from a store row)"
|
|
14
|
+
: "";
|
|
15
|
+
// A retirement that did not land is named, in the same spirit as the re-tag
|
|
16
|
+
// repair's partial count: the migration is durable, the row is still there,
|
|
17
|
+
// and the operator reads which half failed (#376 review).
|
|
18
|
+
const retireFault = s.stampRetireError
|
|
19
|
+
? `Legacy stamp row NOT retired (${s.stampRetireError}); it stays in the store, withheld from recall. Run init again.`
|
|
20
|
+
: "";
|
|
21
|
+
// #375: a repair that did something, or could not finish, is reported. A quiet
|
|
22
|
+
// "Nothing to do." over a store that still holds a live poisoned row is the
|
|
23
|
+
// failure this ticket exists to remove.
|
|
24
|
+
const r = s.retag;
|
|
25
|
+
const repair =
|
|
26
|
+
r && (r.retagged || r.blocked || r.partial || r.remaining || r.unaudited)
|
|
27
|
+
? `\nInjection screen: re-tagged=${r.retagged}, blocked=${r.blocked}, partial=${r.partial}` +
|
|
28
|
+
(r.unaudited ? `, ${r.unaudited} without an audit line` : "") +
|
|
29
|
+
(r.remaining ? `, ${r.remaining} left (run init again)` : "") +
|
|
30
|
+
(r.collateral.length
|
|
31
|
+
? `, ${r.collateral.length} retired by GATE-2 while re-tagging`
|
|
32
|
+
: "")
|
|
33
|
+
: "";
|
|
7
34
|
if (s.skipped) {
|
|
8
|
-
|
|
35
|
+
// The skip path can carry a stamp fault of its own: the migration honoured a
|
|
36
|
+
// legacy row and could not write the file, so the next init re-migrates.
|
|
37
|
+
// Silence here is what let a failed migration report success (#376 review).
|
|
38
|
+
const fault = s.stampError
|
|
39
|
+
? `; stamp NOT recorded (${s.stampError}) — the migration will be retried`
|
|
40
|
+
: "";
|
|
41
|
+
return `Already initialized for ${s.scope} at head ${s.head} (stamp ${s.stampTs}). Nothing to do.${migrated}${fault}${retireFault ? `\n${retireFault}` : ""}${repair}`;
|
|
9
42
|
}
|
|
10
|
-
const scr = s.scripts.map((
|
|
43
|
+
const scr = s.scripts.map((r2) => `- ${r2.source}: "${r2.cmd}"`).join("\n");
|
|
44
|
+
const stamp = s.stampError
|
|
45
|
+
? `; stamp NOT recorded (${s.stampError}) — init will run again`
|
|
46
|
+
: `; stamp=${s.stampTs ?? "-"}`;
|
|
11
47
|
return [
|
|
12
48
|
`Initialized ${s.scope} (root ${s.root}, head ${s.head}).`,
|
|
13
49
|
scr ? `Scripts (${s.scripts.length}):\n${scr}` : "Scripts: none detected",
|
|
14
50
|
`Memories: written=${s.written}, collapsed=${s.collapsed}, blocked=${s.blocked}` +
|
|
15
51
|
(s.unaudited ? `, ${s.unaudited} without an audit line` : "") +
|
|
16
|
-
|
|
17
|
-
|
|
52
|
+
stamp +
|
|
53
|
+
migrated,
|
|
54
|
+
retireFault,
|
|
55
|
+
repair.trimStart(),
|
|
56
|
+
]
|
|
57
|
+
.filter((line) => line !== "")
|
|
58
|
+
.join("\n");
|
|
18
59
|
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// One-time repair for rows stored before #372 screened init's writes (#375).
|
|
2
|
+
//
|
|
3
|
+
// #372 made `/repo-init` run the injection screen over the rows it writes, so a
|
|
4
|
+
// checkout sitting in a directory named `eval (x)` now gets its command memories
|
|
5
|
+
// tagged `quarantine`. That covers writes made after it shipped. A store that
|
|
6
|
+
// already holds an untagged poisoned row keeps it, and re-running init cannot
|
|
7
|
+
// fix it: GATE-3's exact-duplicate check compares type and content, so the new
|
|
8
|
+
// quarantined candidate collapses into the old untagged row. `force: true` does
|
|
9
|
+
// not help either — force skips the stamp check, not the dedup.
|
|
10
|
+
//
|
|
11
|
+
// So init scans what it can read and re-tags the hits. Each re-tag is a normal
|
|
12
|
+
// gated write that replaces the row it names (`supersedesTs`) — the one shape
|
|
13
|
+
// GATE-3 reads as a metadata edit rather than a duplicate. Nothing is deleted:
|
|
14
|
+
// the old row survives superseded, and every replacement emits its own
|
|
15
|
+
// `write_promoted` audit line.
|
|
16
|
+
import { runWriteGate, type GateContext } from "../gate/gate.ts";
|
|
17
|
+
import { markSuperseded } from "../store/files/supersede.ts";
|
|
18
|
+
import { loadAll } from "../store/files/load.ts";
|
|
19
|
+
import type { Memory } from "../store/model/memory.ts";
|
|
20
|
+
import { isActive } from "../store/model/predicates.ts";
|
|
21
|
+
import { isVisibleTo } from "../store/model/visibility.ts";
|
|
22
|
+
import {
|
|
23
|
+
isQuarantined,
|
|
24
|
+
quarantineCandidate,
|
|
25
|
+
} from "../store/quarantine/quarantine.ts";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Writes one init run may make. A pathological store (an injection-shaped
|
|
29
|
+
* directory name plus a thousand rows quoting it) must not turn one `/repo-init`
|
|
30
|
+
* into a thousand full-file publishes. The remainder is reported, never hidden.
|
|
31
|
+
*/
|
|
32
|
+
export const MAX_RETAGS_PER_RUN = 100;
|
|
33
|
+
|
|
34
|
+
export interface RetagResult {
|
|
35
|
+
/** Active rows the caller could read. */
|
|
36
|
+
scanned: number;
|
|
37
|
+
/** Rows replaced by a tagged twin AND retired. */
|
|
38
|
+
retagged: number;
|
|
39
|
+
/** Hits the gate refused; they stay active and untagged. */
|
|
40
|
+
blocked: number;
|
|
41
|
+
/** Promoted, but the retirement did not land (another supersession won). */
|
|
42
|
+
partial: number;
|
|
43
|
+
/** Promoted with a fallen `write_promoted` audit line (#155 class). */
|
|
44
|
+
unaudited: number;
|
|
45
|
+
/** Hits left unprocessed because the per-run bound was reached. */
|
|
46
|
+
remaining: number;
|
|
47
|
+
/** Rows GATE-2 retired as a side effect of these writes. Never hidden. */
|
|
48
|
+
collateral: string[];
|
|
49
|
+
/**
|
|
50
|
+
* Retirement attempts that REJECTED (lock contention) rather than returning
|
|
51
|
+
* false (#378 review). The replacement is durable; the original is not.
|
|
52
|
+
* Counted in `partial`, named here.
|
|
53
|
+
*/
|
|
54
|
+
failures: string[];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function emptyRetag(): RetagResult {
|
|
58
|
+
return {
|
|
59
|
+
scanned: 0,
|
|
60
|
+
retagged: 0,
|
|
61
|
+
blocked: 0,
|
|
62
|
+
partial: 0,
|
|
63
|
+
unaudited: 0,
|
|
64
|
+
remaining: 0,
|
|
65
|
+
collateral: [],
|
|
66
|
+
failures: [],
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The row as it should be written again: identical prose and metadata, plus the
|
|
72
|
+
* tags the screen asked for.
|
|
73
|
+
*
|
|
74
|
+
* Every field is copied on purpose. A repair that quietly dropped the verbatim
|
|
75
|
+
* quote (`original`) or the contradiction fields would close one boundary and
|
|
76
|
+
* break another, and `repo` is carried so a global row stays global while a
|
|
77
|
+
* repository row stays in its own repository — an edit must never move a row's
|
|
78
|
+
* visibility. The row's own `ts`, `file` and `superseded_by` are deliberately
|
|
79
|
+
* NOT carried: the gate mints a fresh identity for the replacement.
|
|
80
|
+
*/
|
|
81
|
+
function reTagged(row: Memory, tags: string[]) {
|
|
82
|
+
return {
|
|
83
|
+
type: row.type,
|
|
84
|
+
scope: row.scope,
|
|
85
|
+
content: row.content,
|
|
86
|
+
...(row.issue ? { issue: row.issue } : {}),
|
|
87
|
+
...(row.kw ? { kw: row.kw } : {}),
|
|
88
|
+
...(row.ref ? { ref: row.ref } : {}),
|
|
89
|
+
...(row.claim ? { claim: row.claim } : {}),
|
|
90
|
+
...(row.klass ? { klass: row.klass } : {}),
|
|
91
|
+
...(row.original ? { original: row.original } : {}),
|
|
92
|
+
status: row.status ?? "settled",
|
|
93
|
+
repo: row.repo ?? "global",
|
|
94
|
+
repoPath: row.repo ? row.repoPath : undefined,
|
|
95
|
+
tags,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Re-tag rows that match the injection screen but do not carry the tag.
|
|
101
|
+
*
|
|
102
|
+
* Reach is exactly what the caller can read — this repository's rows plus global
|
|
103
|
+
* rows. Another repository's rows are not this caller's to rewrite.
|
|
104
|
+
*/
|
|
105
|
+
export async function retagQuarantinedRows(
|
|
106
|
+
ctx: GateContext,
|
|
107
|
+
): Promise<RetagResult> {
|
|
108
|
+
const out = emptyRetag();
|
|
109
|
+
const rows = (await loadAll()).filter(
|
|
110
|
+
(m) =>
|
|
111
|
+
isActive(m) &&
|
|
112
|
+
!isQuarantined(m) &&
|
|
113
|
+
(ctx.reader ? isVisibleTo(m, ctx.reader) : true),
|
|
114
|
+
);
|
|
115
|
+
out.scanned = rows.length;
|
|
116
|
+
const hits: Memory[] = [];
|
|
117
|
+
for (const row of rows) {
|
|
118
|
+
// quarantineCandidate returns the same object when nothing matches.
|
|
119
|
+
if (quarantineCandidate(row) !== row) hits.push(row);
|
|
120
|
+
}
|
|
121
|
+
if (hits.length > MAX_RETAGS_PER_RUN)
|
|
122
|
+
out.remaining = hits.length - MAX_RETAGS_PER_RUN;
|
|
123
|
+
for (const row of hits.slice(0, MAX_RETAGS_PER_RUN)) {
|
|
124
|
+
const tagged = quarantineCandidate(row);
|
|
125
|
+
const durable: string[] = [];
|
|
126
|
+
const outcome = await runWriteGate(reTagged(row, tagged.tags ?? []), {
|
|
127
|
+
...ctx,
|
|
128
|
+
supersedesTs: row.ts,
|
|
129
|
+
durable,
|
|
130
|
+
});
|
|
131
|
+
if (outcome.action !== "promoted" && outcome.action !== "collapsed") {
|
|
132
|
+
// Blocked: the untagged row stays exactly as it was, and the operator
|
|
133
|
+
// has to hear that rather than read a clean repair.
|
|
134
|
+
out.blocked++;
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
// #378 review (WhollyMindless): two ways the unsafe original survived.
|
|
138
|
+
// (a) COLLAPSED is not "nothing happened" here — it means a quarantined
|
|
139
|
+
// twin from an earlier interrupted repair is already durable, and the
|
|
140
|
+
// only missing step is retiring the original. Refusing to act on the
|
|
141
|
+
// collapse left the row unquarantined forever (retagged=0, blocked=1
|
|
142
|
+
// on every retry). The collapse survivor IS the twin: the re-tagged
|
|
143
|
+
// candidate differs from the original only by tags, and the
|
|
144
|
+
// supersedesTs carve-out keeps the original from matching as its own
|
|
145
|
+
// duplicate, so an exact-content match is the prior replacement.
|
|
146
|
+
// (b) markSuperseded can REJECT (lock contention), not just return false.
|
|
147
|
+
// The twin is durable either way, so the failure lands in `partial`
|
|
148
|
+
// with its reason instead of escaping as if nothing was written —
|
|
149
|
+
// the #155 lesson, applied to the repair path.
|
|
150
|
+
const successor =
|
|
151
|
+
outcome.action === "collapsed" ? outcome.collapsedWith : outcome.ts;
|
|
152
|
+
if (successor === undefined) {
|
|
153
|
+
out.blocked++;
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
let retired = false;
|
|
157
|
+
try {
|
|
158
|
+
retired = await markSuperseded(
|
|
159
|
+
row.ts,
|
|
160
|
+
{
|
|
161
|
+
superseded_by: successor,
|
|
162
|
+
reason: "init",
|
|
163
|
+
symbol: row.ts,
|
|
164
|
+
from: row.ts,
|
|
165
|
+
to: successor,
|
|
166
|
+
},
|
|
167
|
+
durable,
|
|
168
|
+
);
|
|
169
|
+
} catch (err) {
|
|
170
|
+
out.failures.push(
|
|
171
|
+
`${row.ts}: ${err instanceof Error && err.message ? err.message : String(err)}`,
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
for (const ts of durable)
|
|
175
|
+
if (!out.collateral.includes(ts)) out.collateral.push(ts);
|
|
176
|
+
if (!retired) {
|
|
177
|
+
// The replacement IS durable. Name which half did not land, in the shape
|
|
178
|
+
// memory_update uses (#155), instead of counting a clean re-tag.
|
|
179
|
+
out.partial++;
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
out.retagged++;
|
|
183
|
+
if (outcome.evidenceError !== undefined) out.unaudited++;
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
}
|