opencode-self-improvement 0.14.26 → 0.14.28

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 CHANGED
@@ -90,6 +90,7 @@ What is established, from tests and fixtures (no live store involved):
90
90
 
91
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
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
+ - **Identity triggers have their own recording check.** `test/event-fidelity.test.ts` checks `IDENTITY_EVENT_TYPES` against the original 2.1.4 recording plus `test/fixtures/host-session-move.json`, a normalized one-frame extract from a separate 2.2.2 move capture. The extract must declare nonempty provenance and its retained envelopes must round-trip through the lockfile-pinned `@opencode/schema` 2.0.32 decoder. These checks reject missing metadata and malformed envelopes; they do not authenticate the capture. The identity replay uses the plugin subscription, but live plugin rebinding remains unverified. The recording version is distinct from the CI host pin (2.0.26).
93
94
 
94
95
  What is not established:
95
96
 
@@ -117,6 +118,8 @@ Rows are stamped with your git origin (an id that survives re-clones and moves b
117
118
 
118
119
  Injection, recall, the frontier block, compaction, `memory_forget` and decay only see the current repo plus global rows, resolved from the calling session's identity at flow entry. A session that reaches a plugin instance is bound to that instance's own workspace on first contact — in a process hosting several workspaces, one session never borrows the repository some other workspace's setup left behind. A session whose repository cannot be resolved at all sees global rows only; "unknown" is never "everything". Writes follow that rule in the stricter direction: a named session with no resolved repository has **no write target**, so `memory_remember`, `memory_update`, `memory_import` and auto-capture refuse it (evidence `write_refused`) and store nothing — the alternatives were stamping your private content into whichever workspace's `setup()` ran last, or publishing it to every project as an unstamped row. A caller that names no session at all (the viewer process, a restore, a script) keeps the process scope, and an explicit `global: true` is a deliberate owner. Evidence lines carry the same stamp, so `memory_evidence` answers from the caller's repo plus global lines; a line a named session wrote while its repository was unresolvable is private to that session, and only an explicitly global (or predating-stamps) line reads as global. Preferences that should follow you everywhere go in with `memory_remember global: true`. Rows written before scoping existed are global, and the viewer (an admin surface over every repo) edits and restores a row with its own repo stamp — the viewer's missing session scope never decides a row's visibility. `memory_merge_review` applies the same rule to its inputs: a session may merge exactly the rows it may read — global rows plus its own repo's, from either seat — and a row id it merely knows is not authority to retire another repo's memory. Upgrading changes nothing.
119
120
 
121
+ Gate-authored evidence captures attribution at operation entry: if a session moves repositories while the gate runs, its audit lines remain in the starting repository's partition and can be read with `memory_evidence` from a session bound there. Caller-level init/capture lifecycle events still resolve attribution per event and can land in a different partition; [#199](https://github.com/abogartz/opencode-self-improvement/issues/199) tracks that boundary.
122
+
120
123
  ## Token cost and caching
121
124
 
122
125
  - **Section-frozen injection.** The whole memory section — standing digest, open-thread frontier, relevance block — is computed once per epoch and delivered byte-identically until something the model actually needs changes. The epoch's authority is the **rendered bytes**, not the store fingerprint: a promoted row that changes nothing visible costs no cache bust.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.14.26",
3
+ "version": "0.14.28",
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/evidence.ts CHANGED
@@ -6,7 +6,7 @@ import { dirname, join, resolve } from "node:path";
6
6
  import { createHash } from "node:crypto";
7
7
  import { dateStr, evidenceDir } from "./config.ts";
8
8
  import { appendLog, formatLine } from "./logfmt.ts";
9
- import { repoScope, sessionScope } from "./repokey.ts";
9
+ import { repoScope, sessionScope, type RepoScope } from "./repokey.ts";
10
10
  import { getCurrent } from "./state.ts";
11
11
  import { redactSecrets } from "./secrets.ts";
12
12
 
@@ -55,20 +55,27 @@ function scrubFields(fields: Record<string, unknown>): Record<string, unknown> {
55
55
  return out;
56
56
  }
57
57
 
58
- export async function record(
59
- ev: EvidenceEvent,
60
- fields: Record<string, unknown> = {},
61
- includeContext = true,
62
- sessionID?: string,
63
- ): Promise<void> {
58
+ // Immutable operation attribution, captured before the caller's first await.
59
+ // Null scope is significant: a named-unresolved session must stay private.
60
+ export interface EvidenceContext {
61
+ readonly sid: string;
62
+ readonly call: string | undefined;
63
+ readonly scope: Readonly<RepoScope> | null;
64
+ }
65
+
66
+ export function captureEvidenceContext(sessionID?: string): EvidenceContext {
64
67
  const cur = getCurrent();
65
68
  // An explicitly threaded session outranks the ambient one: gate-authored
66
69
  // lines must name the session the gate runs FOR, not whichever setCurrent
67
70
  // fired last during the gate's own awaits (#118 review note 1 — the rows
68
71
  // were fixed in #118, these lines were the residue). When the two disagree,
69
72
  // the ambient call belongs to the OTHER session's flow, so it is dropped
70
- // rather than borrowed. With sessionID undefined (tool paths — issue #121)
71
- // this is exactly the old ambient read.
73
+ // rather than borrowed. With sessionID undefined this captures the ambient
74
+ // session and call at entry by design (maintenance/direct callers). An
75
+ // explicit "?" keeps the ambient call only when cur.sid is also "?";
76
+ // otherwise it stays absent, even if a later setCurrent supplies a call.
77
+ // Normal tool hooks setCurrent before execute; this snapshot never guesses
78
+ // a missing operation call from a later hook. See #121 for identity context.
72
79
  const sid = sessionID ?? cur.sid;
73
80
  const call = sessionID !== undefined && sessionID !== cur.sid ? undefined : cur.call;
74
81
  // Read-side partitioning of the shared log (#131's rule, applied to
@@ -85,6 +92,17 @@ export async function record(
85
92
  // scope-less process) keep their historical global reading.
86
93
  const named = typeof sid === "string" && sid !== "" && sid !== "?";
87
94
  const scope = named ? sessionScope(sid) : repoScope();
95
+ return Object.freeze({ sid, call, scope: scope ? Object.freeze({ ...scope }) : null });
96
+ }
97
+
98
+ export async function record(
99
+ ev: EvidenceEvent,
100
+ fields: Record<string, unknown> = {},
101
+ includeContext = true,
102
+ sessionID?: string,
103
+ context?: EvidenceContext,
104
+ ): Promise<void> {
105
+ const { sid, call, scope } = context ?? captureEvidenceContext(sessionID);
88
106
  const line = formatLine({
89
107
  ev,
90
108
  ts: new Date().toISOString(),
@@ -135,6 +153,7 @@ export async function recordWriteBlocked(
135
153
  flags: string[],
136
154
  chain?: string,
137
155
  sessionID?: string,
156
+ context?: EvidenceContext,
138
157
  ): Promise<void> {
139
158
  await record(
140
159
  "write_blocked",
@@ -146,5 +165,6 @@ export async function recordWriteBlocked(
146
165
  },
147
166
  true,
148
167
  sessionID,
168
+ context,
149
169
  );
150
170
  }
package/src/gates.ts CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  type Memory,
14
14
  type SupersedeFields,
15
15
  } from "./memory.ts";
16
- import { chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
16
+ import { captureEvidenceContext, type EvidenceContext, chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
17
17
  import { getCurrent, noteAuthored } from "./state.ts";
18
18
  import { MAX_WRITE_EVIDENCE_REFS } from "./triggers.ts";
19
19
  import { flattenMemoryText } from "./sanitize.ts";
@@ -77,6 +77,7 @@ export interface GateContext {
77
77
  // absent/"?" callers capture ambient authority at entry (not after awaits).
78
78
  reader?: Reader;
79
79
  writeAt?: WriteTarget;
80
+ evidenceContext?: EvidenceContext;
80
81
  evidenceCalls: string[];
81
82
  // Total before the telemetry window was selected. Legacy/direct callers
82
83
  // may still supply their complete list; the writer bounds that too.
@@ -249,17 +250,13 @@ export async function runWriteGate(
249
250
  ): Promise<GateOutcome> {
250
251
  const reader = ctx.reader ?? readerFromSid(ctx.sessionID);
251
252
  const writeAt = ctx.writeAt ?? writeTarget(ctx.sessionID ?? getCurrent().sid);
253
+ const evidenceContext = ctx.evidenceContext ?? captureEvidenceContext(ctx.sessionID);
252
254
  const chain = chainId();
253
- // Gate audit lines thread the session: runWriteGate awaits (analysis, the
254
- // locked append), and another session's dispatch can move the ambient
255
- // current mid-gate — ambient-read lines would then name the wrong session
256
- // (#118 review note 1; the rows were fixed in #118, these were the
257
- // residue). Where ctx.sessionID is unset (tool paths — issue #121) record()
258
- // keeps the ambient read, exactly as before.
255
+ // Keep all gate audit lines with entry-time attribution, including refusals.
259
256
  const rec = (ev: string, fields: Record<string, unknown> = {}, includeContext = true) =>
260
- record(ev, fields, includeContext, ctx.sessionID);
257
+ record(ev, fields, includeContext, ctx.sessionID, evidenceContext);
261
258
  const recBlocked = (gate: number, reason: string, flags: string[], chain?: string) =>
262
- recordWriteBlocked(gate, reason, flags, chain, ctx.sessionID);
259
+ recordWriteBlocked(gate, reason, flags, chain, ctx.sessionID, evidenceContext);
263
260
 
264
261
  // Size/type floor BEFORE any scanning: gate analysis regexes
265
262
  // over megabyte content backtrack super-linearly and freeze the service
package/src/host.ts CHANGED
@@ -23,14 +23,18 @@ export interface SessionIdentity {
23
23
  directory?: string;
24
24
  }
25
25
 
26
+ // Shared with the recording-backed fidelity checks. Adding a trigger requires
27
+ // both a protocol declaration and an observation from a live host.
28
+ export const IDENTITY_EVENT_TYPES: readonly string[] = Object.freeze([
29
+ "session.created",
30
+ "session.execution.started",
31
+ "session.moved",
32
+ ]);
33
+
26
34
  /** A directory-less identity still lets the caller resolve the session row. */
27
35
  export function sessionIdentityEvent(raw: unknown): SessionIdentity | undefined {
28
36
  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;
37
+ if (typeof event.type !== "string" || !IDENTITY_EVENT_TYPES.includes(event.type)) return undefined;
34
38
  const data = fields(event.data ?? event.properties);
35
39
  const info = fields(data.info ?? data);
36
40
  const sessionID = info.sessionID ?? data.sessionID;
package/src/index.ts CHANGED
@@ -31,7 +31,7 @@ import { pruneMemory } from "./prune.ts";
31
31
  import { exportMemories, findStaleOpen, importMemories } from "./portable.ts";
32
32
  import { listSnapshots, restoreSnapshot } from "./undo.ts";
33
33
  import { SESSION_CAP, SessionLru } from "./sessions.ts";
34
- import { evidenceFileFor, record, recordCaptureLag } from "./evidence.ts";
34
+ import { captureEvidenceContext, evidenceFileFor, record, recordCaptureLag } from "./evidence.ts";
35
35
  import { proposeConsolidations, renderProposals } from "./consolidate.ts";
36
36
  import { readReads } from "./hits.ts";
37
37
  import {
@@ -220,6 +220,8 @@ export function resetCaptureCooldowns(): void {
220
220
  // test/event-fidelity.test.ts requires every trigger to appear in both that
221
221
  // recording and the installed @opencode/schema manifest: a declared event
222
222
  // alone is insufficient evidence that the host emits it (#78, #136).
223
+ // Identity triggers have a separate observed check in that test, combining
224
+ // this recording with the 2.2.2 move extract in host-session-move.json (#176).
223
225
  export const TURN_END_EVENTS = ["session.execution.succeeded", "session.execution.interrupted"] as const;
224
226
 
225
227
  /** Every event type the capture subscription reacts to (fidelity-tested). */
@@ -298,6 +300,7 @@ const impl = {
298
300
  sessionID: sid,
299
301
  reader: readerFromSid(sid),
300
302
  writeAt: writeTarget(bound),
303
+ evidenceContext: captureEvidenceContext(sid),
301
304
  // NOTE (re-review): this one lookup is intentionally NON-firm — a
302
305
  // provisional binding may supply the gate's verification TREE. The
303
306
  // tree is where a referenced file is checked to exist, not who the
@@ -554,6 +557,7 @@ const impl = {
554
557
  const ownerless = ownerlessWriter(sid);
555
558
  if (ownerless) return await refuseOwnerlessWrite(ownerless, "update");
556
559
  const reader = readerFromSid(sid);
560
+ const updateGate = gateContext(sid);
557
561
  // The whole update — resolve, gate, supersede — runs under one
558
562
  // UPDATE-ORDER lock. Without it, two concurrent updates that both
559
563
  // resolved the same still-active target both promoted and both
@@ -689,7 +693,7 @@ const impl = {
689
693
  repo: requested.repo,
690
694
  repoPath: target.repo ? target.repoPath : undefined,
691
695
  },
692
- { ...gateContext(sid), reader, supersedesTs: target.ts, durable: gateDurable },
696
+ { ...updateGate, reader, supersedesTs: target.ts, durable: gateDurable },
693
697
  );
694
698
  if (outcome.action === "promoted" && outcome.ts && target) {
695
699
  mutated = true;
package/src/init.ts CHANGED
@@ -10,7 +10,7 @@ import { existsSync } from "node:fs";
10
10
  import { cbmBin } from "./config.ts";
11
11
  import { isVisibleTo, loadAll, markSuperseded, readerFromSid, type Reader } from "./memory.ts";
12
12
  import { runWriteGate, type GateContext } from "./gates.ts";
13
- import { record } from "./evidence.ts";
13
+ import { captureEvidenceContext, record } from "./evidence.ts";
14
14
  import { writeEvidence, hasGateCheck } from "./triggers.ts";
15
15
  import { writeTarget } from "./repokey.ts";
16
16
  import { getCurrent } from "./state.ts";
@@ -210,6 +210,7 @@ export async function initStamp(scope: string, sid?: string, reader: Reader = re
210
210
  export async function runInit(args: InitArgs): Promise<InitSummary> {
211
211
  const reader = readerFromSid(args.sessionID);
212
212
  const writeAt = writeTarget(args.sessionID ?? getCurrent().sid);
213
+ const evidenceContext = captureEvidenceContext(args.sessionID);
213
214
  const root = await gitRootOf(args.liveRoot);
214
215
  const scope = basename(root) || basename(args.liveRoot);
215
216
  const head = await gitHead(root);
@@ -220,6 +221,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
220
221
  liveRoot: root,
221
222
  reader,
222
223
  writeAt,
224
+ evidenceContext,
223
225
  ...writeEvidence(args.sessionID ?? getCurrent().sid),
224
226
  hasGateCheck: hasGateCheck(args.sessionID ?? getCurrent().sid),
225
227
  // Stamps land on the caller's session even though runInit awaits git
@@ -1,10 +1,11 @@
1
1
  // Memory Viewer server. Bundled with the plugin: run `bun memory-view` (or
2
2
  // `bun run src/viewer/server.ts`) from the repo root and open the printed URL.
3
- // Binds 127.0.0.1 only — the memory store is local, personal data. All reads go
3
+ // Defaults to 127.0.0.1 — the memory store is local, personal data. All reads go
4
4
  // through the same loadAll() used by recall/inject (so blocked entries are
5
5
  // hidden), and all mutations are non-destructive (snapshot + audit + supersede).
6
6
  // I2: serves only file data; never writes into any repo.
7
7
  import { basename, join } from "node:path";
8
+ import { isIP } from "node:net";
8
9
  import { serve, type Server } from "bun";
9
10
  import { z, type ZodTypeAny } from "zod";
10
11
  import { BlockBody, DeleteBody, EditBody, RestoreEntryBody, UnblockBody, UnrejectBody } from "../schema.ts";
@@ -59,6 +60,18 @@ function allowedHostnames(): Set<string> {
59
60
  return new Set(names);
60
61
  }
61
62
 
63
+ function isLoopbackHostname(name: string): boolean {
64
+ // allowedHostnames supplies trimmed, lower-cased names (IPv6 bracketed).
65
+ const host = name.replace(/^\[|\]$/g, "");
66
+ if (host === "localhost") return true;
67
+ if (isIP(host) === 4) return host.startsWith("127.");
68
+ // Closed spellings only: URL parsing throws on IPv6 zone ids. Ambiguous
69
+ // aliases (including abbreviated IPv4) conservatively trigger the warning.
70
+ return host === "::1" || host === "0:0:0:0:0:0:0:1";
71
+ }
72
+
73
+ const EXPOSURE_WARNING = "[memory-viewer] WARNING: non-loopback hosts are allowed. The viewer serves private memory over plain HTTP without authentication; anyone who can reach it with an allowed Host can read or modify the store. Use only on a network you trust.";
74
+
62
75
  function rejectRequest(req: Request, url: URL, port: number): Response | null {
63
76
  if (!allowedHostnames().has(url.hostname) || (url.port || "80") !== String(port)) {
64
77
  return error("unexpected Host header", 403);
@@ -171,6 +184,10 @@ export async function startViewer(port: number = PORT): Promise<ViewerServer> {
171
184
  },
172
185
  });
173
186
  const bound = server.port ?? port;
187
+ // Warn after binding; wildcard binds (0.0.0.0 and ::) are non-loopback too.
188
+ if ([...allowedHostnames()].some((host) => !isLoopbackHostname(host))) {
189
+ console.warn(EXPOSURE_WARNING);
190
+ }
174
191
  return { server, url: `http://${HOST}:${bound}/` };
175
192
  }
176
193
 
@@ -325,6 +342,6 @@ async function restoreRoute(body: Record<string, unknown>): Promise<Response> {
325
342
 
326
343
  if (import.meta.main) {
327
344
  startViewer(PORT).then(({ url }) => {
328
- console.log(`\nMemory Viewer: ${url}\n(127.0.0.1 only; snapshot+audit are mandatory on every edit/delete)`);
345
+ console.log(`\nMemory Viewer: ${url}\n(snapshot+audit are mandatory on every edit/delete)`);
329
346
  });
330
347
  }