opencode-self-improvement 0.33.5 → 0.33.8
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 +7 -3
- package/docs/internals/auto-capture-evidence.md +2 -0
- package/docs/reference/install.md +25 -0
- package/docs/reference/troubleshooting.md +2 -1
- package/index.ts +48 -2
- package/package.json +1 -1
- package/src/capture/runtime.ts +80 -1
- package/src/inject/budget.ts +20 -26
- package/src/inject/epochs.ts +1 -14
- package/src/inject/pull.ts +8 -12
- package/src/recall/dedupe.ts +41 -4
- package/src/recall/relevant.ts +9 -14
- package/src/status/metrics.ts +40 -1
- package/src/status/report.ts +23 -1
- package/src/telemetry/record.ts +84 -7
package/README.md
CHANGED
|
@@ -73,7 +73,7 @@ It is **on by default** and needs no model name to run. With `captureModel` unse
|
|
|
73
73
|
|
|
74
74
|
What has been established, and by which kind of evidence, is itemised in [docs/internals/auto-capture-evidence.md](docs/internals/auto-capture-evidence.md). Read that file before quoting any figure in it — two of the entries are defects found in the measuring bench itself, and the corrected numbers are the ones recorded there. `bench/capture-trigger-results.md` is a **bench** simulation of trigger *timing* with a scripted extractor; it answers "which moment is worth mining", not "does this earn its keep".
|
|
75
75
|
|
|
76
|
-
**Am I armed?** `memory_evidence` answers on the `plugin_load` line: `capture=on` (the default), `capture=off` (`autoCapture: false`), `invalid_model`, `no_capabilities`, or `switch_mismatch`.
|
|
76
|
+
**Am I armed?** `memory_evidence` answers on the `plugin_load` line: `capture=on` (the default), `capture=off` (`autoCapture: false`), `invalid_model`, `no_capabilities`, or `switch_mismatch`. Once armed, an empty turn leaves one of these lines: `capture_cost` a verdict, `auto_capture_skipped` nothing durable, `auto_capture_start` alone a pass cut before its verdict, `auto_capture_dispose` no turn-end event seen. On desktop this needs `opencode service restart` after an edit — relaunching the app keeps the old service and its already-parsed options alive.
|
|
77
77
|
|
|
78
78
|
## How memory is written
|
|
79
79
|
|
|
@@ -216,8 +216,12 @@ and, next to it, a sibling `tui.ts` — so the repository root carries `index.ts
|
|
|
216
216
|
(re-exporting `src/index.ts`) and `tui.ts` (re-exporting the default of
|
|
217
217
|
`src/tui/panel.tsx`). **Package installs** resolve through `package.json`
|
|
218
218
|
`exports` instead: `"."` → `./index.ts` and `"./tui"` → `./src/tui/panel.tsx`.
|
|
219
|
-
Real code lives under `src/`, one directory per module.
|
|
219
|
+
Real code lives under `src/`, one directory per module. Loose discovery installs
|
|
220
|
+
nothing, so run `bun install` inside the copied directory: the plugin has runtime
|
|
221
|
+
dependencies, and one that cannot be resolved fails the load with an error about
|
|
222
|
+
the default export rather than the missing package
|
|
223
|
+
([#464](https://github.com/abogartz/opencode-self-improvement/issues/464)).
|
|
220
224
|
|
|
221
225
|
## Troubleshooting
|
|
222
226
|
|
|
223
|
-
The whole list, one row per problem with its fix, is in [docs/reference/troubleshooting.md](docs/reference/troubleshooting.md): tools not available, a blocked `memory_remember`, an argument-schema rejection, `memory store is busy`, a store on a network share, a stale plugin after an update, auto-capture doing nothing, malformed rows, stray lock files, a missing `/repo-init`, and a clean reset on Windows.
|
|
227
|
+
The whole list, one row per problem with its fix, is in [docs/reference/troubleshooting.md](docs/reference/troubleshooting.md): tools not available, a load error that blames the default export when a dependency is missing, a blocked `memory_remember`, an argument-schema rejection, `memory store is busy`, a store on a network share, a stale plugin after an update, auto-capture doing nothing, malformed rows, stray lock files, a missing `/repo-init`, and a clean reset on Windows.
|
|
@@ -21,6 +21,8 @@ What is established, from tests and fixtures (no live store involved):
|
|
|
21
21
|
|
|
22
22
|
- **The trigger is live on a real host, and the write now survives it.** An end-to-end scenario drives `opencode run` against a real turn with a scripted provider (`e2e/capture.test.ts`): the turn-end event fires and a capture pass starts, 12 of 12 runs. It used to reach the write gate in only some of them — 3 of 12 in one sample, 6 of 12 in a controlled A/B against the same script, 12 of 12 in two samples after the fix. `opencode run` disposes the plugin as the turn ends, and `captureCleanup` aborted every in-flight pass before its gate ran: the #211 contract, correct for the teardown it was written for and fatal here, because nothing is being torn down and the process simply exits. Cleanup now distinguishes the two cases — a pass still parked in the model call is abandoned, a pass that already holds its answer is drained, because its remaining work is local and milliseconds. All of #211's disposal assertions still pass unchanged. Fixed on this branch, #404.
|
|
23
23
|
|
|
24
|
+
- **The host abandons a turn-end handler that awaits; tying that to the original #406 misses is a hypothesis, not an observation.** Measured 2026-11-21 on opencode v2.3.0 (macOS) with a probe plugin over the same harness: the turn-end event reaches `event.subscribe` in 10 of 10 turns at every handler length, but a handler that awaits a timer records its completion in 0 of 10, and the plugin's cleanup fires 10 of 10. A reviewer's sweep put the abandonment boundary below 50 ms — a 50 ms, 200 ms and 2000 ms handler are all lost, RECV 10/10 throughout — so the claim is if anything understated. A write made synchronously as the handler's first action lands regardless. That is the measured mechanism: the host dispatches turn-end and exits without awaiting the handler. What is NOT measured is the identification of the issue's original natural misses (6 of 8, recorded 2026-11-13 on an older host) with this mechanism. Neither this work (45/45 before, 30/30 after) nor the reviewer (1 miss in 75 turns on v2.3.0, 24/24 under load) could reproduce a natural miss on the current host. So this repo adds observability to TEST the hypothesis rather than assert a cause: the pass writes `auto_capture_start` synchronously before the model call, so a pass that reached the model call but never recorded `capture_cost` is a visible cut; disposal writes `auto_capture_dispose` when an armed instance observed no turn-end event — a PREDICTIVE line, since the event is delivered in every measured run and an idle restart between turns produces it too. A deliberate skip writes `auto_capture_skipped` and no start line, so `memory_status` renders skip, cut, and never-fired apart. These are NOT all the states: a pass cut during the context read or the known-rows read — the awaited `loadAll()` before the receipt — still writes nothing, so that band stays silent exactly as the original failure did. The receipt trades that band (measured 0.72 ms at 200 rows, 2.08 ms at 2000, warm) for not misreporting a healthy skip as a cut. Natural misses, when they recur, are then classified against these lines. `test/capture/capture-start-observable.test.ts` pins the receipt, the skip, the disposal flush, and the cut-outranks-dispose ordering.
|
|
25
|
+
|
|
24
26
|
- **The availability policy is measured against its alternatives, and against its own measuring stick.** `bun run bench:availability` (`bench/availability-results.md`) runs one capture pass over a 197-row store five times — no check, tag (as shipped), drop-at-read (the P3 preview), drop-hardened, and the original rule replayed from the pinned `362655c` module — with the byte budget swept over five sizes and the background resampled at 0/30/90/180 rows, because a claim measured at one budget or one store size is a claim about that budget. Tagging keeps all 10 new transport facts and retrieves 14 of 14 retrievable queries at every budget and every store size, where the original rule keeps 6 of 10 and retrieves 7 at every budget: that rule deleted four of ten new facts on a command mention alone, and a deleted fact cannot be retrieved. The ceiling is stated next to every recall figure and measured on the exact rows the arms retrieve: 14 of the 21 curated transport queries retrieve their own gold when that gold is the ONLY row in the store, so the tag arm's 14 is the achievable maximum and 9/21 was never 43% recall. The counterfactual is printed beside it — strip the keywords the capture reply carries and the ceiling falls to 9/21, because five of these pairs are retrievable only through the keyword list. A 25-case bank of every adversarial verdict this matcher has been found guilty of is re-decided on every run, one repo per case, and asserted in `bun test` because CI runs no bench. Writing those controls found two defects in the bench itself — verdicts keyed on `ts`, which is not unique when a pass writes rows in one millisecond, and a byte column summed across 21 queries and labelled per-block — and the corrected numbers are in the file. The report also states what it cannot measure: the check marks 6 of 16 rows a pass writes and 0 of 180 background rows, and that 0 is a fixture artefact rather than a base rate, because no seeded row quotes the tracked tree. It also tests the tag's justification directly: empty the tracked text and all 6 verdicts disappear, which is the property a read-time policy would keep and a delete would not.
|
|
25
27
|
|
|
26
28
|
## What has not been established
|
|
@@ -36,6 +36,31 @@ cd opencode-self-improvement && bun install
|
|
|
36
36
|
|
|
37
37
|
Then `git pull` and restart opencode to update.
|
|
38
38
|
|
|
39
|
+
## Dropping it into the plugins directory
|
|
40
|
+
|
|
41
|
+
Loose discovery reads `<config>/plugins/<name>/index.ts` and a sibling `tui.ts`,
|
|
42
|
+
and the repository root carries both shims for exactly that route. Discovery
|
|
43
|
+
copies nothing and installs nothing, so the directory needs its own dependencies:
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
cd "<config>/plugins/opencode-self-improvement" && bun install
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Without them the plugin fails to load, and the host reports it as `Plugin must
|
|
50
|
+
export a default definition with an id and an effect or setup function` — the
|
|
51
|
+
missing `zod` is the cause, not the export
|
|
52
|
+
([#464](https://github.com/abogartz/opencode-self-improvement/issues/464)). To see
|
|
53
|
+
which package could not be resolved, run the plugin once from a terminal inside the
|
|
54
|
+
affected project:
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
opencode run --standalone --print-logs "diagnostic"
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`run` needs a message: without one it stops with `You must provide a message`
|
|
61
|
+
before loading any plugin. The desktop plugin panel lists the plugin and says
|
|
62
|
+
nothing about the dependency. The package route above avoids the step entirely.
|
|
63
|
+
|
|
39
64
|
## Restart rules by host
|
|
40
65
|
|
|
41
66
|
A config edit needs a restart to take effect. On the desktop app, relaunching the
|
|
@@ -16,11 +16,12 @@ README points here rather than repeating the table.
|
|
|
16
16
|
|
|
17
17
|
## Common problems
|
|
18
18
|
|
|
19
|
-
The
|
|
19
|
+
The cases a session actually hits.
|
|
20
20
|
|
|
21
21
|
| Problem | Fix |
|
|
22
22
|
| --- | --- |
|
|
23
23
|
| `memory_*` tools not available | The plugin didn't load. Restart opencode and check the `plugins` entry in your config. |
|
|
24
|
+
| `Plugin must export a default definition with an id and an effect or setup function` | The export is not what is wrong: the module never evaluated, so the host saw no export at all. A loose copy under `<config>/plugins/<name>/` carries no `node_modules`, and `zod` cannot be resolved from it ([#464](https://github.com/abogartz/opencode-self-improvement/issues/464)). Run `bun install` in that directory, or install the package instead — `opencode plugin add opencode-self-improvement` resolves through `package.json` `exports` and gets its runtime dependencies from the npm plugin cache. The plugin also logs the package it could not resolve and the directory it loaded from, so the host log names the cause instead of the export. Read that log with `opencode run --standalone --print-logs "diagnostic"` — `run` needs a message, and without one it stops with `You must provide a message` before the plugin is loaded. The desktop **Project → Extensions → Plugins** panel names the plugin but does not show the missing package or this fix. |
|
|
24
25
|
| `memory_remember` says blocked | A gate rejected the write: a stale code reference, a cited path that doesn't exist in the repo, overlap with a superseded memory, or an ambiguous claim. The reason is in `memory_evidence`; rephrase against current code and retry. |
|
|
25
26
|
| `invalid arguments to memory_*` | The call didn't match the tool's input schema; nothing was done and the message names the offending fields. Gate blocks look different (`blocked at GATE (…)`). |
|
|
26
27
|
| `memory store is busy` | A store write exhausted its 5s lock-wait budget, so the mutation is refused rather than run unlocked. Retry after contention clears. An operation spanning several files or steps may have completed earlier steps; refusal is not a rollback of those steps. If the reply reports `PARTIAL`, inspect the named rows and `memory_evidence` / `memory_undo` before retrying. A process that is killed releases the lock when it dies — there is no stale window to wait out. |
|
package/index.ts
CHANGED
|
@@ -1,2 +1,48 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
// The root shim for loose plugin discovery: `<config>/plugins/<name>/index.ts`.
|
|
2
|
+
// Package installs resolve `package.json` `exports` "." here too.
|
|
3
|
+
//
|
|
4
|
+
// The import is dynamic and guarded because a loose copy carries no
|
|
5
|
+
// `node_modules`. An unresolvable runtime dependency — `zod`, imported eagerly
|
|
6
|
+
// by `src/tools/schema.ts` — then throws during evaluation, and the host blames
|
|
7
|
+
// the export instead: "Plugin must export a default definition with an id and an
|
|
8
|
+
// effect or setup function". Catching keeps the definition valid and logs the
|
|
9
|
+
// package that could not be resolved.
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import type { Plugin } from "@opencode/plugin/promise/plugin";
|
|
12
|
+
|
|
13
|
+
let loaded: typeof import("./src/index.ts") | undefined;
|
|
14
|
+
let loadError: unknown;
|
|
15
|
+
try {
|
|
16
|
+
loaded = await import("./src/index.ts");
|
|
17
|
+
} catch (err) {
|
|
18
|
+
loadError = err;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (loadError) {
|
|
22
|
+
// Runs before any hook exists, so the host log is the only surface. The
|
|
23
|
+
// directory names which copy of the plugin failed.
|
|
24
|
+
const where = fileURLToPath(new URL(".", import.meta.url));
|
|
25
|
+
const detail =
|
|
26
|
+
loadError instanceof Error ? loadError.message : String(loadError);
|
|
27
|
+
console.error(
|
|
28
|
+
`opencode-self-improvement: failed to load from ${where}: ${detail}`,
|
|
29
|
+
);
|
|
30
|
+
console.error(
|
|
31
|
+
"opencode-self-improvement: a loose copy under <config>/plugins/ needs its runtime dependencies — run `bun install` in that directory, or install the package with `opencode plugin add opencode-self-improvement`.",
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Only used when the import failed. The id is a literal, not `PLUGIN_ID`,
|
|
36
|
+
// because it has to be right in exactly the case where that module never
|
|
37
|
+
// evaluated — the host keys storage, status and diagnostics on it.
|
|
38
|
+
const unloaded: Plugin = {
|
|
39
|
+
id: "opencode-self-improvement",
|
|
40
|
+
async setup() {
|
|
41
|
+
console.error(
|
|
42
|
+
"opencode-self-improvement: loaded with no tools and no hooks — the module failed to evaluate, so nothing is active. Clear the load error above; the store stays empty until it is gone.",
|
|
43
|
+
);
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export const SelfImprovement: Plugin = loaded?.SelfImprovement ?? unloaded;
|
|
48
|
+
export default SelfImprovement;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.33.
|
|
3
|
+
"version": "0.33.8",
|
|
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
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
// Opt-in capture configuration and dispatch. Cooldowns remain process-wide;
|
|
2
2
|
// subscriptions and dispatch closures belong to one setup instance.
|
|
3
3
|
import type { Cleanup } from "@opencode/plugin/promise/plugin";
|
|
4
|
+
import { existsSync } from "node:fs";
|
|
4
5
|
import { cmpTs } from "../core/cmp-ts.ts";
|
|
6
|
+
import { evidenceDir } from "../core/config/paths.ts";
|
|
5
7
|
import { session, setCurrent } from "../core/state.ts";
|
|
6
8
|
import {
|
|
7
9
|
AUTO_CAPTURE_TAG,
|
|
@@ -22,7 +24,7 @@ import {
|
|
|
22
24
|
import { quarantineCandidate } from "../store/quarantine/quarantine.ts";
|
|
23
25
|
import { flattenMemoryText } from "../store/sanitize.ts";
|
|
24
26
|
import { redactSecrets } from "../store/secrets.ts";
|
|
25
|
-
import { record, recordCaptureLag } from "../telemetry/record.ts";
|
|
27
|
+
import { record, recordCaptureLag, recordSync } from "../telemetry/record.ts";
|
|
26
28
|
import { type AvailabilityIndex, availabilityIndex } from "./available.ts";
|
|
27
29
|
import { parseCandidates, parseModelRef } from "./candidates.ts";
|
|
28
30
|
import { claimVerdictFromContent } from "./checked.ts";
|
|
@@ -267,6 +269,16 @@ export function configureAutoCapture(
|
|
|
267
269
|
};
|
|
268
270
|
const inFlight = new Set<Promise<unknown>>();
|
|
269
271
|
const passPhases = new Set<PassPhase>();
|
|
272
|
+
// Observability counters, read at disposal. `turnEndSeen` counts the
|
|
273
|
+
// turn-end events this instance's subscription actually received; `passesStarted`
|
|
274
|
+
// counts the capture passes that began. Together they make the silent state
|
|
275
|
+
// interpretable: a process that exits with `turnEndSeen === 0 && passesStarted
|
|
276
|
+
// === 0` never got the event, which is a different fact from "a pass ran and
|
|
277
|
+
// found nothing" (a `capture_cost` line) and from "disabled" (the `plugin_load`
|
|
278
|
+
// heartbeat). Both are process-wide for this setup instance, not per-session:
|
|
279
|
+
// the question they answer is "did capture get a chance at all on this host."
|
|
280
|
+
let turnEndSeen = 0;
|
|
281
|
+
let passesStarted = 0;
|
|
270
282
|
function newPhase(): PassPhase {
|
|
271
283
|
return { pastModel: false, abandoned: false };
|
|
272
284
|
}
|
|
@@ -614,6 +626,40 @@ export function configureAutoCapture(
|
|
|
614
626
|
attested,
|
|
615
627
|
);
|
|
616
628
|
const promptChars = capturePrompt.length;
|
|
629
|
+
// The receipt that a capture pass began, written SYNCHRONOUSLY at the
|
|
630
|
+
// last point before the model call — after every skip decision, so a turn
|
|
631
|
+
// that deliberately skipped (no signal, thin transcript) records
|
|
632
|
+
// `auto_capture_skipped` and never this line. `auto_capture_start` means
|
|
633
|
+
// exactly one thing: the pass reached the model call. It must not be
|
|
634
|
+
// async: an async write here yields the event loop several times and
|
|
635
|
+
// measurably shrinks the window the model call has to finish before the
|
|
636
|
+
// host exits. It sits after the context read and the known-rows read on
|
|
637
|
+
// purpose, so a start line with no `capture_cost` is a pass cut AT the
|
|
638
|
+
// model call — the state otherwise byte-identical to "disabled" or "ran
|
|
639
|
+
// and found nothing." The cost of that placement: a pass cut DURING the
|
|
640
|
+
// context read or the known-rows read, before this line, still leaves no
|
|
641
|
+
// trace, so that band is silent by design (see the evidence doc). The
|
|
642
|
+
// write is guarded like the disposal flush: an unwritable evidence log
|
|
643
|
+
// (read-only mount, foreign owner, ENOSPC) must never abort the pass
|
|
644
|
+
// before its model call — observability cannot be allowed to cause the
|
|
645
|
+
// loss it exists to detect.
|
|
646
|
+
passesStarted++;
|
|
647
|
+
try {
|
|
648
|
+
recordSync(
|
|
649
|
+
"auto_capture_start",
|
|
650
|
+
{
|
|
651
|
+
trigger,
|
|
652
|
+
...(modelTag ? { model: modelTag } : {}),
|
|
653
|
+
},
|
|
654
|
+
true,
|
|
655
|
+
sid,
|
|
656
|
+
captureGate.evidenceContext,
|
|
657
|
+
);
|
|
658
|
+
} catch {
|
|
659
|
+
// The receipt is best-effort. A failed write here must not stop the
|
|
660
|
+
// model call or tear down the subscription; the pass simply runs
|
|
661
|
+
// without leaving its start line.
|
|
662
|
+
}
|
|
617
663
|
const out = await generateApi.text({
|
|
618
664
|
model,
|
|
619
665
|
prompt: capturePrompt,
|
|
@@ -1084,6 +1130,11 @@ export function configureAutoCapture(
|
|
|
1084
1130
|
signal: controller.signal,
|
|
1085
1131
|
})) {
|
|
1086
1132
|
if (!captureTriggerFor(raw)) continue;
|
|
1133
|
+
// The turn-end event reached this subscription. Counted before
|
|
1134
|
+
// the session-id and cooldown checks so a delivered-but-cooled event
|
|
1135
|
+
// still proves the event arrived — only a zero here means no turn-end
|
|
1136
|
+
// event reached this instance, the only case the disposal flush records.
|
|
1137
|
+
turnEndSeen++;
|
|
1087
1138
|
const sid = captureSessionID(raw);
|
|
1088
1139
|
if (sid === undefined) continue;
|
|
1089
1140
|
setCurrent({ sessionID: sid });
|
|
@@ -1139,6 +1190,34 @@ export function configureAutoCapture(
|
|
|
1139
1190
|
// the unanswered ones, drain the answered ones.
|
|
1140
1191
|
controller.abort();
|
|
1141
1192
|
await drainInFlight();
|
|
1193
|
+
// Disposal flush: the one capture signal that does not depend on a
|
|
1194
|
+
// turn-end event arriving. If an armed instance is disposed having
|
|
1195
|
+
// observed no turn-end event and started no pass, record that absence.
|
|
1196
|
+
// This line is PREDICTIVE, not observed: on current host versions the
|
|
1197
|
+
// turn-end event reaches the subscription in every measured run, and an
|
|
1198
|
+
// idle instance restarted between turns produces it too — so it names the
|
|
1199
|
+
// state the original report inferred, never an accusation of where a
|
|
1200
|
+
// dispatched event went. Guarded and existence-checked: a disposed
|
|
1201
|
+
// instance must not resurrect a store its caller removed (the teardown
|
|
1202
|
+
// contract), and a failed heartbeat must never turn cleanup into a throw.
|
|
1203
|
+
if (turnEndSeen === 0 && passesStarted === 0) {
|
|
1204
|
+
try {
|
|
1205
|
+
if (existsSync(evidenceDir()))
|
|
1206
|
+
await record(
|
|
1207
|
+
"auto_capture_dispose",
|
|
1208
|
+
{
|
|
1209
|
+
armed: true,
|
|
1210
|
+
turn_end_events: 0,
|
|
1211
|
+
passes: 0,
|
|
1212
|
+
reason: "no_turn_end_observed",
|
|
1213
|
+
subscribed: `[${CAPTURE_EVENT_TYPES.join(",")}]`,
|
|
1214
|
+
},
|
|
1215
|
+
false,
|
|
1216
|
+
);
|
|
1217
|
+
} catch {
|
|
1218
|
+
// observability must not break teardown
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1142
1221
|
};
|
|
1143
1222
|
|
|
1144
1223
|
// The compaction trigger needs no extra subscription: the session
|
package/src/inject/budget.ts
CHANGED
|
@@ -54,20 +54,20 @@ export function cappedFrontier(
|
|
|
54
54
|
};
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
//
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
)
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
57
|
+
// Keep original indices: distinct stored rows can render as the same line.
|
|
58
|
+
export function fittingLineIndices(
|
|
59
|
+
lines: string[],
|
|
60
|
+
available: number,
|
|
61
|
+
order = lines.map((_, i) => i),
|
|
62
|
+
): number[] {
|
|
63
|
+
const kept: number[] = [];
|
|
64
|
+
for (const i of order) {
|
|
65
|
+
const cost = 1 + lines[i].length;
|
|
66
|
+
if (cost > available) continue;
|
|
67
|
+
available -= cost;
|
|
68
|
+
kept.push(i);
|
|
69
|
+
}
|
|
70
|
+
return kept;
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
// Trim an injection block to `budget` characters at WHOLE-line boundaries:
|
|
@@ -76,16 +76,10 @@ export function injectedRows(
|
|
|
76
76
|
// when NOTHING but header lines survived — a dangling "## Relevant durable
|
|
77
77
|
// memory" over zero memories is noise, not memory.
|
|
78
78
|
export function capToBudget(block: string, budget: number): string {
|
|
79
|
-
const lines = block.split("\n");
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
if (len + line.length + 1 > budget) continue; // skip over-long lines, keep scanning
|
|
86
|
-
kept.push(line);
|
|
87
|
-
len += line.length + 1;
|
|
88
|
-
}
|
|
89
|
-
if (kept.every((l) => l.startsWith("## "))) return "";
|
|
90
|
-
return kept.join("\n");
|
|
79
|
+
const [header, ...lines] = block.split("\n");
|
|
80
|
+
if (header.length > budget) return "";
|
|
81
|
+
const kept = fittingLineIndices(lines, budget - header.length);
|
|
82
|
+
const result = [header, ...kept.map((i) => lines[i])];
|
|
83
|
+
if (result.every((line) => line.startsWith("## "))) return "";
|
|
84
|
+
return result.join("\n");
|
|
91
85
|
}
|
package/src/inject/epochs.ts
CHANGED
|
@@ -6,7 +6,6 @@ import { isInjectable } from "../store/model/predicates.ts";
|
|
|
6
6
|
import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
|
|
7
7
|
import { SESSION_CAP, SessionLru } from "../core/lru.ts";
|
|
8
8
|
import { captureEvidenceContext, record } from "../telemetry/record.ts";
|
|
9
|
-
import { capToBudget, injectedRows } from "./budget.ts";
|
|
10
9
|
import { systemDigest } from "./digest.ts";
|
|
11
10
|
import { storeVersion } from "./version.ts";
|
|
12
11
|
import { isUserGuided, selectRelevant } from "../recall/relevant.ts";
|
|
@@ -220,19 +219,7 @@ export function createInjectionEpochs({
|
|
|
220
219
|
: {}),
|
|
221
220
|
},
|
|
222
221
|
);
|
|
223
|
-
|
|
224
|
-
// `budget` and builds the block as header + Σ(1 + line) over lines it
|
|
225
|
-
// accepted while that running sum stayed ≤ budget, and every line length is
|
|
226
|
-
// non-negative. So a non-empty `sel.block` is already ≤ budget, capToBudget
|
|
227
|
-
// keeps every line, and this call returns its argument unchanged. No test
|
|
228
|
-
// can reach a different result; it stays only as a byte bound on the text
|
|
229
|
-
// that rides the prompt if a future caller stops budgeting inside the
|
|
230
|
-
// selector.
|
|
231
|
-
const block = sel.block ? capToBudget(sel.block, budget) : "";
|
|
232
|
-
// Refs the ACTUALLY-injected rows assert (paths + commands), the join key
|
|
233
|
-
// for attribution. Derived from the budget-surviving rows, not the wider
|
|
234
|
-
// candidate pool — crediting paths the model never saw would overclaim.
|
|
235
|
-
const rode = injectedRows(block, sel.selected, sel.rendered);
|
|
222
|
+
const { block, shown: rode } = sel;
|
|
236
223
|
const prefix = [...parts, block].join("\u0000");
|
|
237
224
|
// Ledger terms/identities belong to the stored rows, but coverage refs
|
|
238
225
|
// must describe only the text the model actually received.
|
package/src/inject/pull.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { type Memory } from "../store/model/memory.ts";
|
|
|
4
4
|
import { isInjectable } from "../store/model/predicates.ts";
|
|
5
5
|
import { readerFromSid, visibleTo } from "../store/model/visibility.ts";
|
|
6
6
|
import { injectBudget } from "../core/config/budgets.ts";
|
|
7
|
-
import { FRAME,
|
|
7
|
+
import { FRAME, fittingLineIndices } from "./budget.ts";
|
|
8
8
|
import { formatMemory } from "./format.ts";
|
|
9
9
|
import { type UseSignals, argText } from "../recall/relevant.ts";
|
|
10
10
|
import { scoreMemories } from "../recall/score.ts";
|
|
@@ -278,15 +278,11 @@ export async function contextualPull(
|
|
|
278
278
|
: top;
|
|
279
279
|
if (!merged.length) return [];
|
|
280
280
|
// Held to the injection budget too: three long rows were ~12 KB per call.
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
);
|
|
285
|
-
if (
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
// drop rows, and crediting a memory the model never saw would inflate it.
|
|
289
|
-
return injectedRows(block, merged);
|
|
290
|
-
}
|
|
291
|
-
return [];
|
|
281
|
+
if (typeof output.output !== "string") return [];
|
|
282
|
+
const header = `## Related durable memory (pull)${FRAME}`;
|
|
283
|
+
const lines = merged.map(formatMemory);
|
|
284
|
+
const kept = fittingLineIndices(lines, budget - header.length);
|
|
285
|
+
if (!kept.length) return [];
|
|
286
|
+
output.output += `\n${[header, ...kept.map((i) => lines[i])].join("\n")}`;
|
|
287
|
+
return kept.map((i) => merged[i]);
|
|
292
288
|
}
|
package/src/recall/dedupe.ts
CHANGED
|
@@ -220,6 +220,13 @@ export interface GroupedWindow {
|
|
|
220
220
|
* restate. `groups` carries the rows themselves: a later clash overwrites a
|
|
221
221
|
* slot in the window, and a group keyed on that slot would re-point at
|
|
222
222
|
* whatever landed there.
|
|
223
|
+
*
|
|
224
|
+
* A candidate can win more than one collapse clash at once — a substitution of
|
|
225
|
+
* one kept row and an exact copy of another. It then takes the first slot and
|
|
226
|
+
* vacates the rest, because a row left standing beside the copy that replaced
|
|
227
|
+
* it returns the same text twice and costs a distinct row its slot. The scan
|
|
228
|
+
* only stops at the first clash with grouping off; with grouping on it walks
|
|
229
|
+
* the whole window, so every clash is visible here.
|
|
223
230
|
*/
|
|
224
231
|
export function dedupeWindowGrouped(
|
|
225
232
|
ranked: Memory[],
|
|
@@ -265,7 +272,18 @@ export function dedupeWindowGrouped(
|
|
|
265
272
|
// a slot on a duplicate while a distinct row waits outside — the exact loss
|
|
266
273
|
// this pass exists to prevent. A collapse therefore outranks a group.
|
|
267
274
|
let addition = -1; // first clash that names something new
|
|
268
|
-
let collapse = -1; //
|
|
275
|
+
let collapse = -1; // FIRST clash that is a copy or a correction
|
|
276
|
+
// Every collapse clash the candidate wins, not just the first. A row can
|
|
277
|
+
// beat two kept rows in one pass and the two classes differ: it may be a
|
|
278
|
+
// substitution of one and an exact copy of another. Taking only the first
|
|
279
|
+
// slot leaves the copy it beat standing beside it, so the window returns
|
|
280
|
+
// the same text twice and a distinct row outside never arrives.
|
|
281
|
+
const beaten: number[] = [];
|
|
282
|
+
// Collapse slots emptied because the candidate took their row's meaning.
|
|
283
|
+
const vacated = new Set<number>();
|
|
284
|
+
// A kept row the candidate loses to. One loss is enough to keep the
|
|
285
|
+
// candidate out: the newest copy is the one that rides.
|
|
286
|
+
let outranked = false;
|
|
269
287
|
for (const pos of kept.keys()) {
|
|
270
288
|
const k = kept[pos]!;
|
|
271
289
|
if (
|
|
@@ -284,8 +302,13 @@ export function dedupeWindowGrouped(
|
|
|
284
302
|
if (addition < 0) addition = pos;
|
|
285
303
|
continue;
|
|
286
304
|
}
|
|
287
|
-
|
|
288
|
-
|
|
305
|
+
if (!groupAdditions) {
|
|
306
|
+
collapse = pos;
|
|
307
|
+
break;
|
|
308
|
+
}
|
|
309
|
+
if (collapse < 0) collapse = pos;
|
|
310
|
+
if (ranked[k]!.ts >= ranked[i]!.ts) outranked = true;
|
|
311
|
+
else beaten.push(pos);
|
|
289
312
|
}
|
|
290
313
|
if (
|
|
291
314
|
collapse < 0 &&
|
|
@@ -295,10 +318,24 @@ export function dedupeWindowGrouped(
|
|
|
295
318
|
) {
|
|
296
319
|
kept.push(i);
|
|
297
320
|
} else if (collapse >= 0) {
|
|
298
|
-
|
|
321
|
+
// Decided before any slot changes. A candidate that loses to a newer kept
|
|
322
|
+
// row does not ride, so it must not overwrite the older row it also
|
|
323
|
+
// beat: that would drop a row the candidate never outranked.
|
|
324
|
+
// A winner takes the FIRST clashing slot, keeping its rank, and every
|
|
325
|
+
// other slot it won is removed so the scan refills it.
|
|
326
|
+
const rides = !outranked && ranked[i]!.ts > ranked[kept[collapse]!]!.ts;
|
|
327
|
+
if (rides) {
|
|
328
|
+
kept[collapse] = i;
|
|
329
|
+
for (const pos of beaten) {
|
|
330
|
+
if (pos !== collapse) vacated.add(pos);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
299
333
|
} else if (addition >= 0) {
|
|
300
334
|
if (ranked[i]!.ts > ranked[kept[addition]!]!.ts) kept[addition] = i;
|
|
301
335
|
} else kept.push(i);
|
|
336
|
+
// Removed after the branch: `collapse` and `beaten` are positions inside
|
|
337
|
+
// `kept`, and splicing mid-scan would move them.
|
|
338
|
+
for (const pos of [...vacated].sort((a, b) => b - a)) kept.splice(pos, 1);
|
|
302
339
|
}
|
|
303
340
|
const rows = kept.map((i) => ranked[i]!);
|
|
304
341
|
// Families are recomputed from the window instead of accumulated during the
|
package/src/recall/relevant.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { loadAll } from "../store/files/load.ts";
|
|
|
3
3
|
import { type Memory } from "../store/model/memory.ts";
|
|
4
4
|
import { isInjectable } from "../store/model/predicates.ts";
|
|
5
5
|
import { readerFromSid, visibleTo } from "../store/model/visibility.ts";
|
|
6
|
-
import { FRAME } from "../inject/budget.ts";
|
|
6
|
+
import { FRAME, fittingLineIndices } from "../inject/budget.ts";
|
|
7
7
|
import { formatMemory } from "../inject/format.ts";
|
|
8
8
|
import { conflictLine, findConstant, valuesAgree } from "./conflicts.ts";
|
|
9
9
|
import { RESTATABLE_TAG, USER_GUIDED_TAG } from "../core/tags.ts";
|
|
@@ -144,6 +144,7 @@ export async function selectRelevant(
|
|
|
144
144
|
): Promise<{
|
|
145
145
|
block: string;
|
|
146
146
|
selected: Memory[];
|
|
147
|
+
shown: Memory[];
|
|
147
148
|
rendered: ReadonlyMap<Memory, Memory>;
|
|
148
149
|
}> {
|
|
149
150
|
// Repo-scoped: model-facing reads see the caller's repo + global rows
|
|
@@ -177,7 +178,7 @@ export async function selectRelevant(
|
|
|
177
178
|
const top = text ? scoreMemories(text, mems, limit, use) : [];
|
|
178
179
|
const rest = top.filter((m) => !guided.includes(m));
|
|
179
180
|
const merged = [...guided, ...rest];
|
|
180
|
-
if (!merged.length) return { block: "", selected: [], rendered };
|
|
181
|
+
if (!merged.length) return { block: "", selected: [], shown: [], rendered };
|
|
181
182
|
const lines = merged.map((m) => formatMemory(rendered.get(m) ?? m));
|
|
182
183
|
// The caveat must describe the rows that ACTUALLY ride, so it cannot be fixed
|
|
183
184
|
// before the budget runs (it used to be, and a budget that dropped the only
|
|
@@ -219,11 +220,7 @@ export async function selectRelevant(
|
|
|
219
220
|
// keep scanning), applied BEFORE the re-order so relevance still decides.
|
|
220
221
|
// A block left with nothing but its header renders as nothing — a dangling
|
|
221
222
|
// "## Relevant durable memory" over zero memories is noise, not memory. A
|
|
222
|
-
// header
|
|
223
|
-
// the header width, so no line can clear the test below and the empty
|
|
224
|
-
// `shown` returns exactly what an explicit header check would.
|
|
225
|
-
let used = fitHeader.length;
|
|
226
|
-
shown = [];
|
|
223
|
+
// header wider than the budget leaves no space for any row.
|
|
227
224
|
// PRIORITY decides who rides, and a restatement now sits last in that
|
|
228
225
|
// order — the tree already states it, so a slot spent here is a slot not
|
|
229
226
|
// spent on something the files do not hold. `merged` stays in score order:
|
|
@@ -239,17 +236,14 @@ export async function selectRelevant(
|
|
|
239
236
|
(a, b) =>
|
|
240
237
|
(demoted(merged[a]) ? 1 : 0) - (demoted(merged[b]) ? 1 : 0) || a - b,
|
|
241
238
|
);
|
|
242
|
-
|
|
243
|
-
const line = lines[i] ?? "";
|
|
244
|
-
if (used + 1 + line.length > budget) continue;
|
|
245
|
-
shown.push(i);
|
|
246
|
-
used += 1 + line.length;
|
|
247
|
-
}
|
|
239
|
+
shown = fittingLineIndices(lines, budget - fitHeader.length, fitOrder);
|
|
248
240
|
// `selected` keeps the PRE-budget selection even here: the evidence field
|
|
249
241
|
// `guided=` answers "did the selector pick it", `guidedRode=` answers "did
|
|
250
242
|
// it survive". Returning [] would make a total trim read as "never picked".
|
|
251
|
-
if (!shown.length)
|
|
243
|
+
if (!shown.length)
|
|
244
|
+
return { block: "", selected: merged, shown: [], rendered };
|
|
252
245
|
}
|
|
246
|
+
const kept = new Set(shown);
|
|
253
247
|
shown.sort((a, b) => {
|
|
254
248
|
const ma = merged[a];
|
|
255
249
|
const mb = merged[b];
|
|
@@ -275,6 +269,7 @@ export async function selectRelevant(
|
|
|
275
269
|
...shown.map((i) => lines[i] ?? ""),
|
|
276
270
|
].join("\n"),
|
|
277
271
|
selected: merged,
|
|
272
|
+
shown: merged.filter((_, i) => kept.has(i)),
|
|
278
273
|
rendered,
|
|
279
274
|
};
|
|
280
275
|
}
|
package/src/status/metrics.ts
CHANGED
|
@@ -177,6 +177,21 @@ export interface CaptureHealth {
|
|
|
177
177
|
* only this line, so the inert verdict must consult it ( F1).
|
|
178
178
|
*/
|
|
179
179
|
lastExecuted: string | null;
|
|
180
|
+
/**
|
|
181
|
+
* Newest `auto_capture_start` receipt: a pass reached the model call. It is
|
|
182
|
+
* written only after every skip decision, so a deliberate skip never sets it.
|
|
183
|
+
* A start with no `capture_cost` means completion was unobserved — a different
|
|
184
|
+
* fact from a deliberate skip (`auto_capture_skipped`, no start line) and from
|
|
185
|
+
* a completed run (a `capture_lag` receipt).
|
|
186
|
+
*/
|
|
187
|
+
lastStarted?: string | null;
|
|
188
|
+
/**
|
|
189
|
+
* Newest `auto_capture_dispose` flush: an armed instance was disposed with no
|
|
190
|
+
* turn-end event observed and no pass started. Predictive — built for the state
|
|
191
|
+
* the original report inferred, not one observed on a released host; an idle
|
|
192
|
+
* instance restarted between turns produces it too.
|
|
193
|
+
*/
|
|
194
|
+
lastMissed?: string | null;
|
|
180
195
|
}
|
|
181
196
|
|
|
182
197
|
const CAPTURE_STATES: readonly CaptureHealthState[] = [
|
|
@@ -199,6 +214,8 @@ export function captureHealth(
|
|
|
199
214
|
let blocked = 0;
|
|
200
215
|
let lastFired: string | null = null;
|
|
201
216
|
let lastExecuted: string | null = null;
|
|
217
|
+
let lastStarted: string | null = null;
|
|
218
|
+
let lastMissed: string | null = null;
|
|
202
219
|
for (const line of lines) {
|
|
203
220
|
const f = parseLine(line);
|
|
204
221
|
if (!f) continue;
|
|
@@ -223,6 +240,20 @@ export function captureHealth(
|
|
|
223
240
|
lastExecuted = ts;
|
|
224
241
|
continue;
|
|
225
242
|
}
|
|
243
|
+
if (ev === "auto_capture_start") {
|
|
244
|
+
// A pass began (the turn-end event reached the plugin). Tracked apart from
|
|
245
|
+
// lastFired: a start with no completion is a cut, not a verdict, so
|
|
246
|
+
// it must not make a never-completed capture look "fired and alive."
|
|
247
|
+
if (ts && ts >= cutoff && (!lastStarted || ts > lastStarted))
|
|
248
|
+
lastStarted = ts;
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
if (ev === "auto_capture_dispose") {
|
|
252
|
+
// The disposal flush: armed, disposed, never a turn-end event.
|
|
253
|
+
if (ts && ts >= cutoff && (!lastMissed || ts > lastMissed))
|
|
254
|
+
lastMissed = ts;
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
226
257
|
if (!ev.startsWith("auto_capture_")) continue;
|
|
227
258
|
if (ts && ts < cutoff) continue;
|
|
228
259
|
if (ev.endsWith("promoted")) rows++;
|
|
@@ -234,5 +265,13 @@ export function captureHealth(
|
|
|
234
265
|
blocked++;
|
|
235
266
|
if (ts && (!lastFired || ts > lastFired)) lastFired = ts;
|
|
236
267
|
}
|
|
237
|
-
return {
|
|
268
|
+
return {
|
|
269
|
+
state,
|
|
270
|
+
rows,
|
|
271
|
+
blocked,
|
|
272
|
+
lastFired,
|
|
273
|
+
lastExecuted,
|
|
274
|
+
lastStarted,
|
|
275
|
+
lastMissed,
|
|
276
|
+
};
|
|
238
277
|
}
|
package/src/status/report.ts
CHANGED
|
@@ -177,10 +177,32 @@ export function captureLines(c: CaptureHealth): string[] {
|
|
|
177
177
|
// `capture_lag` completion receipt. A successful capture whose model
|
|
178
178
|
// returned `[]` writes only the receipt, and is alive, not inert
|
|
179
179
|
// ( F1).
|
|
180
|
-
if (!c.lastExecuted && c.rows === 0 && c.blocked === 0)
|
|
180
|
+
if (!c.lastExecuted && c.rows === 0 && c.blocked === 0) {
|
|
181
|
+
// No completion, no promoted row, no refusal in the window. Rank the
|
|
182
|
+
// remaining signals by SEVERITY, never by recency: a later benign line
|
|
183
|
+
// from another instance must not overwrite an earlier loss. These can
|
|
184
|
+
// coexist in one 30-day window (different sessions and instances), so
|
|
185
|
+
// precedence is fixed:
|
|
186
|
+
// 1. a pass reached the model call but recorded no verdict (lastStarted)
|
|
187
|
+
// — an observed fact and a real loss, so it wins outright;
|
|
188
|
+
// 2. an armed instance disposed with no turn-end event observed
|
|
189
|
+
// (lastMissed) — a predictive absence, weaker than an observed cut;
|
|
190
|
+
// 3. nothing ran at all.
|
|
191
|
+
// A completion anywhere in the window (capture_cost/capture_lag, a
|
|
192
|
+
// promoted row, a refusal) is reported as alive above; that masks a
|
|
193
|
+
// same-window cut, a known limitation stated here, not a verdict.
|
|
194
|
+
if (c.lastStarted)
|
|
195
|
+
return [
|
|
196
|
+
" auto-capture: ARMED — a pass reached the model call but recorded no verdict; the turn-end event arrived and the pass did not complete.",
|
|
197
|
+
];
|
|
198
|
+
if (c.lastMissed)
|
|
199
|
+
return [
|
|
200
|
+
" auto-capture: ARMED BUT NEVER FIRED — no turn-end event was observed before disposal; this state has not been seen on a released host (an idle restart also produces it).",
|
|
201
|
+
];
|
|
181
202
|
return [
|
|
182
203
|
" auto-capture: ARMED BUT NEVER FIRED — capture is on, no auto_capture_* or capture_lag lines in the last 30d",
|
|
183
204
|
];
|
|
205
|
+
}
|
|
184
206
|
const fired = c.lastFired ?? c.lastExecuted;
|
|
185
207
|
return [
|
|
186
208
|
` auto-capture: on, last fired ${fired ? ago(fired) : "now"}, ${c.rows} rows, ${c.blocked} refused`,
|
package/src/telemetry/record.ts
CHANGED
|
@@ -1,13 +1,24 @@
|
|
|
1
1
|
// Evidence log writer. One logfmt line per event, appended in hook order to
|
|
2
2
|
// ~/.config/opencode/memory/evidence/<date>.logfmt. Evidence is DATA: never
|
|
3
3
|
// injected into chat, and stored outside every repo.
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
appendFileSync,
|
|
6
|
+
closeSync,
|
|
7
|
+
constants,
|
|
8
|
+
existsSync,
|
|
9
|
+
fchmodSync,
|
|
10
|
+
fstatSync,
|
|
11
|
+
mkdirSync,
|
|
12
|
+
openSync,
|
|
13
|
+
realpathSync,
|
|
14
|
+
} from "node:fs";
|
|
5
15
|
import { dirname, join, resolve } from "node:path";
|
|
6
16
|
import { createHash } from "node:crypto";
|
|
7
17
|
import { evidenceDir } from "../core/config/paths.ts";
|
|
8
18
|
import { dateStr } from "../core/time.ts";
|
|
9
|
-
import { formatLine } from "../core/logfmt/format.ts";
|
|
19
|
+
import { formatLine, IS_WINDOWS } from "../core/logfmt/format.ts";
|
|
10
20
|
import { appendLog } from "../core/logfmt/publish.ts";
|
|
21
|
+
import { tightenDirectory } from "../core/permissions.ts";
|
|
11
22
|
import {
|
|
12
23
|
repoScope,
|
|
13
24
|
sessionScope,
|
|
@@ -135,15 +146,21 @@ export function targetRepoFields(target: {
|
|
|
135
146
|
: { repo: "global", repoPath: undefined };
|
|
136
147
|
}
|
|
137
148
|
|
|
138
|
-
|
|
149
|
+
// Builds one evidence line exactly as `record` would, synchronously. Split out
|
|
150
|
+
// so `recordSync` can flush a line without yielding the event loop — the
|
|
151
|
+
// capture-start receipt must land before the host can cut the handler, and the
|
|
152
|
+
// async `appendLog` path (mkdir + open + chmod + stat + append + close) yields
|
|
153
|
+
// several times, which measurably shrinks the window the capture model call has
|
|
154
|
+
// to finish on a fast-exiting `opencode run`.
|
|
155
|
+
function buildEvidenceLine(
|
|
139
156
|
ev: EvidenceEvent,
|
|
140
|
-
fields: Record<string, unknown
|
|
141
|
-
includeContext
|
|
157
|
+
fields: Record<string, unknown>,
|
|
158
|
+
includeContext: boolean,
|
|
142
159
|
sessionID?: string,
|
|
143
160
|
context?: EvidenceContext,
|
|
144
|
-
):
|
|
161
|
+
): string {
|
|
145
162
|
const { sid, call, scope } = context ?? captureEvidenceContext(sessionID);
|
|
146
|
-
|
|
163
|
+
return formatLine({
|
|
147
164
|
ev,
|
|
148
165
|
ts: new Date().toISOString(),
|
|
149
166
|
// A captured unresolved owner still needs a privacy label: without sid or
|
|
@@ -157,9 +174,69 @@ export async function record(
|
|
|
157
174
|
...(scope ? { repo: scope.key, repoPath: scope.path } : {}),
|
|
158
175
|
...scrubFields(fields),
|
|
159
176
|
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export async function record(
|
|
180
|
+
ev: EvidenceEvent,
|
|
181
|
+
fields: Record<string, unknown> = {},
|
|
182
|
+
includeContext = true,
|
|
183
|
+
sessionID?: string,
|
|
184
|
+
context?: EvidenceContext,
|
|
185
|
+
): Promise<void> {
|
|
186
|
+
const line = buildEvidenceLine(
|
|
187
|
+
ev,
|
|
188
|
+
fields,
|
|
189
|
+
includeContext,
|
|
190
|
+
sessionID,
|
|
191
|
+
context,
|
|
192
|
+
);
|
|
160
193
|
await appendLog(join(evidenceDir(), `${dateStr()}.logfmt`), line);
|
|
161
194
|
}
|
|
162
195
|
|
|
196
|
+
/**
|
|
197
|
+
* Synchronous counterpart to `record`. Use ONLY where a write must land before
|
|
198
|
+
* the process can be cut — currently the capture-start receipt. It does not
|
|
199
|
+
* yield, so the host's exit logic (also on the event loop) cannot preempt it,
|
|
200
|
+
* and it leaves the model call's teardown window intact. Same line shape and
|
|
201
|
+
* redaction as `record`, and the same file protections as `appendLog`: the
|
|
202
|
+
* directory is tightened, the file is opened `O_NOFOLLOW` and its mode is
|
|
203
|
+
* narrowed to `0o600` before the append.
|
|
204
|
+
*/
|
|
205
|
+
export function recordSync(
|
|
206
|
+
ev: EvidenceEvent,
|
|
207
|
+
fields: Record<string, unknown> = {},
|
|
208
|
+
includeContext = true,
|
|
209
|
+
sessionID?: string,
|
|
210
|
+
context?: EvidenceContext,
|
|
211
|
+
): void {
|
|
212
|
+
const dir = evidenceDir();
|
|
213
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
214
|
+
tightenDirectory(dir);
|
|
215
|
+
const line = buildEvidenceLine(
|
|
216
|
+
ev,
|
|
217
|
+
fields,
|
|
218
|
+
includeContext,
|
|
219
|
+
sessionID,
|
|
220
|
+
context,
|
|
221
|
+
);
|
|
222
|
+
const next = line.endsWith("\n") ? line : `${line}\n`;
|
|
223
|
+
const file = join(dir, `${dateStr()}.logfmt`);
|
|
224
|
+
const fd = openSync(
|
|
225
|
+
file,
|
|
226
|
+
constants.O_WRONLY |
|
|
227
|
+
constants.O_APPEND |
|
|
228
|
+
constants.O_CREAT |
|
|
229
|
+
(constants.O_NOFOLLOW ?? 0),
|
|
230
|
+
0o600,
|
|
231
|
+
);
|
|
232
|
+
try {
|
|
233
|
+
if (!IS_WINDOWS) fchmodSync(fd, fstatSync(fd).mode & 0o600);
|
|
234
|
+
appendFileSync(fd, next);
|
|
235
|
+
} finally {
|
|
236
|
+
closeSync(fd);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
163
240
|
export function contentHash(content: string): string {
|
|
164
241
|
return createHash("sha1").update(content).digest("hex").slice(0, 12);
|
|
165
242
|
}
|