opencode-self-improvement 0.14.18 → 0.14.20
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 +35 -15
- package/package.json +1 -1
- package/src/capture.ts +3 -16
- package/src/gates.ts +14 -4
- package/src/host.ts +97 -0
- package/src/index.ts +65 -388
- package/src/init.ts +3 -3
- package/src/inject.ts +5 -8
- package/src/injection-epochs.ts +313 -0
- package/src/logfmt.ts +10 -4
- package/src/resolver.ts +2 -4
- package/src/state.ts +8 -0
- package/src/triggers.ts +41 -3
- package/src/types.ts +2 -2
package/README.md
CHANGED
|
@@ -4,6 +4,8 @@ Durable memory for [opencode](https://opencode.ai): the decisions, commands and
|
|
|
4
4
|
|
|
5
5
|
Every memory passes four write gates, injection is budgeted and cache-stable, and nothing is ever deleted — updates supersede and `memory_undo` rolls back.
|
|
6
6
|
|
|
7
|
+
Every figure in this README carries a provenance marker: **measured** (read off a live store), **bench** (a deterministic synthetic workload, reproducible with the command printed under the table), or **illustrative** (sample output showing shape, not a measurement). A number without a marker is a claim that has not been checked.
|
|
8
|
+
|
|
7
9
|
## Quick start
|
|
8
10
|
|
|
9
11
|
**1. Add the plugin** to `~/.config/opencode/opencode.jsonc` (global) or a project `opencode.jsonc`:
|
|
@@ -15,7 +17,7 @@ Every memory passes four write gates, injection is budgeted and cache-stable, an
|
|
|
15
17
|
}
|
|
16
18
|
```
|
|
17
19
|
|
|
18
|
-
**2. Restart opencode.** It installs the package and its dependencies at startup, and the plugin installs its own slash commands.
|
|
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.
|
|
19
21
|
|
|
20
22
|
**3. Run `/repo-init`** in each repo you work in. It indexes the code graph, stores the test / build / lint / typecheck commands as memories, and writes an init stamp tied to the current git head. Rerun `/repo-init force` after a refactor.
|
|
21
23
|
|
|
@@ -36,7 +38,7 @@ After that, memory is just conversation: ask the agent to remember something and
|
|
|
36
38
|
- **`/repo-init`** — per-repo setup: code graph index plus build/test commands, keyed to the git head.
|
|
37
39
|
- **Write gates** — code references are verified against your actual repo, near-duplicates are collapsed, contradictions with superseded memories are rejected. Blocked writes are logged with a reason in `memory_evidence`, which reads one real calendar day inside `evidence/` at a time — its `date` is a date, never a path.
|
|
38
40
|
- **Memory-aware compaction** — durable memories are handed to the compaction summarizer, so a long session keeps its facts.
|
|
39
|
-
- **Auto-capture (opt-in)** — on the
|
|
41
|
+
- **Auto-capture (experimental, opt-in)** — in progress and **not working yet**. The design: on the turn-end and compaction triggers, one cheap model pass per trigger proposes candidates, which face the same write gates, with a 5-minute cooldown per session and trigger bounding the spend. What is not true today: it has never been observed firing on a live opencode 2.x store, so enabling it may cost model calls and store nothing. See [Auto-capture is experimental](#auto-capture-is-experimental).
|
|
40
42
|
- **Repo scoping** — rows belong to the repo that wrote them; project A's facts never surface in project B.
|
|
41
43
|
- **Safe across concurrent sessions** — whole-file rewrites hold a per-file lock honored across processes and hand the new file over with an atomic rename.
|
|
42
44
|
- **Decay** — `memory_decay` retires stale open threads. Dry run by default, snapshot-first, undoable.
|
|
@@ -61,10 +63,10 @@ Zero configuration is the default. To tune, use the object form of the plugin en
|
|
|
61
63
|
| --- | --- | --- |
|
|
62
64
|
| `injectBudget` | `1200` | Character cap on the injected relevance block and each contextual pull; trimmed at whole-memory boundaries. Env fallback: `OPENCODE_MEMORY_INJECT_BUDGET`. |
|
|
63
65
|
| `frontierBudget` | `3 × injectBudget` | Character cap on the session-start open-threads block. A thread longer than the budget is not injected and is reported as omitted. Env fallback: `OPENCODE_MEMORY_FRONTIER_BUDGET`. |
|
|
64
|
-
| `autoCapture` | `false` | Master switch for auto-capture. Off by default, so the install stays zero-token. |
|
|
66
|
+
| `autoCapture` | `false` | Master switch for auto-capture, which is **experimental and has never fired on a verified live store** — see [Auto-capture is experimental](#auto-capture-is-experimental). Off by default, so the install stays zero-token. |
|
|
65
67
|
| `captureModel` | — | `"provider/id"` model used for auto-capture. Required when `autoCapture` is on; missing or invalid disables capture with a startup warning. |
|
|
66
68
|
| `captureMax` | `3` | Maximum candidates proposed per capture pass. |
|
|
67
|
-
| `captureOnCompact` | `true` | When `autoCapture` is on, also mine the transcript at compaction, before the summarizer replaces it. Its 5-minute cooldown is separate from the
|
|
69
|
+
| `captureOnCompact` | `true` | When `autoCapture` is on, also mine the transcript at compaction, before the summarizer replaces it. Its 5-minute cooldown is separate from the turn-end one, so the two triggers' hit-rates stay measurable. Setting it while `autoCapture` is off does nothing and reports a startup warning. |
|
|
68
70
|
| `notifyBlocked` | `true` | Terminal (TUI) only: toast when a write gate blocks a write. Blocks are always in `memory_evidence` either way. |
|
|
69
71
|
|
|
70
72
|
### Environment variables
|
|
@@ -80,8 +82,26 @@ Zero configuration is the default. To tune, use the object form of the plugin en
|
|
|
80
82
|
| `OPENCODE_VIEWER_PORT` | Admin editor port (default `8787`). |
|
|
81
83
|
| `OPENCODE_VIEWER_ALLOWED_HOSTS` | Comma-separated hosts beyond loopback. See [Surfaces](#surfaces). |
|
|
82
84
|
|
|
85
|
+
## Auto-capture is experimental
|
|
86
|
+
|
|
87
|
+
**Status: in progress, and not working yet.** Auto-capture has never been observed firing on a live opencode 2.x store. It is shipped behind `autoCapture` because the plumbing is finished — the trigger, the model pass, the gates, the cooldown — not because the outcome has been verified. Treat it as a switch that may cost model calls and store nothing.
|
|
88
|
+
|
|
89
|
+
What is established, from tests and fixtures (no live store involved):
|
|
90
|
+
|
|
91
|
+
- **The trigger events are ones the host actually emits.** Capture subscribes to `session.execution.succeeded` and `session.execution.interrupted`, the two turn-end events present in a recording of the desktop service (`test/fixtures/host-events.jsonl`). `session.idle`, `session.status` and `session.execution.failed` are *declared* by the host but absent from that recording, so they deliberately do not trigger capture; `test/event-fidelity.test.ts` refuses a trigger that is only declared. An earlier revision subscribed to `session.idle` and stayed silent for days with no signal — reading a declared event as an emitted one is the failure that fixture exists to prevent.
|
|
92
|
+
- **The path runs under simulated host traffic** — unit tests hand the plugin the recorded envelopes and assert a candidate lands through the write gate, including conservation (a near-duplicate collapses at the gate instead of writing a second row): `test/capture.test.ts`, `test/capture-compaction.test.ts`. No terminal e2e scenario covers the trigger, so the simulated envelope is the strongest evidence that exists — and fabricating the envelope is exactly what passed while this feature was dead.
|
|
93
|
+
|
|
94
|
+
What is not established:
|
|
95
|
+
|
|
96
|
+
- That a live host emits those events in the shape the subscription reads, end to end. No `auto_capture_*` line and no `capture_lag` line exists anywhere in the maintainer's evidence history (checked 2026-10-26 through 2026-10-29); a live trial armed on 2026-10-26 was stood down on 2026-10-29 without ever firing, so it answered nothing.
|
|
97
|
+
- Anything about quality. What auto-capture would write, how often it duplicates a memory you would have written yourself, and what it costs remain unmeasured. `bench/capture-trigger-results.md` is a **bench** simulation of trigger *timing* with a scripted extractor — its compaction world captured 0 rows and 4 of its 6 controls report FAIL. It answers "which moment is worth mining", not "does the shipped feature work".
|
|
98
|
+
|
|
99
|
+
**Am I armed?** `memory_evidence` answers on the `plugin_load` line: `capture=off` (the option is not on), `invalid_model` (`captureModel` is not `provider/id`), `no_capabilities` (the host did not expose what capture needs) or `capture=on`, next to `subscribed=[…]` listing the event types that subscription really reacts to. On desktop this needs `opencode service restart` after an edit — relaunching the app keeps the old service and its already-parsed options alive, so `capture=` can report a value your config no longer contains. `capture=on` plus no `auto_capture_*` line after a session is the open bug, not your configuration.
|
|
100
|
+
|
|
83
101
|
## How memory is written
|
|
84
102
|
|
|
103
|
+
Promotion evidence keeps a bounded sample of call IDs: the ten most recent code-engagement calls, plus the latest gate check, the latest recorded gate FAIL/fix/PASS recovery, and the latest recorded tool FAIL/PASS retry (at most 16 distinct IDs). `evidence_refs_count` is the total number of recorded session calls before sampling, including non-code tools; the sampled IDs are audit pointers, not a complete history. Grounding and memory attribution still use the full in-memory ledger. Existing evidence day-files are left unchanged: this upgrade does not backfill, compact, or delete historical audit records.
|
|
104
|
+
|
|
85
105
|
Four gates run before anything is stored, and each emits an ordered evidence line:
|
|
86
106
|
|
|
87
107
|
1. **GATE-1 — code references resolve.** Call signatures and paths embedded in the memory are checked against your live source tree.
|
|
@@ -107,7 +127,7 @@ Injection, recall, the frontier block, compaction, `memory_forget` and decay onl
|
|
|
107
127
|
- **Evidence is never injected**, and the standing system digest is two lines.
|
|
108
128
|
- **Measured, not claimed.** The plugin reads each turn's `tokens.cache` accounting and displays the actual hit rate next to the badge.
|
|
109
129
|
|
|
110
|
-
|
|
130
|
+
**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:
|
|
111
131
|
|
|
112
132
|
| Policy | Recomputes | Cache busts | Injected chars (20 turns) | Avg/turn | Worst section |
|
|
113
133
|
| --- | ---: | ---: | ---: | ---: | ---: |
|
|
@@ -124,7 +144,7 @@ bun run bench
|
|
|
124
144
|
|
|
125
145
|
## Recall quality
|
|
126
146
|
|
|
127
|
-
No vector database, no embedding model, no API key.
|
|
147
|
+
No vector database, no embedding model, no API key. **Bench** — what the keyword matcher gives up, measured against classic BM25 on a deterministic eval (store of 200, k=3 — the production injection limit):
|
|
128
148
|
|
|
129
149
|
| Query, vs. the stored memory | share | R@1 | R@3 | with `kw` R@1 | with `kw` R@3 |
|
|
130
150
|
| --- | ---: | ---: | ---: | ---: | ---: |
|
|
@@ -136,7 +156,7 @@ No vector database, no embedding model, no API key. What the keyword matcher giv
|
|
|
136
156
|
|
|
137
157
|
- **In-project prompts are overwhelmingly lexical** (`bun test`, "the rate limiter", "staging deploys"): 98–100% R@3, flat from store size 50 to 500.
|
|
138
158
|
- **Single-overlap guessing was traded away.** Free-text prompts that share one concept abstain rather than force a guess; wrong top-memory fell to 6%. `memory_recall` still covers them.
|
|
139
|
-
- **Zero-overlap paraphrase is the real limit, and write time is where it is answered.** `memory_remember`
|
|
159
|
+
- **Zero-overlap paraphrase is the real limit, and write time is where it is answered.** `memory_remember` asks each row for 3–5 `kw` aliases (other names, other verb forms, the literal command); auto-capture asks for the same list, so these numbers are measured through the tool path rather than through capture. Keywords are indexed and never rendered. Strict R@1 0% → 26%, near R@1 28% → 67%. A permutation control (every row given someone else's aliases) scores 29%/35%, so the gain is meaning rather than extra tokens. The limit is narrowed, not removed.
|
|
140
160
|
- **Caveats.** The dataset is synthetic (52 memories / 105 queries, a fictional project), its class mix is deliberately adversarial, and scoring is single-gold.
|
|
141
161
|
|
|
142
162
|
Full methodology and all store sizes: `bench/recall-results.md`.
|
|
@@ -147,7 +167,7 @@ bun run bench:recall
|
|
|
147
167
|
|
|
148
168
|
## Write latency
|
|
149
169
|
|
|
150
|
-
A write that cites code references builds one tree index — a single recursive walk that prunes `node_modules` and VCS directories — shared by GATE-1 and GATE-2, and reads each source file at most once.
|
|
170
|
+
A write that cites code references builds one tree index — a single recursive walk that prunes `node_modules` and VCS directories — shared by GATE-1 and GATE-2, and reads each source file at most once. **Bench** — measured on a 5,300-file fixture (300 sources + 5,000 `node_modules` decoys), scope seeded with 5 embedded call forms:
|
|
151
171
|
|
|
152
172
|
| Call forms in the write | Shipped | One scan per form |
|
|
153
173
|
| --- | ---: | ---: |
|
|
@@ -163,20 +183,20 @@ bun run bench:write
|
|
|
163
183
|
|
|
164
184
|
## The store keeps score
|
|
165
185
|
|
|
166
|
-
The plugin keeps a **use ledger** (`<memory-root>/hits.logfmt`, append-only, rotated at 2 MB, never ingested as a memory) and reports it in `memory_status` and the `/memory` panel:
|
|
186
|
+
The plugin keeps a **use ledger** (`<memory-root>/hits.logfmt`, append-only, rotated at 2 MB, never ingested as a memory) and reports it in `memory_status` and the `/memory` panel. Illustrative output — shape, not a measurement:
|
|
167
187
|
|
|
168
188
|
```
|
|
169
189
|
STORE
|
|
170
190
|
41 active · 12 superseded · 4 open · 6 scopes
|
|
171
191
|
retrieved 33 rows in the last 30d; never retrieved 8 (20%) — reported, not acted on
|
|
172
|
-
24.1 KB total · 604 B per row · 1.3 rows/day (30d)
|
|
192
|
+
24.1 KB total · 604 B per row · 1.3 rows/day (30d)
|
|
173
193
|
```
|
|
174
194
|
|
|
175
195
|
- **Credit comes from three distinct sources** — the row rode the injected block, `memory_recall` returned it, or a grep/read pull appended it — because "the model asked" and "the harness offered" are different facts. Credit requires ≥2 shared terms with the query and is throttled to one line per memory per session per source per hour.
|
|
176
196
|
- **No prompt content is stored.** The ledger keeps a scan-truncated string from the *memory* side, never your message.
|
|
177
197
|
- **Reinforcement is a tie-break only** (`useBoost ≤ 1.0`): a recently used row wins a tie and can never outrank a real score gap. In consolidation the most recently used member of a cluster is never the merge loser.
|
|
178
198
|
- **`never retrieved` is stated, not acted on.** Pruning is your decision. Retired rows cannot inherit reinforcement: ledger rows are verified against the store on read.
|
|
179
|
-
- **Capture lag** is how stale the newest message was when auto-capture fired.
|
|
199
|
+
- **Capture lag** is how stale the newest message was when auto-capture fired. The line prints only when at least one `capture_lag` sample exists, which needs auto-capture to have fired — see [Auto-capture is experimental](#auto-capture-is-experimental).
|
|
180
200
|
|
|
181
201
|
## Consolidation
|
|
182
202
|
|
|
@@ -185,7 +205,7 @@ STORE
|
|
|
185
205
|
- **Deterministic.** The canonical row is the survivor's prose verbatim plus the absorbed rows' aliases as keywords. No model rewrites anything.
|
|
186
206
|
- **Proven by recorded reads.** Every read the ledger recorded for a cluster is replayed against the merged store, and a merge is proposed only when the canonical row catches at least as many of the cluster's own reads as the best single member did alone. A cluster with no recorded reads is reported as *unmeasured* and never merged on resemblance.
|
|
187
207
|
|
|
188
|
-
|
|
208
|
+
**Bench** — on the eval dataset the pass takes 200 rows to 52 with **R@3 52 → 53 and R@1 52 → 50**, and store-wide injected characters 25 945c → 6 933c. Both the regression and the budget swap are bounded in CI (`test/consolidate-bench.test.ts`).
|
|
189
209
|
|
|
190
210
|
## Secret redaction
|
|
191
211
|
|
|
@@ -232,7 +252,7 @@ Same data behind each one (`memory_status`; no model call).
|
|
|
232
252
|
|
|
233
253
|
**Terminal (opencode CLI)** — the plugin ships a TUI half (`@opencode/plugin/tui`) that loads automatically:
|
|
234
254
|
|
|
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.
|
|
255
|
+
- **Footer badge** — illustrative `● 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, and `—` throughout on a provider that reports no cache usage.
|
|
236
256
|
- **`/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.
|
|
237
257
|
- **Block toast** when a write is refused (`"notifyBlocked": false` to silence).
|
|
238
258
|
|
|
@@ -301,7 +321,7 @@ bun run gate:hooks # once per clone: run the gate on `git push`
|
|
|
301
321
|
| Stray `*.logfmt.lock` or `*.tmp` in the store | Write bookkeeping; safe to delete while nothing is writing. |
|
|
302
322
|
| `/repo-init` missing from the command list | The self-install couldn't write to `~/.config/opencode/commands/`. Create it and restart, or ask the model to "init memory for this repo" — the same tool. |
|
|
303
323
|
| Init says `Graph: unavailable` | `codebase-memory-mcp` couldn't start. Install pinned `0.11.0` or point `OPENCODE_CBM_BIN` at the binary. Scripts are still remembered without it. |
|
|
304
|
-
| Stale plugin after an update | `opencode plugin update opencode-self-improvement` (or bump the pinned `@version` in the `plugins` entry) and restart opencode. |
|
|
324
|
+
| Stale plugin after an update | `opencode plugin update opencode-self-improvement` (or bump the pinned `@version` in the `plugins` entry) and restart opencode. On desktop use `opencode service restart`: relaunching the app leaves the background service — and the plugin version and options it already parsed — alive. |
|
|
305
325
|
| `Error: Plugin is not configured` right after `plugin add` | An opencode bug ([#54654](https://github.com/anomalyco/opencode/issues/54654)), not a config problem: the first `plugin list/check/update` against a cold background service reads the plugin inventory before activation finishes. The plugin is installed and loading — just run the command again. |
|
|
306
|
-
| Auto-capture does nothing | `
|
|
326
|
+
| Auto-capture does nothing | Auto-capture is **experimental and has never fired on a verified live store** — see [Auto-capture is experimental](#auto-capture-is-experimental). `memory_evidence` says which case you are in from the `plugin_load` line: `capture=off` (option not on), `invalid_model` (`captureModel` must be `provider/id`; a bad one disables capture with a startup warning), `no_capabilities` (host did not expose what capture needs), or `capture=on`. `captureOnCompact` alone does nothing. `capture=on` with no `auto_capture_*` line after a session is the open bug, not your config. Rejected candidates log as evidence, not errors. On desktop, changing any of these options needs `opencode service restart`. |
|
|
307
327
|
| Reset all memories | Delete `~/.config/opencode/memory/`. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.14.
|
|
3
|
+
"version": "0.14.20",
|
|
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.ts
CHANGED
|
@@ -1,26 +1,13 @@
|
|
|
1
|
-
// Opt-in auto-capture
|
|
2
|
-
//
|
|
3
|
-
// and time are all injected by the caller (src/index.ts), so everything here
|
|
4
|
-
// is unit-testable. Every candidate that leaves this module still flows
|
|
1
|
+
// Opt-in auto-capture parsing, prompt, and lag helpers. Host access and model
|
|
2
|
+
// calls live in src/index.ts. Every candidate that leaves this module flows
|
|
5
3
|
// through runWriteGate in index.ts: capture NEVER writes memories directly,
|
|
6
4
|
// so dupes/stale/canonical rules keep the moat (same as model-authored writes).
|
|
7
5
|
// All parsing functions are TOTAL: any malformed input yields [] / "" / null,
|
|
8
6
|
// never a throw.
|
|
9
|
-
import {
|
|
7
|
+
import { TYPES } from "./types.ts";
|
|
10
8
|
import { flattenMemoryText } from "./sanitize.ts";
|
|
11
9
|
import { redactSecrets } from "./secrets.ts";
|
|
12
10
|
|
|
13
|
-
export interface CaptureOptions {
|
|
14
|
-
model: string; // "provider/id"
|
|
15
|
-
max: number;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export interface CaptureDeps {
|
|
19
|
-
generate: (prompt: string) => Promise<string>;
|
|
20
|
-
sessionText: string;
|
|
21
|
-
now: () => Date;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
11
|
export interface CaptureCandidate {
|
|
25
12
|
type: string;
|
|
26
13
|
scope: string;
|
package/src/gates.ts
CHANGED
|
@@ -6,7 +6,6 @@ import { memoryRoot, canonicalFile } from "./config.ts";
|
|
|
6
6
|
import { bracketList, parseLine, readLines } from "./logfmt.ts";
|
|
7
7
|
import {
|
|
8
8
|
appendMemory,
|
|
9
|
-
loadAll,
|
|
10
9
|
loadScope,
|
|
11
10
|
markManySupersededReport,
|
|
12
11
|
snapshotFiles,
|
|
@@ -16,6 +15,7 @@ import {
|
|
|
16
15
|
} from "./memory.ts";
|
|
17
16
|
import { chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
|
|
18
17
|
import { noteAuthored } from "./state.ts";
|
|
18
|
+
import { MAX_WRITE_EVIDENCE_REFS } from "./triggers.ts";
|
|
19
19
|
import { flattenMemoryText } from "./sanitize.ts";
|
|
20
20
|
import { containsSecret, redactSecrets } from "./secrets.ts";
|
|
21
21
|
import { readerForSession } from "./memory.ts";
|
|
@@ -70,6 +70,9 @@ export const auditCaveat = (outcome: GateOutcome): string =>
|
|
|
70
70
|
export interface GateContext {
|
|
71
71
|
liveRoot: string;
|
|
72
72
|
evidenceCalls: string[];
|
|
73
|
+
// Total before the telemetry window was selected. Legacy/direct callers
|
|
74
|
+
// may still supply their complete list; the writer bounds that too.
|
|
75
|
+
evidenceCallsCount?: number;
|
|
73
76
|
hasGateCheck: boolean;
|
|
74
77
|
// The session this write belongs to, when the caller knows it by name.
|
|
75
78
|
// Repo-stamp resolution prefers it over the mutable global current, which
|
|
@@ -96,8 +99,9 @@ export interface GateContext {
|
|
|
96
99
|
durable?: string[];
|
|
97
100
|
}
|
|
98
101
|
|
|
99
|
-
|
|
100
|
-
|
|
102
|
+
// Shared optional fields remain readable by diagnostic callers before they
|
|
103
|
+
// narrow on action. The variants below require the fields each verdict owes.
|
|
104
|
+
interface GateOutcomeFields {
|
|
101
105
|
reason?: string;
|
|
102
106
|
ts?: string;
|
|
103
107
|
chain: string;
|
|
@@ -116,6 +120,11 @@ export interface GateOutcome {
|
|
|
116
120
|
collapsedWith?: string;
|
|
117
121
|
}
|
|
118
122
|
|
|
123
|
+
export type GateOutcome =
|
|
124
|
+
| (GateOutcomeFields & { action: "promoted"; ts: string })
|
|
125
|
+
| (GateOutcomeFields & { action: "blocked"; reason: string })
|
|
126
|
+
| (GateOutcomeFields & { action: "collapsed" });
|
|
127
|
+
|
|
119
128
|
const STOPWORDS = new Set([
|
|
120
129
|
"use",
|
|
121
130
|
"using",
|
|
@@ -753,7 +762,8 @@ export async function runWriteGate(
|
|
|
753
762
|
ch,
|
|
754
763
|
supersedes: supersededTs ?? "-",
|
|
755
764
|
canonical: canon ? `canonical.logfmt:${canon.entry.ts}` : "-",
|
|
756
|
-
evidence_refs: bracketList(ctx.evidenceCalls),
|
|
765
|
+
evidence_refs: bracketList(ctx.evidenceCalls.slice(-MAX_WRITE_EVIDENCE_REFS)),
|
|
766
|
+
evidence_refs_count: ctx.evidenceCallsCount ?? ctx.evidenceCalls.length,
|
|
757
767
|
snapshot: snapshot[0] ?? "-",
|
|
758
768
|
trusted: ctx.trusted ? true : undefined,
|
|
759
769
|
grounded_by: groundedByEngagement ? "engagement" : undefined,
|
package/src/host.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Compatibility boundary for host payloads. These adapters only read data;
|
|
2
|
+
// repository binding, ambient fallbacks, clocks, and I/O belong to the caller.
|
|
3
|
+
function fields(value: unknown): Record<string, unknown> {
|
|
4
|
+
return value !== null && typeof value === "object" ? value as Record<string, unknown> : {};
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface ToolIdentity {
|
|
8
|
+
sessionID?: string;
|
|
9
|
+
callID?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** V2 ToolContext uses `id` for the call; absent/empty fields need a fallback. */
|
|
13
|
+
export function toolIdentity(context: unknown): ToolIdentity {
|
|
14
|
+
const { sessionID, id } = fields(context);
|
|
15
|
+
return {
|
|
16
|
+
sessionID: typeof sessionID === "string" && sessionID ? sessionID : undefined,
|
|
17
|
+
callID: typeof id === "string" && id ? id : undefined,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface SessionIdentity {
|
|
22
|
+
sessionID: string;
|
|
23
|
+
directory?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A directory-less identity still lets the caller resolve the session row. */
|
|
27
|
+
export function sessionIdentityEvent(raw: unknown): SessionIdentity | undefined {
|
|
28
|
+
const event = fields(raw);
|
|
29
|
+
if (
|
|
30
|
+
event.type !== "session.created" &&
|
|
31
|
+
event.type !== "session.execution.started" &&
|
|
32
|
+
event.type !== "session.moved"
|
|
33
|
+
) return undefined;
|
|
34
|
+
const data = fields(event.data ?? event.properties);
|
|
35
|
+
const info = fields(data.info ?? data);
|
|
36
|
+
const sessionID = info.sessionID ?? data.sessionID;
|
|
37
|
+
const directory = fields(info.location).directory ?? fields(data.location).directory
|
|
38
|
+
?? fields(event.location).directory ?? info.directory;
|
|
39
|
+
if (typeof sessionID !== "string") return undefined;
|
|
40
|
+
return { sessionID, directory: typeof directory === "string" ? directory : undefined };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Legacy context messages sometimes carry location directly or inside info. */
|
|
44
|
+
export function sessionDirectoryFromMessages(messages: unknown): string | undefined {
|
|
45
|
+
if (!Array.isArray(messages)) return undefined;
|
|
46
|
+
for (const message of messages) {
|
|
47
|
+
const row = fields(message);
|
|
48
|
+
const directory = fields(row.location).directory ?? fields(fields(row.info).location).directory;
|
|
49
|
+
if (typeof directory === "string" && directory) return directory;
|
|
50
|
+
}
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** session.get returns either a row or a {data: row} response. */
|
|
55
|
+
export function sessionDirectoryFromRow(result: unknown): string | undefined {
|
|
56
|
+
const response = fields(result);
|
|
57
|
+
const row = fields(response.data ?? response);
|
|
58
|
+
const directory = fields(row.location).directory ?? row.directory;
|
|
59
|
+
return typeof directory === "string" && directory ? directory : undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface SessionUsage {
|
|
63
|
+
sessionID: string;
|
|
64
|
+
input: number;
|
|
65
|
+
read: number;
|
|
66
|
+
write: number;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** V2 session usage, or the assistant-message usage emitted by older hosts. */
|
|
70
|
+
export function sessionUsageEvent(raw: unknown): SessionUsage | undefined {
|
|
71
|
+
const event = fields(raw);
|
|
72
|
+
let info: Record<string, unknown>;
|
|
73
|
+
if (event.type === "session.usage.updated") {
|
|
74
|
+
info = fields(event.data);
|
|
75
|
+
} else if (event.type === "message.updated") {
|
|
76
|
+
info = fields(fields(event.properties).info ?? event.info ?? fields(event.data).info);
|
|
77
|
+
if (info.role !== "assistant") return undefined;
|
|
78
|
+
} else {
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
if (typeof info.sessionID !== "string" || !info.tokens) return undefined;
|
|
82
|
+
const tokens = fields(info.tokens);
|
|
83
|
+
const cache = fields(tokens.cache);
|
|
84
|
+
return {
|
|
85
|
+
sessionID: info.sessionID,
|
|
86
|
+
input: Number(tokens.input) || 0,
|
|
87
|
+
read: Number(cache.read) || 0,
|
|
88
|
+
write: Number(cache.write) || 0,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Session ID envelopes accepted by capture; trigger selection stays separate. */
|
|
93
|
+
export function captureSessionID(raw: unknown): string | undefined {
|
|
94
|
+
const event = fields(raw);
|
|
95
|
+
const sessionID = fields(event.data).sessionID ?? event.sessionID ?? fields(event.properties).sessionID;
|
|
96
|
+
return typeof sessionID === "string" ? sessionID : undefined;
|
|
97
|
+
}
|