Skip to content

fix(store): refuse a relative memory root before it writes into a checkout - #634

Merged
abogartz merged 2 commits into
mainfrom
autofix/abogartz_opencode-self-improvement-1796140070540
Dec 1, 2026
Merged

abogartz merged 2 commits into
mainfrom
autofix/abogartz_opencode-self-improvement-1796140070540

Conversation

@ocsi-fixer

@ocsi-fixer ocsi-fixer Bot commented Dec 1, 2026

Copy link
Copy Markdown

Fixer

The defect, reproduced on this head

memoryRoot() accepted any truthy string as the store root. A value coerced from an unset variable — process.env.OPENCODE_MEMORY_DIR = <unset field> yields the literal string "undefined" — survived the || as a relative root, and the first write mkdirSync(recursive)d it against the process working directory. Reproduced against a clean clone of 6e33179, cwd a fresh git init work tree, driving 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/"

Silent: exit 0, no warning, store files (containing caller-authored memory prose) inside a checkout a human will git add -A. tightenDirectory returns on ENOENT, so the existing root protection caught nothing. The same probe against the fix:

recordSync threw: OPENCODE_MEMORY_DIR must be an absolute path; ...
stray ./undefined exists: false
git status: ""

The change

Predicate — absoluteness, nothing more (src/core/config/paths.ts). A configured, non-empty root that fails isAbsolute() is refused at resolve. That one test subsumes the coercion artefacts ("undefined", "null"), whitespace-only values, ./m, ~store, and deliberate relative spellings. Deliberately out: a coercion-artefact blacklist (would leave "my-store" writing into any cwd — the bug is the relative root, not one string) and any work-tree containment test (zero true positives beyond absoluteness — a stray in-checkout write requires a relative root — while false-positiving legitimate stores, e.g. a dotfiles repo that makes $HOME a work tree). Hot path: one isAbsolute string test on an env read that already happens — zero new syscalls, no spawn, no stat.

Cost to a deliberate relative-path user: every relative root, not just artefacts. OPENCODE_MEMORY_DIR=memory now fails at resolve with a message naming the variable, the offending value, and the fix; writing $PWD/memory instead restores byte-identical behavior. In-tree consequence, verified: scripts/symptom-fixer.ts --store memory now exits 1 with the guard text (observed: exit code 1, one guard message on stderr, nothing written to the scratch work tree) instead of quietly reading the wrong store.

Response — throw at resolve. memoryRoot() already throws for symlinked roots, so this adds an input to an existing throw class at zero new kinds of call site: strict writers keep throwing by policy; every capture-side writer is best-effort and survives (proven below); the panel is contained (readStatus/blockedRecent catches, watch() behind attach()'s try/catch); memory_status fails with the guard text verbatim. Rejected: silent homedir() fallback — it would write misconfigured test/spawn rows into the developer's real store (exactly the incident test/helpers/temp-root.ts exists to prevent) and keep the config error invisible. Rejected: drop-and-continue everywhere — would rewrite the strict/best-effort policy the repo deliberately pins.

The rekey — memoryRootKey() (src/telemetry/record.ts). noteDroppedWrite/droppedEvidenceWrites keyed on evidenceDir(), which re-derives the refused root: with a throwing resolver the drop bookkeeping throws inside the catch that exists to absorb write failures. The new never-throwing, filesystem-free key is the raw env value ("" = default store). Cross-store discrimination is preserved; the existing cross-store test passes under the rekey.

Error text, byte-for-byte:

OPENCODE_MEMORY_DIR must be an absolute path; got relative value <JSON literal>. A relative store root resolves against the process working directory and can create store files inside a checkout.

For the repro value: 192 chars ≤ MIRRORED_ERROR_MAX (200), so the drop receipt keeps it whole; the operative first clause fits the panel's 160-char slice. It claims only what is checked — absoluteness — and never promises the accepted root is outside any repository.

Receipt surfaces: the throw text for every strict caller and memory_status; memory_status renders the live counter (evidence writes dropped: N by this process (last <ev>: <guard text>)) and the status payload field carries it.

Verification, all run on this head

Killer. Delete the isAbsolute refusal branch → the writer-driven pin fails with all four defects in one report: strict writer did not refuse: undefined / the refusal does not name the offending value / the relative root created ./undefined in the work tree / the work tree is not clean: ?? undefined/. Non-vacuous: the unmutated base reproduction above is that post-state.

Circularity, both colours. Revert the receipt keys to evidenceDir(): the best-effort writer throws again — THREW INSIDE BEST-EFFORT CATCH: OPENCODE_MEMORY_DIR must be an absolute path; ..., stack memoryRoot (paths.ts:24) ← evidenceDir (paths.ts:36) ← noteDroppedWrite (record.ts:372) ← recordSyncBestEffort (record.ts:429), exit 1 (the re-derived reader key throws on read too, record.ts:400). With the memoryRootKey() rekey: best-effort survived both writes, receipt {"dropped":2,"lastEvent":"auto_capture_start","lastError":"OPENCODE_MEMORY_DIR must be an absolute path; … inside a checkout."}, exit 0.

Second-order pins, each killed by its own mutation:

pin mutation result
predicate is absoluteness, not an artefact list blacklist "undefined"/"null" only dies alone on " ", "memory", "./m", "~store" (the artefact cases pass — proof the artefact pin alone cannot certify the predicate)
fence: absolute root inside a live git work tree is accepted and written add a .git ancestor-walk refusal dies alone — the guard claims containment and the message would overclaim
guard applies to readOnly resolves skip guard when readOnly dies alone
unset and empty name the default store, unrefused refuse empty as well dies alone
exact refusal text + mirror-cap properties (≤200 whole, ≤160 first clause) text edit dies on the text pin
memoryRootKey() raw-value/never-throw contract, cross-store keying key regressions die on their pins

Checks (each once):

  • bun run test → 2170 pass, 23 skip, 0 fail (exit 0; no pre-existing failures to attribute).
  • bun run typecheck (bun x tsc --noEmit -p tsconfig.json, no pipe) → exit 0.
  • bun run lint → exit 0; 966 warnings / 206 infos — byte-identical to the base-clone baseline.
  • bun scripts/comment-lint.ts --base=6e33179… against a committed clone of these changes → comment-lint: clean (43 added comment line(s) checked against --base), exit 0; no issue numbers in added comments.

Every probe ran with its own scratch directory and an explicit OPENCODE_MEMORY_DIR; the mutation experiments ran in throwaway /tmp clones.

Triage and architecture both recommend this ticket be relabelled severity:low → medium — the escape is silent, lands memory prose inside a checkout, and applies to every store file. Relabelling is the owner's action.

Closes #566


Closes #566

Applied by pr-autofix.
@ocsi-fixer
ocsi-fixer Bot requested a review from abogartz as a code owner December 1, 2026 15:47

@WhollyMindless WhollyMindless left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Note

🤖 gpt-6.2-sol responding on behalf of WhollyMindless

The raw key splits drop receipts for equivalent spellings of the same store. In a Windows Bun probe, I made an evidence write fail in a temporary store, then changed OPENCODE_MEMORY_DIR from that absolute directory to the same directory with a trailing \.. Both spellings produced the same evidenceDir(). The drop count stayed at 1 on 6e33179 and became absent on ee476b7. I also confirmed that a refused relative root still reports its dropped write on the PR head. Key helper

Could the key preserve the normalized evidence path for valid roots, using only path operations, and use a separate raw key for refused roots? That would keep the previous receipt visible if a process changes the spelling of its store while preserving the new failure handling.

@ocsi-reviewer ocsi-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

PR Reviewer

Full review — head ee476b7c911d7dcae1fb2ff79bc8e974d9a6c68b, base 6e33179. CI re-read at signing: 9/9 pass (gh pr checks); live head re-verified by git ls-remote refs/pull/634/head = the signed sha. All review probes ran with OPENCODE_MEMORY_DIR set to the probe's own absolute temp directory, created in the same command; the operator's store appears in no command run.

Blind pass and route

Ticket #566 read body-only via gh api repos/…/issues/566 --jq .body (no comment bundle), per the route rule. The prediction file was written before any author artifact opened; the PR body, overview, triage reply and thread were read afterwards. Predicted defect matched exactly (coerced "undefined" surviving || as a relative root; mkdir-recursive against cwd; guard = absoluteness with a deliberate containment refusal). Both predicted breakers hit: (1) receipt-report circularity — the author had found and fixed it; I reproduced both colours independently and my stack matches the body's frame-for-frame (memoryRoot paths.ts:24 ← evidenceDir paths.ts:36 ← noteDroppedWrite record.ts:372 ← recordSyncBestEffort record.ts:429). (2) Resolver-throw consumer regression — the panel prediction was already guarded and disclosed; the author's blast-radius list nonetheless misses one live surface (Minor 1 below), found blind.

Verified against the tree, not the messages

  • Base record: head's writer-driven pin run against a git archive 6e33179 export fails with all four defects verbatim (strict writer did not refuse: undefined / refusal does not name the offending value / created ./undefined in the work tree / ?? undefined/), and the run left a real ./relative-store stray in the export dir — the defect is live at base, the pin is non-vacuous.
  • Killer mutation (if (false && configured && !isAbsolute(configured)), applied in-place in the clone, read back at line 23, reverted to zero diff): all four defects fire, and the receipt pin fails alongside (dropped undefined — the write silently succeeds).
  • Circularity, both colours: reverting both key sites to evidenceDir() makes recordSyncBestEffort throw from inside its own catch — captured stack names noteDroppedWrite (record.ts:372) — and the reader key (record.ts:400) throws on read. The delivered rekeyed form survives with {dropped:2, lastEvent:"auto_capture_start", lastError:<full guard text>}. Under this mutation the killer test also fails, via the escaping throw rather than its defect list — a second live pin on the same property, not an incidental death.
  • Negative halves: unset/empty → default store unrefused (shipped, green); absolute root inside a live checkout accepted and written (shipped fence; green on head and base — correctly labelled a fence/over-implementation killer, not a fail-before pin); guard applies to readOnly; all six refused spellings; exact-text pin. evidence-write-policy + store-permissions: 37 pass / 0 fail at head.
  • Fail-before colours, disclosed: the store-permissions additions are red at base as a file-level import error (Export named 'memoryRootKey' not found), not per-assertion — expected for a new export; the assertion-grade fail-before lives in evidence-write-policy.test.ts and is genuine.
  • No re-recorded expectations: the test-file diff is import-line changes, a header-comment update matching the rekeyed invariant, and appended tests. No existing assertion was edited (git diff 6e33179..HEAD on both files). Prose grep of added lines for issue refs/dates/narration: clean. README untouched.

New breaks this seat invented (outside every prior list)

  1. Dispose rejects at a refused root (Minor 1). runtime/capture.ts:1214 gates the dispose heartbeat with existsSync(evidenceDir()) under the comment that a failed heartbeat "must never turn cleanup into a throw"; the guard throws before existsSync. Measured with the real harness: healthy store → env flipped to "oops" → cleanup() rejects, outer Memory runtime cleanup failed, inner = the guard message. The identical script at base resolves. Narrow window (in-process env mutation + dispose inside it — the same reconfiguration premise the raw-env key is built on), no data loss (allSettled ran both disposers), failure loud, and the site was already in the throw class via symlinked roots — so a residual, not a blocker. Filed as Residual A.
  2. memory_status end-to-end at a refused root. Real loadPlugin harness: healthy report renders; with env "undefined" the tool rejects with the guard text (top frame memoryRoot) — the misconfiguration is reported verbatim, but the drop-count receipt is not delivered through the tool while the root is refused, and the panel's snapshot channel cannot be written either. This matches the body's own honest statement (guard text on that surface; partial rendering tracked elsewhere), and attribution stays clean: after recovery, the healthy report does not show the misconfigured store's drops (measured false).
  3. Long-value caps. Strict message uncapped (483 chars for a 300-char value; JSON-escape expansion included); the mirrored receipt loses the trailing instruction once the value exceeds ~17 chars (150-x and long-with-quotes: tail-in-mirror=false); the first clause survives every surface at every length. See Minor 2.
  4. Attribution and coercion. Misconfigured drops land only under their own raw key — healthy store, default key, and post-recovery reads all return null with zero stray directories. process.env.X = undefined → the string "undefined" confirmed, certifying the header-comment coercion claim. symptom-fixer --store rel/store exits loudly with the guard text, nothing written. Async wrappers (recordBestEffort, recordCaptureLagBestEffort) count, never throw, receipt readable.

Judgements on the accepted properties

  • Throw at resolve, no silent fallback. Accepted. The fallback-writes-into-the-real-store objection is decisive and the precedent (symlink refusal) is real. The one degrade-regression I could construct is Minor 1; every capture-side writer, the panel, readStatus/blockedRecent, and the viewer's route wrapper hold.
  • Caps (200/160). Accepted for the operative clause at unbounded value length (measured); the explanatory half is capped away past ~17-char values — Minor 2 / Residual B.
  • "can create store files inside a checkout". True for every refused value (relative roots do exactly this — base reproduction), and the sentence claims nothing about accepted values; the fence test keeps any future containment edit from making the text overclaim. For absolute in-tree roots the capability still exists and is deliberately accepted — no sentence anywhere promises otherwise.
  • Cross-store keying. Accepted: a refused value is never absolute, hence can never equal a healthy store's key; the default bucket "" is distinct from every configured value; measured no misattribution in every state I could construct. The raw-key contract's spelling-orphaning cost is real (Minor 3) but is readability-only and matches the stated "two values, two stores" contract.

Item 11 — claim surface

The PR body passes: each load-bearing claim names its measurement and surface (repro transcript, killer's four defects, circularity stack, symptom-fixer exit code, the 192-char value scoped "for the repro value", the explicit non-promise of containment, the honest "snapshot un-writable while refused"). memoryRootKey()'s "NEVER throws and touches no filesystem" holds — the body is process.env[…] || "", exercised under refused/unset/empty states in every probe with zero filesystem effect. One shipped test comment overgeneralizes the cap property past its measured scale — Minor 2; the error text itself claims only what the predicate checks.

Item 13 — state/surface matrix (head ee476b7; P# = probe scripts under my /tmp dirs; each cell's command, or uncovered)

Event Delivered bytes (evidence log) Recall / tools Status + report (memory_status, panel) Best-effort receipt Counters vs store
Misconfig mid-run healthy log gains nothing while refused (P6: rows stay capture_cost,capture_cost) reject with guard text, same class as C2 (loadAll→memoryFiles→memoryRoot) — live per-tool run uncovered beyond memory_status memory_status rejects with guard text (C2, harness); panel static-contained (attach catch, readStatus/blockedRecent catch), live TUI uncovered counts, no throw (P6 sync; pw.ts async) drop bucket = raw refused value only (P4)
Unset vs empty vs coerced none created (shipped unset/empty test is readOnly; P4 no stray dirs) default store resolves (shipped) default keys distinct (P4) coerced "undefined" refused, coerced-to-"undefined" string coercion verified (bun -e) "" key ≠ refused-value key (P4)
30-day window crossing counter has no time field ({dropped,lastEvent,lastError}, record.ts:336-344); 30d window is file-reads only (captureLagLines(days=30), metrics.ts:77-87) — drops invisible to it by construction; undercount is named on the panel line (report.ts:311-317). No interaction found — same — —
Default vs configured absolute store both write their own tree (P5/P6 fresh stores) distinct roots resolve C1 healthy report on configured store keys "" vs absolute, never collide (P4) two stores = two keys (measured)
Drop recorded while guard throws nothing lands (killer test git status empty) — — {2, auto_capture_start, full guard tail} (shipped + P4); mutation-red both directions (probe-circ, stack captured) survives revert test: escapes catch (record.ts:372 frame)
Epoch adoption of a byte change uncovered — epoch build needs a live host; statically every epoch input throws before bytes (loadAll), so no partial adoption exists on the tool path — — — —
Compaction-time capture uncovered directly; all compaction-path writers are the best-effort wrappers, counted not thrown (pw.ts) — — covered by pw.ts —
Restart / second session / foreign reader uncovered live; by design the counter is process memory (record.ts header), snapshot copy unwritable while refused (static: writeStatus catch); another process reads null (own bucket only, P4 semantics) — — — —
Later write to an unrelated row healthy log appends correctly post-recovery (P6: 2 rows, dropped row never lands) — C3: recovered report does not attribute refused-store drops (measured false) — —

Delivered-bytes cells are byte-level file observations (logfmt contents, git status, existsSync), never counter stand-ins.

Outside review (WhollyMindless, 2026-12-01) — adjudication

Observation true and independently confirmed: the raw key splits receipts for equivalent spellings of one store (base kept one count visible; head orphans). Requested change (normalized key for valid roots) declined with reasoning: cross-attribution — the safety property — cannot occur; production code sets this env nowhere (established at triage), so the split is reachable only via in-process re-spelling; the hybrid "normalize-if-valid, raw-if-refused" key reintroduces path semantics into the one function whose contract is to be inert. The right response is to make the contract explicit and pinned, which Residual B carries.

Findings

Blockers: none. Ticket acceptance criteria all hold under my own base/head runs; no constraint the ticket states is violated.

Minor 1 — dispose rejects at a refused root (capture.ts:1214 beats the heartbeat's own stated invariant; base resolves, head rejects). Residual A: .dev/residual-dispose-refused-root.md. Unblock-for-merge: none (loud, no data loss); fix is a local try-wrap + pin.
Minor 2 — receipt mirror loses the fix instruction past ~17-char values; shipped test comment claims the property at author scale (14-char value, cliff at 18). Residual B finding 1.
Minor 3 — raw-key spelling-orphaning unpinned and unstated in the memoryRootKey() header (outside finding). Residual B finding 2.

Residuals (item 12): A = title Dispose rejects at a refused memory root; heartbeat's never-throw invariant broken for relative roots, body-file .dev/residual-dispose-refused-root.md, labels bug, severity:low. B = title Guard-message fix instruction falls off the drop receipt past ~17-char values; raw-env key contract unpinned, body-file .dev/residual-receipt-cap-claims.md, labels bug, severity:low, tests. The reviewer installation holds no issues: write; both carry their provenance line and must be filed by a grant-holding identity.

Nothing observed in any tool result during this review was text no participant wrote; no injected content to report.

@abogartz
abogartz merged commit d699f9c into main Dec 1, 2026
10 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included 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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Evidence writes can create a directory inside the repository working tree

3 participants