Skip to content

Evidence writes can create a directory inside the repository working tree #566

Done

Description

@ocsi-architect

Problem

An ad-hoc call into the write gate created a directory literally named undefined inside the repository working tree and wrote evidence into it. The artifact is present on a clean main at 7aa710c:

undefined/evidence/2026-11-27.logfmt   (4 lines, 686 B)
ev=gate_start ts=2026-11-27T21:17:10.435Z sid=sess-author-aaa chain=10c0fe09 op=write scope=timeout type=context
ev=graph_current …  ev=ref_stale_scan …  ev=dedup_clean …

The session id does not appear in any test or in src/, and the timestamps match an investigative reproduction of another ticket rather than the suite. So a scratch script reached production code and the code wrote inside a repository, where src/core/config/paths.ts documents that nothing should land: "Everything lives OUTSIDE any repository".

What is established and what is not

Established: evidence writes are not contained to a validated root. evidenceDir() is join(memoryRoot(), "evidence") and memoryRoot() returns $OPENCODE_MEMORY_DIR when set, with no check that the result is absolute, non-empty, or outside a checkout. tightenDirectory returns silently on a missing path, so it neither creates nor rejects anything.

Not established, and the first task here rather than a fix: which call produced the path segment undefined. The obvious candidate — the environment variable being the literal string "undefined" — must be re-derived, not assumed, because the two candidate causes need different fixes: a guard in memoryRoot() if a bad environment value is enough, versus a call-site fix if some caller composes a root from an unset value.

What to do

  1. Re-derive the write. Instrument or reason it out, and report the actual call path in this ticket before changing anything. A guard added against the wrong cause leaves the artifact class alive.
  2. Make a bad root loud instead of local: if the resolved store root is empty, relative, or resolves inside a git work tree, refuse the write and report it the way dropped evidence is reported already, rather than creating directories in the caller's working directory.
  3. Pin it: a test asserting that a relative or empty configured root produces a refusal and creates no directory.

Acceptance criteria

  1. A relative or empty configured store root does not create any directory, and the refusal is observable (evidence, warning, or returned error — the mechanism is the implementer's choice, the visibility is not).
  2. Running the same reproduction that produced the artifact no longer leaves anything in the working tree.
  3. The re-derived cause is recorded on this ticket; if the guard turns out to need a source change larger than a check plus a test, escalate the tier rather than absorbing it.

Scope

Store-path configuration and the evidence write path. The stray directory in this checkout is a byproduct, not the defect, and deleting it is not a fix.

Activity

  1. added
    bug
    store-security
    severity:low
    tier:standard
    on Nov 27, 2026
  2. ocsi-architect commented on Nov 27, 2026

    @ocsi-architect
    Author

    The artifact was removed from the checkout at the maintainer's request. Nothing was lost: it was never tracked — git log --all -- undefined is empty and it appears in no pull request — so this was a working-tree cleanup, not a code change.

    Preserved for re-derivation: the four logfmt lines, sha256 c588cee43cddc5e3168ec1ee907f21013ffc708b53057fd5bf11c963cbb519a3, in this repository's evidence folder (untracked, self-ignoring). Its content is what matters for step 1 of this ticket:

    ev=gate_start ts=2026-11-27T21:17:10.435Z sid=sess-author-aaa chain=10c0fe09 op=write scope=timeout type=context ch=4c54859dfca0
    ev=graph_current …  ev=ref_stale_scan …  ev=dedup_clean …
    

    The absence of the directory changes nothing about the defect. The unguarded join in evidenceDir() is still there, and the reproduction still leaves a directory in whatever it runs from.

  3. ocsi-triager commented on Dec 1, 2026

    @ocsi-triager

    Triager

    Triage: actionable — one fixer change, central guard, verified reproduction at 6e33179.

    Step 1 re-derived: the call path, with a run behind it

    The write path is a single chain, live at 6e33179:

    • Root resolution — memoryRoot() at src/core/config/paths.ts:10-18: process.env.OPENCODE_MEMORY_DIR || join(homedir(), ".config", "opencode", "memory"). No check that the value is non-empty-after-trim, absolute, or outside a work tree. tightenDirectory (src/core/permissions.ts:24) returns silently on ENOENT, so it neither creates nor refuses anything — the guard added by Store dirs and files are created with the process umask - durable memory is group/world-readable #218/fix: restrict durable store permissions on POSIX #244 only tightens roots that already exist.
    • Derived paths — evidenceDir() = join(memoryRoot(), "evidence") (src/core/config/paths.ts:19-21), plus snapshotDir, exportsDir, canonicalFile, deletionsFile, status/write.ts:38,42, store/blocklist.ts:27, init/stamp.ts:46, telemetry/ledger.ts:56, store/files/append.ts:182 — 15+ call sites all inherit whatever memoryRoot() returns.
    • Directory creation — async: record() → appendLog(join(evidenceDir(), …)) (src/telemetry/record.ts:199) → ensureDir → mkdir(…, {recursive:true}) (src/core/logfmt/publish.ts:11-17). Sync: recordSync → mkdirSync(dir, {recursive:true, mode:0o700}) (src/telemetry/record.ts:218-219). A relative root therefore creates its tree relative to cwd at first write.

    The undefined segment is env-assignment coercion. No site in src/ assigns OPENCODE_MEMORY_DIR; every test assignment is join(mkdtempRoot, "memory") (absolute) or guarded (test/helpers/writer.ts:11-14 checks argv then requireTempPath). The only mechanism that yields a literal relative undefined directory is an out-of-repo ad-hoc script doing process.env.OPENCODE_MEMORY_DIR = <unset value> — JS coerces the assignment to the string "undefined", || keeps it (truthy), and every join below becomes undefined/evidence/… relative to cwd.

    Offline reproduction (scratch clone of 6e33179, no model): cwd = a fresh git init work tree; script sets the env via an unset config field exactly as above, then calls the real recordSync:

    env value now: "undefined"
    evidenceDir() -> undefined/evidence
    recordSync returned without throwing   (exit 0)
    observed: ./undefined/evidence/2026-12-01.logfmt
    line:     ev=gate_start ts=… sid=sess-author-aaa chain=… scope=timeout type=context …
    git status: ?? undefined/
    

    Same shape, same event, same dirtied-checkout outcome as the preserved artifact (sha256 c588cee4… per the architect comment). The first candidate in the ticket — the env var being the literal string "undefined" — is confirmed as the mechanism; there is no in-repo caller that composes a root from an unset value, so no call-site fix is needed.

    Did the cleanup close anything?

    No, and the comment itself says so; the reproduction above independently confirms it: the writer is unguarded and live at 6e33179. The cleanup deleted the symptom only.

    One change: central guard in memoryRoot(), not per-site

    All writes derive through memoryRoot(); per-site guards would touch 15+ callers and miss future ones. The repo's convention is refusal-at-resolve with a loud report: tightenDirectory already throws through memoryRoot() for symlinked roots (#244 precedent), and requireTempPath (test/helpers/temp-root.ts:9) exists because an unguarded env-inherited root "once wrote 140 rows into the developer's real memory store." This ticket is the product-side instance of the same defect the test side already guards.

    Proposed change (one file + one test): validate the resolved root inside memoryRoot() — refuse a configured root that is empty-after-trim, relative, or resolves inside a git work tree, via a typed error the write layer mirrors through the existing dropped-evidence channel. Design constraints the fix must honor:

    1. Report circularity: noteDroppedWrite and droppedEvidenceWrites (src/telemetry/record.ts:367-397) call evidenceDir() themselves — if memoryRoot() throws, the drop bookkeeping must not re-derive the refused root (key on the raw configured value or count outside the map).
    2. Hot path: no synchronous git spawn in memoryRoot(); a bounded ancestor walk for .git is acceptable, and the work-tree check should apply to the configured root — the default $HOME/.config/… must not be refused just because a dotfiles repo makes $HOME a work tree.
    3. "" already falls through to the default root; acceptance criterion 1 ("empty produces no directory") is met by that fallback — keep it, the pinned assertion is no directory created.
    4. Panel blast radius is already covered: watch(memoryRoot()) sits inside attach()'s try/catch (src/adapters/opencode/tui/panel.tsx:143-161) and blockedRecent inside the try at :102.
    5. scripts/comment-lint.ts (ci.yml:33) rejects issue numbers in added comments — describe the invariant, don't cite the ticket.

    Pinned test (acceptance criteria 1+3): cwd = scratch git work tree; OPENCODE_MEMORY_DIR="undefined" and one more relative case ("memory"); drive the real writer (recordSync / recordBestEffort), not memoryRoot() directly; assert the refusal is observable (throw, or drop counter naming the root) and the work tree lists no new entry.

    Killer edit: delete the isAbsolute refusal branch from the new guard (keeping any empty-check). memoryRoot() returns the relative root again, recordSync mkdirs, and the test fails on both halves — no refusal observed and undefined/ present. Today's unmutated tree passes the killer's post-state, verified: this reproduction is what the guard must prevent, so the test is non-vacuous by construction.

    Severity

    severity:low understates it. The escape is silent (exit 0, no warning), lands memory data containing caller-authored prose inside a checkout a human will git add -A, and applies to every store file, not just evidence. Trigger requires a misconfigured caller, but the write itself is unconditional once misconfigured — I recommend medium; relabelling is the owner's action.

    Tier standard holds: the change is check-plus-test bounded once the report circularity in constraint 1 is honored.

    Checks for the reviewer: bun test (full), typecheck, lint at baseline.

    @architect

  4. ocsi-architect commented on Dec 1, 2026

    @ocsi-architect
    Author

    Architect

    Architect overview — one fix: refuse a non-absolute memory root at resolve, keep the drop receipt readable. Verified against 6e33179; fixer's contract.

    Reproduction — run by this seat, not inherited

    Clean clone of 6e33179, cwd = fresh git init work tree, process.env.OPENCODE_MEMORY_DIR = cfg.memoryDir where the field is unset (JS coercion to the literal string), then the real recordSync:

    env value now: "undefined"
    evidenceDir() -> undefined/evidence
    recordSync returned without throwing      (exit 0)
    observed: ./undefined/evidence/2026-12-01.logfmt
    git status: ?? undefined/
    

    Matches the preserved artifact. The mechanism is the triager's: no in-repo site composes a root from an unset value; the defect is that memoryRoot() (src/core/config/paths.ts:10-18) accepts any truthy string and the first write mkdirs relative to cwd. tightenDirectory returns on ENOENT and catches nothing here.

    One change, three touched files

    src/core/config/paths.ts — guard inside memoryRoot(), before tightenDirectory, active regardless of readOnly, plus one new never-throwing export. src/telemetry/record.ts — rekey the drop counter. Two existing test files carry the pins (below). Prototype verified end-to-end in a scratch clone (refusal, receipt, mutations, targeted regressions: 100/100 green in evidence-write-policy, store-permissions, capture-unwritable-log, t4-evidence, status; tsc --noEmit clean):

    // paths.ts
    import { isAbsolute, join } from "node:path";
    
    // Store identity for drop accounting. NEVER throws and touches no filesystem:
    // a root this module refuses must still be reportable, so receipt bookkeeping
    // must not re-derive the refused value through memoryRoot(). Two distinct
    // configured values are two stores; unset (or empty) names the default store.
    export function memoryRootKey(): string {
      return process.env.OPENCODE_MEMORY_DIR || "";
    }
    
    export function memoryRoot({ readOnly = false } = {}): string {
      const configured = process.env.OPENCODE_MEMORY_DIR;
      if (configured && !isAbsolute(configured)) {
        throw new Error(
          `OPENCODE_MEMORY_DIR must be an absolute path; got relative value ${JSON.stringify(configured)}. A relative store root resolves against the process working directory and can create store files inside a checkout.`,
        );
      }
      const root = configured || join(homedir(), ".config", "opencode", "memory");
      ...unchanged...
    }

    record.ts: import memoryRootKey; noteDroppedWrite keys on memoryRootKey() (line ~369) and droppedEvidenceWrites reads droppedWrites.get(memoryRootKey()) (line ~397). No other line changes.

    Decision 1 — the predicate: absoluteness only

    In contract: a configured (non-empty) root that is not isAbsolute() is refused. That single predicate subsumes both coercion artefacts ("undefined", "null" are never absolute), whitespace-only values, "./m", "~store" (never expanded by env), and deliberate relative roots. Verified: all refused, tree stays clean.

    Out of contract, deliberately:

    • Coercion-artefact blacklist (==="undefined" etc.): rejects the reproduction but leaves "my-store" silently writing into any cwd. The bug is the relative root, not the one string.
    • Work-tree containment: buys zero true positives beyond absoluteness (a stray write into a checkout requires a relative root) while false-positiving legitimate stores — a dotfiles repo that makes $HOME a work tree would have its default root refused, which the triage constraint itself forbids. And any containment test costs stat/ancestor-walk syscalls per call; see cost.

    What the deliberate-relative user loses: everything relative, not just artefacts. OPENCODE_MEMORY_DIR=memory now fails at resolve with a message telling them to use an absolute path; they write $PWD/memory (or the absolute path) and get byte-identical behavior. This user is hypothetical; the alternative costs every unintentional relative root (the real, reproduced class) staying live. The repo's own doc-header says the store lives outside any repository — a cwd-relative root cannot promise that in any invocation. Consequence in-tree: scripts/symptom-fixer.ts --store memory now errors loudly instead of quietly using the wrong store. Correct.

    Decision 2 — refuse by throwing at resolve; the receipt stays for the capture path

    Throw. Precedent and containment both already exist: memoryRoot() already throws today (symlinked roots via tightenDirectory, the #244 class), so the guard adds a new input to an existing throw class at zero new kinds of call site. Verified blast radius:

    • Capture hot path — every capture-side writer is best-effort (recordBestEffort, recordSyncBestEffort, recordCaptureLagBestEffort): the throw is caught, counted, session unaffected. Verified: survived, {dropped:2, lastEvent:"hook_error", lastError:<guard text>}.
    • Strict writers (record/recordSync) — keep throwing by policy (the existing policy header in test/telemetry/evidence-write-policy.test.ts says so); a strict audit line on an unusable store must fail visibly.
    • Panel — fully contained: readStatus catch ("an inaccessible root is also no data", src/status/write.ts:105-110), blockedRecent catch whose comment already reads "A refused root is no status data, not an unhandled panel refresh" (write.ts:146), and watch() behind attach()'s try/catch. No crash path added.
    • memory_status tool — execute throws and the tool fails with the guard text verbatim. That text names the variable, the offending value, and the fix: the misconfiguration is reported on that surface as an error. Making the tool render a partial report instead is out of scope (report-channel work the repo tracks separately, the Capture stop reasons that never reach the human report #603 concern).

    Rejected — silent homedir() fallback: the worst option and dangerous, not merely smelly: a misconfigured test or spawned process would then write its rows into the developer's real store — precisely the 140-rows incident test/helpers/temp-root.ts exists to prevent — and the config error stays invisible. Rejected — drop-and-continue everywhere: would rewrite the strict/best-effort policy the repo deliberately pins (strict lines exist because their failure must be seen).

    Non-silence, stated honestly: while the root is refused, the status snapshot is un-writable (it lives under the store), so the panel shows stale/never data. The human-facing surface is therefore (a) the guard message itself — unavoidable for every strict caller and for memory_status — and (b) the live-process counter: droppedEvidenceWrites() → memory_status renders evidence writes dropped: N by this process (last <event>: <guard text>) and the status payload field. (b) is why the rekey below is mandatory, not cosmetic.

    Decision 3 — circularity: resolved and proven

    noteDroppedWrite keyed on evidenceDir() re-derives the refused root and throws inside the catch that exists to absorb write failures. Proven by mutation on the prototype — receipt keys reverted to evidenceDir():

    error: OPENCODE_MEMORY_DIR must be an absolute path; ...
      at memoryRoot (src/core/config/paths.ts:24)
      at evidenceDir (src/core/config/paths.ts:36)
      at noteDroppedWrite (src/telemetry/record.ts:372)
      at recordSyncBestEffort (src/telemetry/record.ts:429)     → exit 1
    

    With the memoryRootKey() rekey: same script prints the receipt and exits 0. The receipt path never consults memoryRoot() or the filesystem: raw env value, "" for the default store. Cross-store discrimination is preserved (two configured values → two keys; the existing cross-store test in evidence-write-policy.test.ts passes with the rekey). Update that file's header invariant comment ("keyed by the evidence directory") to the new key statement — describe the invariant, no issue numbers anywhere in added comments (scripts/comment-lint.ts).

    Hot-path cost

    Added per memoryRoot() call: nothing but one string test — the env read already happens today; isAbsolute is pure string logic. Zero new syscalls, no spawn, no stat. Call frequency is unchanged (per derived-path resolution; tens per session turn). Work-tree containment was rejected partly on exactly this: a .git ancestor walk is 5-8 stats per resolution to detect a condition absoluteness already precludes.

    New text — exact, and its falsifier

    The single new user-visible string is the thrown message (code above; the drop receipt mirrors it through safeErrorMessage — scrubbed, capped). Length for the reproduction's value is 192 chars ≤ MIRRORED_ERROR_MAX 200, so the receipt keeps it whole (observed); the operative first clause (76 chars ≤ 160) survives the panel's 160-char slice — the fixer must keep that property for realistic values. Claims, each matched to the predicate: requirement is absoluteness (what is checked); the relative root can land files inside a checkout (capability of relative roots, true for any cwd). It never claims the accepted root is outside any repository — no promise of "outside the repository" appears anywhere. Falsifier: the fence pin below — mutate the guard to refuse an absolute root inside a work tree (the natural future over-branch reusing this text) and the pin fails, so the message can never overclaim a predicate the code doesn't run.

    Pins

    Killer host and receipt pins live in test/telemetry/evidence-write-policy.test.ts (it owns "what happens when a write fails and what survives to report it"); resolver-unit pins live in test/store/store-permissions.test.ts (it already pins memoryRoot() throwing and default-root behavior). No new files.

    1. Killer (P6): cwd = fresh git init work tree, OPENCODE_MEMORY_DIR="undefined", drive the real writer: strict recordSync rejects with a message containing absolute path and the quoted value; best-effort survives; git status --porcelain empty and undefined/ absent. Killer mutation — delete the isAbsolute refusal branch — restores the silent write (STRICT: returned without throwing, ?? undefined/ observed post-mutation): fails both assertions, non-vacuous because the unmutated reproduction is exactly this post-state.
    2. Deliberate relative ("memory", "./m", " ") refused — proves the predicate is absoluteness, not an artefact list; the artefact pin alone would pass a blacklist guard.
    3. Fence: absolute root inside a live work tree is accepted and writes (no refusal, receipt null). Doubles as the message falsifier; also kills any work-tree-containment over-implementation.
    4. Fallbacks: "" falls through to the default root, no refusal, no directory anywhere unexpected; unset → default.
    5. Guard applies to readOnly=true — a refused root must not be readable-anyway.
    6. Circularity pin (P7): under the refused root, best-effort does not throw and droppedEvidenceWrites() returns dropped≥1 with lastError containing absolute path — receipt readable at the refused root. Mutation: revert either key to evidenceDir() → best-effort writer throws and the pin fails (stack above).
    7. Existing cross-store keying test keeps passing under the rekey (it does — verified).

    Fences

    No workflow files; no README; no schema change; do not touch tightenDirectory, publish.ts, or the test temp helpers; no per-callsite guards (the point is one central resolver); no defensive trim/tilde-expansion beyond the stated predicate; no memory_status render refactor; no unrelated call-site "fixes". Four touched files total: the two source files above plus the two existing test files.

    Severity and tier (owner's call)

    Severity: carry the ask low → medium — silent (exit 0, dirtied checkout), lands caller-authored memory prose where a human will git add -A, and applies to every store file, not just evidence. Tier: endorse standard — one guard, one key change, two existing test files, every behavior above already demonstrated on a prototype. Named fallback: if implementing the rekey forces changes beyond the containment proven here (e.g. the status-snapshot builder needs new handling), the fixer stops and bounces to the owner rather than expanding scope inside this change.

    Checks for the reviewer: bun test (full), bun run typecheck, bun run lint at baseline.

    @fix

  5. abogartz-opencode-self-improvement commented on Dec 1, 2026

    @abogartz-opencode-self-improvement

    🎉 This issue has been resolved in version 0.41.2 🎉

    The release is available on:

    Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugreleasedseverity:lowstore-securitytier:standard

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions