Skip to content

fix(security): session-scoped reads, evidence credential scrub, viewer origin preservation (#127 #128 #129) - #133

Merged
abogartz merged 10 commits into
abogartz:mainfrom
WhollyMindless:fix/security-127-129
Oct 28, 2026
Merged

abogartz merged 10 commits into
abogartz:mainfrom
WhollyMindless:fix/security-127-129

Conversation

@WhollyMindless

@WhollyMindless WhollyMindless commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Addresses the three high-priority findings from the 2026-10-26 security review. Regression-first: each fix ships with a suite that fails on the reviewed revision (cf9b73c, 0.14.9) and passes here — 11 of the 12 new tests are red on that revision (the twelfth is the deliberate single-session no-regression guard, green everywhere by design).

#127 — cross-repository session leaks via ambient identity

session.context awaited the store read and filtered with the mutable global current, so a second session's hook dispatching during that await moved the filter and injected the other repo's frontier. Fix: an immutable Reader resolved synchronously at flow entry from the event's / ToolContext's own sessionID and carried through every await — injection sinks, recall, contextual pulls, compaction, prune, decay, the gate's scope reads, and the write stamps behind GateContext.sessionID. isVisibleHere remains only as the documented ambient (out-of-plugin) convenience.

The unbound-session fail-open (unknown repo -> see everything) is gone: a plugin flow whose caller identity names no repository sees explicit/legacy global rows only. All-repository breadth is now a property of the entry point (ADMIN_READER: the viewer, out-of-plugin maintenance), never of a missing session.

The follow-up review round closed the remaining shape of the same flaw: readerForSession still fell back to the module scope, which in a process that loaded several plugin instances belongs to whoever set up last. Entry binding replaced the fallback — tools, hooks, capture, and the compaction path bind an unknown caller PROVISIONALLY to their own instance's setup location (a real identity from the event stream or the session-row API still replaces it), so the caller's repository is the workspace the call actually reached; a session nothing can resolve stays global-only.

#128 — credentials persisted by ordinary tool use

afterTool stored summarize(text) — the first 80 folded characters — and record persisted fields verbatim, so a recognized credential in any read/grep/edit/bash result survived byte-for-byte in evidence/<date>.logfmt in the default configuration and rode back through memory_evidence. Scrubbing now happens at the durable write boundaries: record scrubs every string field it writes, and afterTool redacts the complete output before folding/truncation, so boundary-sliced token prefixes and PEM fragments cut before their END marker cannot survive as unmatchable text. The follow-up round added the one boundary the first pass missed: markManySuperseded scrubs the supersede fields (a merge/decay/update reason) before they are rewritten into the loser's daily row — previously the evidence line beside it was clean while the tombstone kept the token verbatim. Deletion-audit reasons carry the same rule. The tool_result telemetry line itself still lands. Historical files are untouched — remediation stays separate (#74).

Evidence reads are scoped too (the previously deferred acceptance line is resolved): every record() line from a resolvable session, or from a genuinely session-less flow, stamps the recording repository, and memory_evidence filters through evidenceVisibleTo — the line-level twin of isVisibleTo — so a shared log partitions by repo while explicitly global (repo=global) lines, legacy unstamped sid-less lines, and the admin viewer keep their global semantics. The one case no stamp can describe — a line a NAMED session wrote while its repository was unresolvable — is private to that session (visible back to it and to the admin surface), never global and never another instance's repository; the second follow-up round below closed that.

#129 — viewer edits made private rows global

The standalone viewer has no repo scope, so editMemory appended the replacement unstamped — which every read path treats as global. A typo fix made a repo-private memory injectable in every project. Edits now carry the target's stamp verbatim (an unstamped/legacy target lands explicitly repo=global — same visibility, honest on the line); omitted issue/tags/kw survive instead of erasing import/auto-capture provenance and retrieval aliases; the delete-audit line records the origin; and restore-entry — schema, route, and the viewer UI — replays it. The viewer stays the explicit admin surface: it lists every repo, and now says which repo each row carries.

Follow-up review round (a8c5b7a probes)

Committed as red-first pairs on this branch: 97559e0 (regressions, all three red at a8c5b7a) → d56956e (fixes, green).

  • Probe 1 (unbound session inherits a later setup's repository; A's context hook injected B's frontier): fixed by the entry-binding rework above.
  • Probe 3 (memory_evidence surfaced another repository's tool_result lines from a shared store): fixed by the evidence stamp + evidenceVisibleTo filter.
  • Probe 4 (ghp_ token in a merge reason scrubbed in evidence but verbatim in the loser's daily row): fixed by the markManySuperseded scrub.

Five pre-existing tests relied on exactly the module-scope borrowing this round removed; their sessions are now bound explicitly — the same shape the plugin itself uses at entry.

Second follow-up round (d56956e re-review probes)

The re-review found the same identity flaw one boundary later — on the WRITE side of the evidence log. record() stamped a named-but-unresolved session through repoScopeFor(sid), whose module fallback belongs to whoever set up LAST, so session A's line could arrive carrying repository B's stamp; and evidenceVisibleTo treated a MISSING stamp as the global marker, so an unresolved session's fresh line was readable from everywhere. Committed again as a red-first pair: 65812bc (test/security-evidence-unbound-server.test.ts, both red at d56956e — probe 2 with the review-corrected assertion that the foreign repo= stamp is ABSENT, reproducing the exact smoking-gun line) → a909685 (green):

  • record() stamps a NAMED session only from its OWN resolved scope; the module-scope fallback remains only for genuinely session-less writes (viewer, out-of-plugin maintenance, CLI).
  • A missing stamp is not the global marker: an explicit repo=global line and an unstamped line that names NO session (legacy, session-less writes) stay global, exactly as before; an unstamped line that names a session is visible only back to that session and to the admin surface. memory_evidence threads the caller's own sid into the predicate.

Also from that review (finding 2, order-dependent suite failures on some hosts): session bindings are module-global, so injection-framing now resets state and session scopes in its afterEach, and negative-eval's beforeEach clears the ambient session (resetState) before its scope-crossing tests resolve the ambient reader. And gateContext's liveRoot lookup now carries an explicit note that it is the gate's non-firm VERIFICATION TREE lookup, never an identity path.

The first CI run on these heads reddened probe 2 for a fixture-precision reason only: CI tests the PR merge commit, and main (0.14.10, #142) added an ev=plugin_load boot record that instance B legitimately stamps with B's repository (a session-less write) in the shared day file; the probe's whole-file "foreign stamp absent" scan tripped on that line while A's line was correctly unstamped. 203240f scopes the assertion to the line carrying A's marker — still red at d56956e, green at the fix, immune to unrelated stamped lines.

Validation

  • Full bun test: 542 pass / 5 skip / 0 fail (this machine: the service-host stamp e2e fails for a sandbox reason — no git for the spawned service — identically at every reviewed head; green in CI).
  • bun x tsc --noEmit clean; biome lint 0 errors.
  • Red-on-base proof: test/security-*.test.ts run against detached cf9b73c → 11 fail, 1 pass (the guard); the three follow-up regressions red at a8c5b7a, green at d56956e; the two re-review regressions red at d56956e, green at a909685/203240f.
  • New suites: test/security-session-isolation.test.ts, test/security-evidence-redaction.test.ts, test/security-viewer-scope.test.ts, test/security-unbound-identity.test.ts, test/security-evidence-unbound-server.test.ts — real hooks, real evidence writer, real viewer routes; no sleeps or source mocks.

Rebase record

2026-10-27 (late): rebased onto main 0.14.11 (#145 export/import containment + #146 test teardown), current head 9a7c674; round SHAs above are the pre-rebase history, preserved in the review threads. The only conflict was src/portable.ts's import block — main's resolveContained/exports machinery plus this PR's readerFromSid/isVisibleTo decay filter, resolved as their union (the now-unused isVisibleHere import dropped). Parity check against pristine main on this machine: both fail exactly the same 17 tests (#145's export/symlink cluster under Windows/Bun 1.3.10 + the known service-host e2e sandbox case), all green in CI.

Fixes #127. Fixes #128. Fixes #129.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Follow-up review at a8c5b7a4864476dcfceca0d9232ab000792e6589, also exercised as part of the combined #135 head c9791ed7efc48eb200fefc3593f03dcb07d8b6d9: please fix the remaining isolation gap and resolve the outstanding #128 requirements before marking this PR ready or treating #127/#128 as closed.

  1. P1 — an unbound session still inherits another setup's repository (security: concurrent and unbound sessions can inject another repository's private memories (high) #127). readerForSession() falls back to the shared repoScope(). I reproduced: load plugin A, load plugin B, seed a private B frontier row, then invoke A's real context hook for an unbound A session. A's system context contains B's private marker. The new test only covers the null-setup-scope case; it misses a non-null scope left by another setup. Unknown caller identity must produce global-only access or defer injection, unless the caller's own repository is resolved. Preserve the normal single-session case by binding that session explicitly, rather than borrowing the last setup's scope. Affected lines. This same Reader also defeats fix(security): date-shaped evidence reads, ownership-checked merges, redact-before-crop capture (#130 #131 #132) #135's merge authorization for unbound callers (security: memory_merge_review can supersede another repository's rows (medium) #131).

  2. P1 — ordinary evidence reads still cross the session/repository boundary (security: tool-output evidence stores recognized credentials without redaction (high) #128). With A and B both correctly bound, drive B's execute.after hook with a confidential ordinary-text marker, then call memory_evidence with A's ToolContext. A receives B's tool_result line and its output summary. Redacting recognized credentials does not protect other confidential text. This is the deferral already acknowledged in the PR description, not a new regression. Please define and enforce normal caller-scoped evidence reads; retain any all-repository audit use case behind an explicit administrative entry point. If this is split into a follow-up, link that issue and make the closure/acceptance decision explicit rather than leaving an unconditional Fixes #128 claim.

The related audit/reason audit is also incomplete: a synthetic recognized credential in memory_merge_review.reason is scrubbed in evidence but written verbatim into the loser's daily memory row. Details and a probe are included in the #135 review; this is a remaining write boundary, not a regression in the new tool-output scrub.

The #129 viewer fix looks correct for the reviewed cases: edits retain origin and omitted issue/tags/keywords, and deletion/restore preserves repository visibility. The new ordinary tool-output redaction tests also pass, including summary-boundary and PEM cases.

All five runnable regression probes and the #135 findings. On the combined head, the existing suite passes 537 tests, with 5 skipped and 0 failures, typecheck passes, and lint reports no errors; all five additional probes fail. Tests use the repository's actual hooks/tools through the fake-host harness, temporary stores, and synthetic credentials on Windows / Bun 1.3.10.

Please add committed regressions for the non-null/multiple-setup unbound case and cross-session evidence read, fix the behavior, rerun the suite, and keep #127/#128 open until the outstanding acceptance cases are resolved or explicitly split.

WhollyMindless added a commit to WhollyMindless/opencode-self-improvement that referenced this pull request Oct 27, 2026
Probe 2 (unbound session retiring another repository's rows through
memory_merge_review) is GREEN already at this head: the identity fix
from the abogartz#133 side (entry binding, readerForSession without the
module-scope fallback) resolves the caller to its own instance's
repository, and the abogartz#131 ownership check then refuses both seats.
Committed as the pinned acceptance case.

Probe 5 is RED here: with the evidence directory poisoned, the merge
retires the loser, its record() throws, and the catch — written for the
lock-acquisition case — reports "nothing was done" while the row IS
superseded on disk. The next commit makes the catch tell the truth
about where the failure landed.

@abogartz abogartz left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review — verified empirically; approve

Method: detached worktrees of this branch and of cf9b73c; every load-bearing claim re-run, not read.

Verified against the tree:

  • Red-on-base reproduced exactly: the three new suites on cf9b73c → 11 fail / 12 run; the 12th (single-session no-regression guard) green as stated.
  • Full suite on the branch: 0 fail (520 pass / 12 skip on this host; total 532 = your 527 + 5 — the pass/skip split is host-dependent, win32 skipIf groups). bun run typecheck clean; biome lint 0 errors.
  • #127 threading checked call-site by call-site: the context hook captures sid from the event before any await and carries it (index.ts context hook → injectableRows(sid) → refreshEpoch(sid, mems)); systemDigest receives { sessionID } explicitly; contextualPull resolves the Reader from input.sessionID before the store read (inject.ts:456); storeVersion/selectRelevant receive the entry-filtered rows. Ambient (readerForAmbient) remains only in the documented out-of-plugin paths.
  • The isolation race test is deterministic, not sleep-based: A's context hook parks on the store read, B's execute.before moves the ambient mid-await — the base failure is structural, so the pin cannot rot into a flake.
  • #128: scrubFields covers every string field, and every record() call site passes flat strings (flags is pre-joined in recordWriteBlocked); afterTool redacts the complete output before folding; stored content is already redacted at the appendMemory choke point, so deletion-audit content copies are clean.
  • #129: edit carries the target's stamp verbatim (repo: target.repo ?? "global"), omitted issue/tags/kw survive, and the origin round-trips audit → schema → route → UI.

Nits (non-blocking):

  1. Two new unused-import warnings: isVisibleHere (src/index.ts:20) and visibleHere (src/inject.ts:9); visibleTo (src/index.ts:29) is also imported-unused. "advisory warnings unchanged" isn't quite true — net +2.
  2. README: "a plugin session whose identity is not yet bound sees global rows only, never another workspace's" — readerForSession is sessionScope(sid) ?? repoScope(): an unbound session with a module scope set sees that repo (correct for the single-workspace plugin; on a serve host it's the last setup's workspace during the pre-bind window — the code comment near the identity-race backstop acknowledges this). Suggest "its own workspace or global only".
  3. Cross-reference: memory_export still has no reader filter (src/portable.ts:50) — any session can export every repo's rows. Pre-existing, out of this PR's scope; filed separately.

LGTM — the diff matches the body on every claim I checked. Not merging per maintainer.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Re-review of d56956e29e311f63f739462bbad78c0e109bad1f: the three earlier probes for multi-setup injection, bound-repository evidence reads, and merge-reason redaction now pass. One #128 isolation blocker remains for newly written evidence from unresolved server sessions. This is separate from historical-store cleanup.

Two cases reproduce through the actual registered hooks/tools with temporary stores and synthetic ordinary-text markers:

  1. Load a server-style plugin with no setup directory, run a read result for unresolved session A, then bind session B to a repository and ask B for memory_evidence. B receives A's new confidential output. The evidence line has A's sid but no repository stamp, and evidenceVisibleTo() treats every unstamped line as global.
  2. Load that scope-less plugin first, then another plugin for repository B. A's new evidence is now stamped as B's repository because record() calls repoScopeFor(sid), whose unknown-session fallback is the shared module scope. B can read A's output through its correctly scoped evidence tool.

Writer fallback · Unstamped-is-global filter.

Please keep newly written evidence for an unresolved session private to that session, or defer recording sensitive excerpts until identity is known. Do not borrow another instance's repository, and distinguish explicit global/admin evidence from a missing repository stamp. Keep any historical-evidence policy separate.

Both probes fail on this head, on #135's updated head b2f7ac2, and on its CI merge commit 603110f. The original three probes pass on this head; all five original review probes pass on #135's updated head. Local verification used Windows / Bun 1.3.10 and the fake-host harness, not real-host end-to-end exploit tests. Please retain #128 as incomplete until these unresolved-session cases pass.

Two runnable unresolved-session evidence probes

Save as recheck-133-evidence.test.ts in the repository root and run bun test ./recheck-133-evidence.test.ts. The second probe's positive repo=B assertion is diagnostic evidence of the current incorrect stamp; when fixing the writer, replace it with the desired assertion that B's stamp is absent. Both tests require that B cannot read A's output.

import { afterEach, beforeEach, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, dirname, join, resolve } from "node:path";
import { loadPlugin, type LoadedPlugin } from "./test/harness.ts";
import { rememberSessionDir, resetSessionScopes, resolveRepo, setRepoScope } from "./src/repokey.ts";
import { resetState } from "./src/state.ts";
import { dateStr, evidenceDir } from "./src/config.ts";

let root: string, b: string;
let plugins: LoadedPlugin[];
beforeEach(() => {
  root = mkdtempSync(join(tmpdir(), "osi-recheck133-"));
  b = join(root, "repo-b"); mkdirSync(b);
  process.env.OPENCODE_MEMORY_DIR = join(root, "memory");
  process.env.OPENCODE_COMMANDS_DIR = join(root, "commands");
  resetState(); resetSessionScopes(); setRepoScope(null); plugins = [];
});
afterEach(async () => {
  for (const p of plugins) await p.cleanup();
  resetState(); resetSessionScopes(); setRepoScope(null);
  delete process.env.OPENCODE_MEMORY_DIR; delete process.env.OPENCODE_COMMANDS_DIR;
  if (dirname(resolve(root)) !== resolve(tmpdir()) || !basename(root).startsWith("osi-recheck133-")) {
    throw new Error("Unexpected fixture cleanup path");
  }
  rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 20 });
});

test("new evidence from an unresolved server session must not be global to other sessions", async () => {
  const p = await loadPlugin(null); plugins.push(p);
  await p.toolHooks["execute.after"]({ sessionID: "ses-unresolved-a", id: "read-a", tool: "read", input: {},
    result: { content: "UNRESOLVED_A_CONFIDENTIAL_RESULT" } });
  const raw = readFileSync(join(evidenceDir(), `${dateStr()}.logfmt`), "utf8");
  expect(raw).toContain("sid=ses-unresolved-a");
  rememberSessionDir("ses-b", b);
  const out = await p.tools.memory_evidence.execute({ ev: "tool_result" }, { sessionID: "ses-b", id: "evidence-b" });
  expect(out.content).not.toContain("UNRESOLVED_A_CONFIDENTIAL_RESULT");
});

test("unresolved server-session evidence must not borrow another instance's repo stamp", async () => {
  const pa = await loadPlugin(null); plugins.push(pa);
  const pb = await loadPlugin(b); plugins.push(pb);
  rememberSessionDir("ses-b", b);
  await pa.toolHooks["execute.after"]({ sessionID: "ses-unresolved-a", id: "read-a", tool: "read", input: {},
    result: { content: "UNRESOLVED_A_WRONG_REPO_RESULT" } });
  const raw = readFileSync(join(evidenceDir(), `${dateStr()}.logfmt`), "utf8");
  expect(raw).toContain("sid=ses-unresolved-a");
  // The current code attributes A's fresh evidence to B via repoScopeFor().
  expect(raw).toContain(`repo=${resolveRepo(b).key}`);
  const out = await pb.tools.memory_evidence.execute({ ev: "tool_result" }, { sessionID: "ses-b", id: "evidence-b" });
  expect(out.content).not.toContain("UNRESOLVED_A_WRONG_REPO_RESULT");
});

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Follow-up round pushed — committed regressions first, then fixes: 97559e0 (all three red at a8c5b7a) → d56956e (green, full suite rerun).

1 — unbound session inheriting another setup's repository (#127). readerForSession()'s ?? repoScope() is gone; an unknown caller now gets global-only access unless its own repository is resolved, resolved by binding the session explicitly rather than borrowing a scope. Every plugin entry (tools via toolIds, the context/after/compaction hooks, captureSession) binds an unknown session PROVISIONALLY to its own instance's setup location — the caller reached THIS instance, so this workspace is the caller's repo as far as the flow can know; a firm identity from the event stream or the session-row API still replaces the guess (sessionDirFirm guards let the real lookups proceed through a provisional entry, rememberSessionDir clears the provisional flag). With no location to bind (server-start shape) or a ?/absent sid, the flow reads global rows only. Committed as exactly your probe, plus the positive direction: A loads, B loads, B's private frontier seeded, A's real context hook fired for a never-bound A session — B's marker absent, A's own rows still inject; both assertions in test/security-unbound-identity.test.ts. The same binding fixes the cross-side leak you flagged into #131's merge seats (pinned there).

2 — ordinary evidence reads crossing the boundary (#128). Now defined and enforced as caller-scoped, not deferred: every record() line stamps the recording repository (repoScopeFor(sid) — the session's when bound, else this process's scope, mirroring store writes), and memory_evidence filters lines through evidenceVisibleTo, placed beside isVisibleTo so the two predicates cannot drift. Unstamped/legacy lines stay global. The all-repository audit use case is retained behind an explicit administrative entry point exactly as you asked: no model-facing tool path answers with ADMIN_READER anymore; cross-repo inspection is the out-of-plugin viewer or reading the day file directly. Your probe (both instances bound, B's execute.after marker invisible through A's memory_evidence, A's own line preserved) is in the same file.

Audit/reason boundary (your #128 note). markManySuperseded now scrubs every string field through redactSecrets before formatLine({...parsed, ...clean}) — covers the merge/decay/update tombstones. Your probe now asserts both halves: the evidence line clean and the loser's daily row clean; it was red at a8c5b7a with the ghp_ payload verbatim in the row.

Closure and acceptance wording. With 1–3 passing as committed regressions there is no deferral left behind the Fixes #128 claim, and nothing splits. On "keep #127/#128 open": GitHub closes them only when a PR with the Fixes keyword MERGES — this PR stays draft and nothing merges without your re-check, so both stay open in the meantime, and the PR body states the same semantics.

Per your ask, the five pre-existing tests that had been relying on module-scope borrowing now bind their sessions explicitly (frontier, injection-framing, the audit-scrub case); the fail-closed isolation tests were untouched. README states the new semantics. Full suite 540 pass / 5 skip / 0 fail (this machine shows the known service-host e2e stamp sandbox failure, identical at a8c5b7a), tsc clean, biome lint 0 errors. Keeping the PR draft pending your re-check of d56956e.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

@abogartz Thanks for the independent verification. One sequencing clarification: the new unresolved-session evidence finding and two runnable probes were posted at 00:14:28 UTC, 19 seconds after this approval. The three earlier follow-up probes now pass, but these two additional cases still fail on d56956e, #135's b2f7ac2, and its CI merge commit 603110f.

The approval is attached to d56956e, although its README nit quotes the earlier readerForSession() implementation (sessionScope(sid) ?? repoScope()). That reader fallback was removed in d56956e. The remaining leak is a different path: record() still uses repoScopeFor(sid), which can borrow another instance's scope for an unresolved server session; with no scope at all, evidenceVisibleTo() treats the fresh unstamped line as global. In both cases, correctly bound session B receives session A's new tool-output marker.

Could you run the two linked probes before treating #128 as resolved? This concerns new writes with a known session ID but unresolved repository identity, not historical-store remediation. My recommendation remains to keep the stack in draft until that isolation case is fixed; the passing original probes and current CI do not cover it.

@abogartz abogartz left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent re-verification of d56956e (macOS, Bun 1.4.3) — dismissing my earlier approval, which was attached to a8c5b7a. Three findings:

1 — Your two unresolved-session probes: confirmed red here. Both fail on d56956e exactly as you describe. Probe 2's raw line is the smoking gun:

ev=tool_result sid=ses-unresolved-a repo=8cb1152496e9 repoPath=.../osi-recheck133-*/repo-b output_summary=UNRESOLVED_A_WRONG_REPO_RESULT

record()'s repoScopeFor(sid) module fallback stamps A's evidence with B's repo (B's setup ran last and owns the shared module scope), so B's correctly-scoped read legitimately returns A's confidential output. Probe 1: the unstamped line is indistinguishable from legacy-global, and evidenceVisibleTo lets it through. Agreed: keep #128 open until both pass; the "distinguish explicit repo=global from a missing stamp" direction is the right one — otherwise any fix that just stamps global re-creates probe 1.

2 — NEW: d56956e breaks bun test ./test/ on this host — 2 failures, and it's your re-bind. The two negative-eval.test.ts "scope crossing — the injected block" tests fail in the full-suite run (pass in isolation). Root cause, not speculation — minimal repro bun test ./test/injection-framing.test.ts ./test/negative-eval.test.ts:

  • d56956e added rememberSessionDir("fr-cap", liveRoot) to injection-framing.test.ts:378, but that file never calls resetSessionScopes() — the binding survives into the next test file (module-global bySession).
  • negative-eval.test.ts's beforeEach calls setRepoScope(null) but not resetState() — the ambient getCurrent().sid is still "fr-cap".
  • The scope-crossing tests rely on ambient = module scope for BOTH the write stamp (appendMemory → repoScopeFor(sid)) and the read (readerForAmbient). With the ambient sid bound, ALPHA and BETA rows both get stamped with the framing temp repo and one reader sees both → the cross-repo assertion fails.

CI is green on Linux and Windows, so this is order/host-dependent — which is the worst kind: the gate command is not order-independent on macOS/Bun 1.4.3. The fix is hygiene, one line each: resetSessionScopes() in injection-framing's afterEach, resetState() in negative-eval's beforeEach. Given the #68 epic's rule, the re-bind commit should have caught this with the gate command on any host.

3 — The provisional-binding design itself reviewed clean, with one note. Guard discipline is right: real lookups use sessionDirFirm (index.ts:330/362/382/384), rememberSessionDir clears the provisional flag, resetSessionScopes clears the set. Note: gateContext's liveRoot uses the non-firm sessionDir (index.ts:289), so a provisional guess becomes the gate's verification tree — consistent with "as far as the flow can know", but worth a comment so a future edit doesn't mistake it for firm identity.

Verified green here: tsc clean, biome 0 errors, the 97559e0 regression suites pass, and the rest of the suite (521 pass / 12 skip) is clean apart from finding 2. Standing with the author: draft until the unresolved-session isolation passes, plus the reset hygiene.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Confirmed the new test-state finding independently on Windows, Bun 1.3.10, at stacked head 70abfec (#135, which includes #133's d56956e). It is not limited to macOS/Bun 1.4.3.

bun test ./test/injection-framing.test.ts ./test/negative-eval.test.ts
  • Unmodified head: 37 pass / 1 skip / 2 fail; both failures are the reported scope-crossing assertions.
  • With only resetSessionScopes() added to injection-framing's afterEach and resetState() added to negative-eval's beforeEach (plus imports): 39 pass / 1 skip / 0 fail.

This was an isolated local verification; I restored the test files afterward and have not pushed changes. Please include those resets with the #133 fix, then carry the update into #135.

Agreed with the re-review: the two unresolved-session evidence probes remain the security blocker for #128 and both PRs. The test reset fix addresses a separate test-isolation problem; it does not repair the evidence writer/filter. Keep the two evidence regressions in the committed suite and verify them after the identity fix.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Rechecked a909685 and both failed jobs. The two previously reported unresolved-session evidence leaks now pass locally, and the test-state reset fix passes too. The current CI failures are a separate test-assertion problem when this branch is merged with current main.

Both jobs fail only at test/security-evidence-unbound-server.test.ts:104:

  • Linux: 537 pass / 12 skip / 1 fail.
  • Windows: 544 pass / 5 skip / 1 fail.

CI tested merge commit 6c5fb2e (a909685 into 61e01b0). Main's startup heartbeat legitimately writes a plugin_load line stamped to repo B. The assertion checks the whole daily log for B's stamp, so it fails on that startup line. A's actual tool_result line has its own sid and no B stamp.

Verified correction: import parseLine from ../src/logfmt.ts, remove the unused resolveRepo import, and replace the two raw-log assertions in probe 2 with:

const results = raw.split("\n").map((line) => parseLine(line)).filter(
  (fields) => fields?.ev === "tool_result" &&
    fields.sid === "ses-unresolved-a" && fields.call === "read-a",
);
expect(results).toHaveLength(1);
expect(results[0]?.output_summary).toBe("UNRESOLVED_A_WRONG_REPO_RESULT");
expect(results[0]?.repo).toBeUndefined();
expect(results[0]?.repoPath).toBeUndefined();

Keep the subsequent assertion that B's memory_evidence response excludes A's marker. This checks the actual protected event and ensures evidence still exists; it does not require unrelated B events to disappear.

Verification on Windows/Bun 1.3.10:

Local verification only; I restored the tracked file and did not push changes. Please land the assertion correction, obtain green CI, and carry these commits into #135 before final stack sign-off.

WhollyMindless added a commit to WhollyMindless/opencode-self-improvement that referenced this pull request Oct 27, 2026
Probe 2 (unbound session retiring another repository's rows through
memory_merge_review) is GREEN already at this head: the identity fix
from the abogartz#133 side (entry binding, readerForSession without the
module-scope fallback) resolves the caller to its own instance's
repository, and the abogartz#131 ownership check then refuses both seats.
Committed as the pinned acceptance case.

Probe 5 is RED here: with the evidence directory poisoned, the merge
retires the loser, its record() throws, and the catch — written for the
lock-acquisition case — reports "nothing was done" while the row IS
superseded on disk. The next commit makes the catch tell the truth
about where the failure landed.
WhollyMindless added a commit to WhollyMindless/opencode-self-improvement that referenced this pull request Oct 27, 2026
…w private rule

abogartz#133's a909685 made a NAMED-but-unresolved session's fresh evidence
private to that session (the re-review's isolation contract). The
readability control here wrote its line for an unbound ses-130 and read
it context-less, so the private branch — working as designed — hid it.
The control now binds ses-130 to the workspace, the shape every session
that reaches a plugin instance has; the traversal, calendar and symlink
doors are untouched. Full suite 554 pass / 1 fail (the known
service-host e2e sandbox case, green in CI).
@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Both re-review probes are committed and green at a909685.

The probes (65812bc, red at d56956e, through the registered hooks/tools with temp stores): probe 1 asserts session B never receives an unresolved session A's fresh output while A still reads its own line; probe 2 keeps the corrected assertion — the foreign repo= stamp is absent, not merely unreadable — and reproduced the exact smoking-gun line from the review before the fix.

The fixes (a909685), at the two boundaries that made them possible:

  • record(): a NAMED session's line is stamped from its OWN resolved scope only. repoScopeFor's module fallback is gone for named callers and remains only for genuinely session-less writes (viewer, out-of-plugin maintenance, CLI). A later instance's setup no longer decides where A's evidence lives.
  • evidenceVisibleTo(): a missing stamp is not the global marker. Explicit repo=global and unstamped lines naming NO session (legacy, session-less writes) keep the historical global reading — that policy is untouched; an unstamped line that names a session is visible only back to that session and to the admin surface. memory_evidence threads the caller's own sid into the predicate, per the agreed direction.

Finding 2 (order-dependent failures on your host): session bindings are module-global, so injection-framing's afterEach now resets state + session scopes, and negative-eval's beforeEach calls resetState() before its scope-crossing tests resolve the ambient reader. The minimal repro bun test ./test/injection-framing.test.ts ./test/negative-eval.test.ts is green (39 pass). gateContext's liveRoot lookup carries the non-firm annotation (the gate's verification tree, never an identity).

Validated: probes 10/10 with the earlier security suites; full suite 542 pass / 5 skip (the known service-host e2e sandbox case only, identical at the reviewed base, green in CI); tsc --noEmit clean; biome lint 0 errors. Body updated. Stack stays draft; #127–#129 stay open until merge.

WhollyMindless added a commit to WhollyMindless/opencode-self-improvement that referenced this pull request Oct 27, 2026
Probe 2 (unbound session retiring another repository's rows through
memory_merge_review) is GREEN already at this head: the identity fix
from the abogartz#133 side (entry binding, readerForSession without the
module-scope fallback) resolves the caller to its own instance's
repository, and the abogartz#131 ownership check then refuses both seats.
Committed as the pinned acceptance case.

Probe 5 is RED here: with the evidence directory poisoned, the merge
retires the loser, its record() throws, and the catch — written for the
lock-acquisition case — reports "nothing was done" while the row IS
superseded on disk. The next commit makes the catch tell the truth
about where the failure landed.
WhollyMindless added a commit to WhollyMindless/opencode-self-improvement that referenced this pull request Oct 27, 2026
…w private rule

abogartz#133's a909685 made a NAMED-but-unresolved session's fresh evidence
private to that session (the re-review's isolation contract). The
readability control here wrote its line for an unbound ses-130 and read
it context-less, so the private branch — working as designed — hid it.
The control now binds ses-130 to the workspace, the shape every session
that reaches a plugin instance has; the traversal, calendar and symlink
doors are untouched. Full suite 554 pass / 1 fail (the known
service-host e2e sandbox case, green in CI).
@WhollyMindless

Copy link
Copy Markdown
Contributor Author

First CI pass on the new heads went red on probe 2 for a fixture-precision reason, now resolved at 203240f:

GitHub tests the PR merge commit, and main has moved to 0.14.10 — #142 added an ev=plugin_load boot record. Instance B's own boot line is a session-LESS write, so under the very rule this round fixed it legitimately stamps B's repository — and it shares the day file with A's tool_result. Probe 2's whole-file "the foreign repo= stamp is absent" scan tripped on B's legitimate stamp; A's own line was correctly unstamped on CI as well (probe 1 and the read-side assertion passed on both jobs). The assertion now scans the line carrying A's marker: still red at d56956e (there the marker line itself carries B's stamp), green at the fix, immune to unrelated stamped lines. Verified both ways locally by running the probe against d56956e's and a909685's src.

No product-code change in 203240f — test file only.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

@abogartz Rechecked 203240f7c33af7dc2f91ddc780521a19f6796b20: my previously reported blockers for #133 are cleared, and this head is ready from my review.

  • 203240f changes only the probe: it requires A's marker line to exist, checks that line for the foreign stamp, and preserves the assertion that B cannot read A's output. It no longer mistakes B's legitimate startup heartbeat for a leak.
  • On this exact head, the two unresolved-session regressions, the three earlier fix(security): session-scoped reads, evidence credential scrub, viewer origin preservation (#127 #128 #129) #133 follow-ups, and the framing/negative-eval pair pass locally on Windows/Bun 1.3.10: 44 pass / 1 skip / 0 fail. The same-session read control also passes.
  • CI run 40430200496 is complete: test, test-windows, lint, and smoke all passed.

This clears the unresolved evidence identity/visibility findings and the test-state leak raised in the re-review. Please complete your final re-review and update the outstanding changes-requested review when satisfied; the PR is still draft. Keep #127–#129 open until the changes are merged. This sign-off is for #133 at the head above; #135's final stacked head is reviewed separately.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

@abogartz All three findings in your 00:30 changes-requested review (attached to d56956e) are addressed on the current head — mapping for the re-review:

  1. Both unresolved-session probes — committed red-first at 65812bc (probe 2 with your corrected assertion: the foreign repo= stamp is ABSENT on A's line; it reproduced your smoking-gun line verbatim at d56956e), fixed at a909685: record() stamps a NAMED session from its own resolved scope only (module fallback kept solely for session-less writes), and a missing stamp is no longer the global marker — explicit repo=global and unstamped sid-less lines keep the historical reading, a named session's unstamped line is private to that session + admin. 203240f only scopes probe 2's scan to A's marker line, because main's 0.14.10 plugin_load heartbeat (fix(capture): fire on turn-end events; session.idle is never emitted (#136) #142) legitimately stamps B's boot line in the shared day file; A's line itself was correctly unstamped there too.
  2. The order-dependent negative-eval scope-crossing failures — your root cause was exactly right: injection-framing's afterEach now calls resetState() + resetSessionScopes(), and negative-eval's beforeEach calls resetState() before setRepoScope(null). The minimal repro bun test ./test/injection-framing.test.ts ./test/negative-eval.test.ts passes; the ambient reader/writer pair can no longer resolve through a previous file's repo.
  3. gateContext.liveRoot note — the non-firm lookup now carries the verification-tree-vs-identity comment (finding 3 landed with the fix).

CI green on 203240f (run 40430200496: test, test-windows, lint, smoke); local full suite 542 pass / 5 skip. When your re-verification at this head is satisfied, would you dismiss the changes-requested so the stack can leave draft on your signal? Keeping it draft until then; #127–#129 stay open until merge.

The context hook awaited the store read and then filtered with the ambient current: a concurrent session hook dispatching during that await moved it, and the prompt of one session filled with the other repo rows. Every model-facing flow now resolves its caller identity SYNCHRONOUSLY at entry (from the event or ToolContext sessionID, never a global re-read after an await) and carries it through the flow: injection sinks, recall, contextual pulls, compaction, prune, decay, gate scope reads, and the write stamps behind GateContext.sessionID.

Unknown plugin-session identity now fails CLOSED to explicit/legacy global rows (the old !cur -> true fail-open meant an unbound serve-host session saw every repo private frontier). Administrative all-repository breadth is a property of the entry point (ADMIN_READER: the viewer, out-of-plugin maintenance), never of a missing session. The deletion-audit origin fields and restore-entry schema fields belong to abogartz#129 and ride with the shared files.
…artz#128)

afterTool persisted summarize(text) - the first 80 folded characters of tool output - and record() persisted caller fields verbatim, so a recognized credential in ordinary tool output survived byte-for-byte in evidence/<date>.logfmt in the DEFAULT configuration (auto-capture off) and rode back into the model through memory_evidence. record() now scrubs every string field it writes; afterTool redacts the COMPLETE output before folding/truncation, so a token sliced at the 80-char boundary or a PEM block cut before its END marker cannot survive as an unmatchable fragment. The tool_result line itself still lands - telemetry is kept, the secret is not. Old files are untouched: remediation of past evidence stays separate (abogartz#74).
…abogartz#129)

The standalone viewer has no repository scope, so an edit appended the replacement UNSTAMPED - isVisibleHere reads an unstamped row as GLOBAL: a typo fix in the viewer made a repo-private memory recallable and injectable in every project. The replacement now carries the target's stamp verbatim (an unstamped target lands explicitly repo=global - same visibility, stated honestly on the line), omitted issue/tags/kw survive the edit instead of erasing import/auto-capture provenance and retrieval aliases, the delete-audit line records the origin, and restore-entry - schema, route and UI - replays it. The viewer remains the explicit ADMIN read surface: it lists every repo, and now shows which repo each row belongs to.
…rtz#129

Three suites driving the real registered hooks, the real evidence
writer and the real viewer routes, built from the reproductions posted
with the issues. On the reviewed revision (cf9b73c) 11 of the 12 tests
fail - the survivor is the deliberate single-session no-regression
guard, which passes everywhere. On this branch all 12 pass, and the
full suite (527) stays green.
The repo-scoping paragraph now states the abogartz#127 semantics (identity is
the calling session's, an unbound plugin session sees global rows only,
the viewer's missing scope never decides a row's visibility), and the
redaction paragraph names the abogartz#128 durable audit boundaries.
…ombstone probes

Three committed red-first regressions from the a8c5b7a follow-up review:
(1) an unbound session must not inherit the LAST loaded plugin instance
repository through the module-scope fallback (multi-workspace process);
(2) memory_evidence must not surface another repository tool_result lines
from a shared store; (3) a credential in a merge reason scrubs in the
evidence line but rode the loser daily row verbatim. Red on a8c5b7a.
…on evidence, scrub tombstones

Three fixes for the committed regressions (review probes 1, 3, 4):

- readerForSession drops the module-scope fallback: in a process that
  loaded several plugin instances the module scope belongs to whoever set
  up LAST, which is another workspace. Plugin flows now bind an unknown
  session at entry — tools, hooks and capture bind it PROVISIONALLY to
  THIS instance's setup location (a real event/API identity still
  replaces it), so a reader resolves the caller's own repository or
  global rows, never a foreign repo. gates.ts treats "?" as the ambient
  readerFromSid case, as everywhere else.
- Evidence lines carry the recording repository (repoScopeFor at
  record()), and memory_evidence filters through evidenceVisibleTo, the
  evidence-line twin of isVisibleTo — a shared log partitions like the
  store does.
- markManySuperseded scrubs its string fields at the write boundary, so
  a credential in a merge/decay/update reason cannot persist in the
  retired daily row while the evidence line beside it was cleaned (abogartz#128's
  rule, the one line it was short).

Tests: five existing tests relied on the module-scope borrowing this
review removed; their sessions are now bound explicitly — the shape the
plugin itself uses (frontier, injection-framing, audit scrub). The
README's repo-scoping and redaction paragraphs state the new semantics.

Full suite 540 pass / 5 skip / 1 fail on this machine: the failing case
is the pre-existing service-host e2e stamp scenario, which fails
identically at a8c5b7a here (sandboxed service cannot run git) and is
green in CI. tsc clean; biome lint 0 errors.
…e probes

Committed red-first regressions for the re-review finding on d56956e:
fresh evidence for a session whose repository cannot be resolved was
globally readable (no stamp read as the legacy-global marker) or, with
a second plugin instance loaded, borrowed the last setup module scope.
Probe 2 keeps the reviewers corrected assertion: the foreign repo stamp
must be ABSENT, not merely unreadable. Red at d56956e.
…, never borrowed

The re-review's two probes, fixed at the two boundaries that made them
possible:

- evidence.ts record(): a NAMED session's line is stamped from its OWN
  resolved scope only. The module-scope fallback (repoScopeFor) is gone
  for named callers — in a multi-instance process it belongs to whoever
  set up LAST, which is how A's tool_result ended up stamped with B's
  repository. Only session-less writes (out-of-plugin maintenance,
  viewer, CLI) take the process scope.
- memory.ts evidenceVisibleTo(): a missing stamp is not the global
  marker. An explicit repo=global line and a line with no stamp AND no
  named session (legacy, session-less writes) keep the historical
  global reading; a line a NAMED session wrote while its repository was
  unresolvable is visible only back to that session and to the admin
  surface. memory_evidence threads the caller's sid into the predicate.

Also from the re-review (finding 2, order-dependent suite failures on
some hosts): session bindings are module-global, so injection-framing
now resets state + session scopes in afterEach, and negative-eval's
beforeEach clears the ambient session (resetState) before its
scope-crossing tests resolve the ambient reader. gateContext's liveRoot
gains the non-firm-lookup annotation (it is the gate's verification
tree, never an identity); README states the missing-stamp-is-not-global
rule.

Red-on-base: test/security-evidence-unbound-server.test.ts (committed
first) fails both probes at d56956e — probe 2 with the exact foreign
repo= stamp. Full suite 542 pass / 5 skip (this machine: the known
service-host e2e sandbox failure, identical at the reviewed base,
green in CI); the finding-2 minimal repro
(bun test ./test/injection-framing.test.ts ./test/negative-eval.test.ts)
passes; tsc clean; biome lint 0 errors.
CI runs the PR merge commit, and main (0.14.10, abogartz#142) added an
`ev=plugin_load` boot record: instance B's own line — a session-less
write, legitimately stamped with B's repository under the very rule
this round fixed — shares the day file with A's tool_result. Probe 2's
whole-file `not.toContain` tripped on B's legitimate stamp; A's line
itself was correctly unstamped on CI too. Scan the line carrying A's
marker instead: the smoking-gun line is the one that must lose the
foreign repo= field. Red at d56956e (A's own line carries B's stamp
there), green at the fix; unrelated stamped lines cannot redden it.
@WhollyMindless

Copy link
Copy Markdown
Contributor Author

@abogartz Main has advanced to 2bdf024 (0.14.11, including #145's export/import path containment), and both #133 and #135 now have the same textual conflict in src/portable.ts's import block. Neither PR has merged; this is an integration blocker in addition to the outstanding review state.

The resolution must retain main's containment/filesystem imports and #133's explicit reader imports. Replace the conflicted block with:

import { constants } from "node:fs";
import { mkdir, open } from "node:fs/promises";
import { dirname, join } from "node:path";
import { allowOutsideStorePaths, exportsDir, memoryRoot } from "./config.ts";
import { resolveContained } from "./containment.ts";
import { isActive, isVisibleTo, loadAll, readerFromSid, type Memory } from "./memory.ts";

Keep the subsequent imports. In particular, retain isVisibleTo/readerFromSid used by the scoped decay implementation and retain the threaded sessionID in importMemories; main's new path checks and export writer also need to survive. The rest of the merge applied automatically.

I verified the conflict on both exact heads (203240f and 4beccfa) against 2bdf024, then resolved it in an isolated local merge of the complete #135 stack:

  • bun run typecheck: passed.
  • Full bun run test on Windows/Bun 1.3.10: 576 pass / 10 skip / 16 fail, with no failures in the security suites.
  • All 16 identical failing test names reproduce on unmodified main 2bdf024 when running the affected six files. These include export EINVAL failures and symlink-creation EPERM on this host; they are not new failures introduced by the merge. This local run is therefore not a green full-suite result.

Please update #133 against current main with the combined imports, then replay #135's five commits onto the updated #133 head and rerun Linux/Windows CI. My prior sign-offs remain tied to the previously tested heads; the new integration needs fresh checks.

Local merge was aborted after verification and the review worktree restored; no PR branch was changed or pushed.

WhollyMindless added a commit to WhollyMindless/opencode-self-improvement that referenced this pull request Oct 27, 2026
Probe 2 (unbound session retiring another repository's rows through
memory_merge_review) is GREEN already at this head: the identity fix
from the abogartz#133 side (entry binding, readerForSession without the
module-scope fallback) resolves the caller to its own instance's
repository, and the abogartz#131 ownership check then refuses both seats.
Committed as the pinned acceptance case.

Probe 5 is RED here: with the evidence directory poisoned, the merge
retires the loser, its record() throws, and the catch — written for the
lock-acquisition case — reports "nothing was done" while the row IS
superseded on disk. The next commit makes the catch tell the truth
about where the failure landed.
WhollyMindless added a commit to WhollyMindless/opencode-self-improvement that referenced this pull request Oct 27, 2026
…w private rule

abogartz#133's a909685 made a NAMED-but-unresolved session's fresh evidence
private to that session (the re-review's isolation contract). The
readability control here wrote its line for an unbound ses-130 and read
it context-less, so the private branch — working as designed — hid it.
The control now binds ses-130 to the workspace, the shape every session
that reaches a plugin instance has; the traversal, calendar and symlink
doors are untouched. Full suite 554 pass / 1 fail (the known
service-host e2e sandbox case, green in CI).
@WhollyMindless

Copy link
Copy Markdown
Contributor Author

@abogartz Rechecked the rebased head 9a7c674177ac3e83e7683e72558cc3b326b42835 against main 2bdf024. The integration blocker is cleared, and my #133 sign-off carries forward to this exact head.

  • GitHub reports the branch mergeable again.
  • The src/portable.ts resolution matches the combined imports previously verified: main's containment/filesystem protections remain, alongside isVisibleTo/readerFromSid and the explicitly threaded importing session.
  • git range-diff shows the other nine commits unchanged; the reader commit's changes are the expected adaptation to current main.
  • Local Windows/Bun 1.3.10 check at this head: all 17 security tests passed, and bun run typecheck passed.
  • CI run 40574638742 is now fully green: test, test-windows, lint, and smoke. Windows finished successfully after the initial three-check notification.

No outstanding blocker from my review of #133 at this head. The PR is still draft and awaits the maintainer's final review/state update. #135's new stacked head will be checked separately.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

GitHub flagged this branch as conflicting with main — main moved to 0.14.11 while the stack was in review (#145 export/import containment for #24, plus #146's capture-sid-race session-scope teardown). Rebased: head is now 9a7c674, MERGEABLE.

The only conflict was src/portable.ts's import block, a pure intersection of the two changes: main's containment machinery (resolveContained, exportsDir, constants.O_NOFOLLOW write path) and #127's decay-filter rework (readerFromSid + isVisibleTo in findStaleOpen). Resolved as their union; the now-unreferenced isVisibleHere import is dropped, everything else auto-merged (their containment hunks and our reader threading never touched the same lines).

Parity evidence that the rebase introduced nothing: full bun test on this machine fails exactly the same 17 tests on pristine main and on this rebased branch (557 vs 574 pass, the +17 are this PR's suites; the 17 reds are #145's export/symlink cluster — O_NOFOLLOW → EINVAL on this Windows/Bun 1.3.10 host — plus the known service-host e2e sandbox case), all of which are green in Linux/Windows CI. On the rebased head: security suites 17/17, tsc clean, lint 0 errors. #135 follows on top at 152d613.

@WhollyMindless
WhollyMindless marked this pull request as ready for review October 27, 2026 22:12
@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Consolidated record for the final review, keyed to the current head: every item in the 00:30 changes-requested review (attached to the pre-rebase d56956e) is addressed on 9a7c674:

  1. Probe 1 + probe 2 (unresolved-session evidence leaks) — src/evidence.ts stamps a NAMED session only from its own resolved scope (named ? sessionScope(sid) : repoScope()); src/memory.ts evidenceVisibleTo implements missing-stamp-is-not-global (explicit repo=global and sid-less lines stay global; a named session's unstamped line is private to it + admin). Committed red-first as 473add2 (both red at d56956e, probe 2 reproducing the exact foreign-stamp line) → fixed in bf2bbf7; green here.
  2. Order-dependent suite failures (fr-cap leak + unreset ambient state) — injection-framing's afterEach calls resetState() + resetSessionScopes(); negative-eval's beforeEach calls resetState(). The minimal repro passes as a pair on this head.
  3. gateContext.liveRoot note — the non-firm verification-tree-vs-identity comment is in src/index.ts.

State: MERGEABLE on main 0.14.11, CI green (run 40574638742: test, test-windows, lint, smoke), tsc clean, lint 0 errors, range-diff clean vs the previously signed-off stack, and the re-reviewer's sign-off explicitly carried forward to this head. Note on local test runs: 17 tests fail on some Windows hosts (Bun 1.3.10 + O_NOFOLLOW/EINVAL in #145's export machinery) — identical on pristine main, green on CI's Bun 1.4.4; none of them are from this PR.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Erratum to the local-test notes above — the "known environment" phrasing undersold what we now know with root causes, so here is the precise version (filed as #147/#148 so it lives upstream, not in this thread):

Three separate, fully-diagnosed reasons a full-suite run on a Windows dev box shows reds unrelated to this stack — and one invocation trap that made this confusing to report:

  1. Bun version skew — 16 of the 17. fix(security): confine export/import paths to the store (#24) #145's export machinery needs the CI-pinned Bun 1.4.4; on 1.3.x, O_NOFOLLOW throws EINVAL on Windows. Re-running this head under 1.4.4 locally: all 16 green. Not a defect, just version drift between a dev box and the CI pin.
  2. Missing skip guards — test/containment.test.ts: 2 of 7 symlink tests miss the file's win32 skip guard and EPERM on unprivileged Windows #147. Two of containment.test.ts's seven symlink-fixture tests lack the skipIf(win32) guard the file uses on its other five; on a dev box without developer mode the fixture's own symlinkSync EPERMs before product code runs. Not a defect.
  3. The service-host e2e cannot pass on Windows at all — e2e/stamp.test.ts gives the service a POSIX-only PATH — service-hosted stamp test can never pass on Windows (and no CI job runs e2e there) #148. e2e/stamp.test.ts:103 hands the spawned service a hard-coded POSIX PATH (/usr/bin:/bin:/…), so the service's plugin can never find git on Windows and the origin-derived key at line 238 can never match — guaranteed red on every Windows machine, ever. It goes unnoticed because test:e2e runs only in the ubuntu smoke job and test-windows runs bun test ./test/, which excludes ./e2e/. The Session repo identity never binds on host 2.1.4 — recall silently partitions writes under the server cwd #90 contract itself is intact — the failing row's repoPath correctly resolved the session's project; only the fixture's sandbox is broken. Not a defect in this stack, and now not a secret either.

The invocation trap: bun run test (CI's test jobs) ≠ bun run test:e2e (CI's smoke job) ≠ bare bun test (Bun's default pattern sweeps e2e/ too). The "17 local reds" quoted across this stack's comments were a bare-bun-test number; on CI's own definitions those lanes are separately and fully green on this head (runs referenced above), Linux and Windows.

Net for reviewers: at 9a7c674, local Windows reds = exactly items 2 + 3 (post-1.4.4), root-caused, CI-invisible by job-layout, none originating in this stack.

@abogartz abogartz left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Final pass — APPROVED (supersedes my CHANGES_REQUESTED on d56956e)

Method: detached worktrees of 9a7c674 and of the pre-fix base cf9b73c, macOS / Bun 1.4.3. Claims re-run against the tree, not read. The diff, not the body, is the contract.

All three blocking findings are closed — verified in both directions

1 — unresolved-session evidence probes: fixed, and not by the shortcut I warned against.
Red-first pair verified at the correct post-rebase commits (d56956e ≡ 98fe87f by git patch-id --stable):

  • At 473add2 (regressions in, fix not yet applied) both probes are RED, with exactly the leak from my review: ev=tool_result sid=ses-unresolved-a repo=<B's key> repoPath=…/repo-b.
  • At 9a7c674 both GREEN.

The fix is the prescribed one, not a global stamp that would re-create probe 1: record() drops the module fallback for named callers (const scope = named ? sessionScope(sid) : repoScope(), src/evidence.ts:55-56), and evidenceVisibleTo() (src/memory.ts:691-712) makes a missing stamp not the global marker — explicit repo=global and unstamped-and-session-less stay global; unstamped-plus-named-session resolves to that session alone, failing closed for everyone else. memory_evidence threads the caller's own sid into the predicate (src/index.ts:739).

2 — the macOS/Bun order-dependent suite break: fixed.
Your minimal repro bun test ./test/injection-framing.test.ts ./test/negative-eval.test.ts gives exactly the 2 predicted failures at d56956e (negative-eval.test.ts:441 and :461, "scope crossing — the injected block") and 39 pass / 1 skip / 0 fail at 9a7c674.

3 — gateContext.liveRoot annotation: present (src/index.ts:332-337, non-firm verification-tree note). Guard discipline re-checked: firm lookups at src/index.ts:330/362/382/384, rememberSessionDir clears the provisional flag, resetSessionScopes clears the set.

Independent verification of the #127 entry binding

repoScopeFor survives at exactly three sites, all correct: the ambient reader (src/memory.ts:653, documented out-of-plugin), and the two write stamps (src/memory.ts:273, src/portable.ts:265). The module fallback there is unreachable for a real session because toolIds() binds provisionally synchronously at entry (src/index.ts:361-363) and bindSessionIdentity ends with the same provisional bind — so by the time a row is stamped, the sid resolves through the session map. bindSessionProvisional never overwrites an existing binding (src/repokey.ts:123). No model-facing tool exposes a repo/repoPath field (only the documented global boolean), so the partition cannot be forged from a tool call.

Red-on-base reproduced independently

Copying this PR's suites onto pristine cf9b73c src: 14 fail / 1 pass. The single green is the ordinary single-session flow still injects its own repo's rows — the deliberate no-regression guard, green by design, exactly as the body states.

#129 round trip checked end to end

audit line → deletedRows() → data-repo/data-repo-path (escaped) → /api/restore-entry → RestoreEntryBody → appendMemory. RestoreEntryBody declares repo/repoPath (src/schema.ts:206-207), so zod does not strip them — the restore half genuinely works. Probed the schema directly: real paths with spaces ACCEPT, repoPath with an embedded newline REJECT (no logfmt line forging).

Gates on this host

bun run gate: 578 pass / 12 skip / 0 fail + e2e 11 pass / 0 fail, tsc clean, biome 0 errors, merge gate: all green, exit 0. (The gated-injection.test.ts ENOTDIR traces are the intentional memory-root-is-a-file degradation tests, not failures.) No .github/workflows files touched, so the CLI merge is not blocked by the token's missing workflow scope.

Non-blocking (follow-up, not a merge condition)

  1. record() spreads ...scrubFields(fields) after the computed repo/repoPath/sid/call (src/evidence.ts:63-66), so a field literally named repo would outrank the authoritative stamp. I audited every call site: none does this today. Cheap hardening: spread fields first, or delete reserved keys in scrubFields.
  2. Genuinely session-less lines still take the module repoScope(), i.e. last-setup-wins in a multi-instance process. Affected lines are non-sensitive telemetry (plugin_load, store_lock, init_*) and the behavior is documented; threading the instance dir would close it symmetrically.

Both are defense-in-depth on paths I could not reach. Approving.

@abogartz
abogartz merged commit 8ad23d2 into abogartz:main Oct 28, 2026
4 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.14.12 🎉

The release is available on:

Your semantic-release bot 📦🚀

abogartz-opencode-self-improvement Bot pushed a commit that referenced this pull request Oct 28, 2026
## [0.14.14](v0.14.13...v0.14.14) (2026-10-28)

### Bug Fixes

* **security:** an unresolved session has no write target ([#152](#152)) ([e1256e0](e1256e0)), closes [127/#133](#133)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

2 participants