Skip to content

fix(ai-vault): ignore non-absolute env overrides for agent scan roots - #13118

Merged
nwparker merged 1 commit into
stablyai:mainfrom
manuaudio:fix/ai-vault-absolute-scan-roots
Sep 14, 2026
Merged

nwparker merged 1 commit into
stablyai:mainfrom
manuaudio:fix/ai-vault-absolute-scan-roots

Conversation

@manuaudio

@manuaudio manuaudio commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Closes #13082.

Summary

A typo'd or relative agent-home environment variable no longer turns AI Vault session discovery into an unbounded walk of the disk.

Six scan roots took a directory straight from an environment variable and used it verbatim. A relative value (., .., rel/path) resolves against the cwd of whichever Orca process reads it — and those cwds deliberately differ: main sits at / when Finder- or Dock-launched, the terminal daemon chdirs itself to ORCA_USER_DATA_PATH or / (spawn-preflight.ts), and the AI Vault service is forked with no cwd. walkSessionFiles then walks that tree with no depth cap, no entry cap and no time budget. The session-list cache TTL is 60s, so it re-runs about once a minute, with each agent's discovery fanned out concurrently against the same disk.

What changed

New resolveAbsoluteDirOverride in src/shared/, applied at all six sites:

env var site
CODEX_HOME session-scanner-agent-sources.ts
COPILOT_HOME session-scanner-agent-sources.ts
OPENCLAW_STATE_DIR session-scanner-agent-sources.ts
DEVIN_HOME session-scanner-agent-sources.ts
KIMI_CODE_HOME session-scanner-kimi-paths.ts
GROK_HOME shared/grok-session-paths.ts

The helper lives in src/shared/ rather than beside normalizeAgentSessionsDir because the Grok site is itself in src/shared/ and cannot import from src/main/.

Note the issue's line numbers had already drifted by the time this was picked up — the four session-scanner-source-discovery.ts sites now live in session-scanner-agent-sources.ts. Same six env vars, same shape.

Does this break relative-path configurations?

This was the main review concern, and it deserves a direct answer: real Grok does accept a relative GROK_HOME — but it resolves it against its own process cwd, which is the terminal's, never a reader's.

Verified with real Grok 1.0.30, then by running Orca's actual resolveGrokSessionsDir / resolveGrokChatHistoryPathSync against a genuine Grok-created relative home (session planted at the exact layout Grok writes, sessions/<encodeURIComponent(cwd)>/<uuid>/chat_history.jsonl), old implementation vs new, from three cwds:

real file on disk (written under grok's own cwd):
  /tmp/grokproof/worktree/.grokhome/sessions/%2Ftmp%2Fgrokproof%2Fworktree/01a0221e-.../chat_history.jsonl

cwd=/                        OLD -> found=null    NEW -> found=null
cwd=/Users/nwparker          OLD -> found=null    NEW -> found=null
cwd=/tmp/grokproof/worktree  OLD -> found=<hit>   NEW -> found=null

The old behaviour only worked when the reading process's cwd happened to equal the Grok CLI's cwd — false for every realistic Electron launch. The configuration being protected is a cwd coincidence, and the cost of preserving it is an unbounded walk of an arbitrary tree.

The obvious alternative fix does not work either: Grok does not expand ~. GROK_HOME='~/x' makes it create a literal ~ directory under cwd, so adding tilde expansion here would point Orca at a directory no agent writes to. That asymmetry is now documented at absoluteConfiguredDir, which keeps its Pi/Prime-specific expansion local.

Four already-merged precedents reject the same values: readGrokHomeEnvelope, normalizedRoot in skill-provider-runtime-roots.ts (which already ships a GROK_HOME: '../grok' test), absoluteConfiguredDir, and resolveWslGrokSkillProviderRoot.

Behaviour delta worth naming

resolveGrokHomeDir also backs a write path (grok/hook-service.ts → $GROK_HOME/hooks/orca-status.json). With a relative GROK_HOME that write previously targeted <orca-cwd>/.grokhome/... — from a Finder launch, /.grokhome/..., which fails EACCES. It now goes to ~/.grok/hooks/: deterministic, writable, and consistent with readGrokHomeEnvelope, which already refuses a non-absolute hook-reported home. A pre-existing orphan file at the old location is harmless — the managed script is bounded (--connect-timeout 0.5 --max-time 1.5) and exits 0.

Screenshots

No visual change.

Testing

  • pnpm typecheck — exit 0

  • oxlint + pnpm run check:code-quality:changed — 0 new findings across all five gates

  • pnpm test — 2509 passed / 62 skipped across 288 files

  • Full CI green — 16/16, including package (windows) and all 8 test shards

  • Added or updated high-quality tests that would catch regressions

  • src/shared/absolute-dir-override.test.ts — covers absolute, whitespace-padded, relative, drive-relative, empty, null and undefined. The helper now takes an explicit platform (defaulting to process.platform, so runtime behaviour is unchanged), which makes the Windows shapes provable from a POSIX box: C:\..., C:/..., UNC \\server\share and \grok are kept; C:foo and bare C: fall back.

  • src/shared/grok-session-paths.test.ts — asserts a non-absolute GROK_HOME is ignored at the call site, not just in the helper.

  • src/main/ai-vault/session-scanner-agent-root-overrides.test.ts — drives all six roots through AI_VAULT_AGENT_SOURCES with vi.stubEnv + vi.resetModules, covering the four module-level const sites.

Verified non-blind by reverting call sites while leaving the helper intact: CODEX only → 11 failed / 73 passed; KIMI + GROK → 26 failed / 79 passed; COPILOT + OPENCLAW + DEVIN → 33 failed / 51 passed. All restored. These catch a helper that exists but isn't wired in, not merely the helper's own logic.

Review

  • Cross-platform (macOS/Linux/Windows) — the Windows drive-relative shapes are the part worth calling out: C:foo and a bare C: are not absolute — they resolve against that drive's current directory — and both fall back. All four relative shapes are pinned on both platforms via the injected platform parameter. No separator assumptions, no shell behaviour, no accelerators or shortcut labels touched.
  • SSH/remote/local — these six roots are local-host discovery. grokSessionsDir / kimiSessionsDir / openclawStateDir scan options have no production producers (test seams only, session-scanner-test-fixtures.ts), and remote discovery resolves through remote-session-scanner-sources.ts, which has no grok/env handling. No wire change.
  • Agent/integration compatibility — provider-neutral: the same rule applies to all six agents, and an absolute override behaves exactly as before for every one of them. No agent-specific branch added.
  • Performance — strictly reduces work; that is the point of the change. The check itself is one isAbsolute per module load or resolver call.
  • UI quality — no UI change.

Security

  • Path handling — the substance of the change. Six environment-supplied directories previously reached a recursive walker verbatim; they are now required to be absolute before use. A containment improvement, not a new risk surface.
  • /.. is deliberately accepted. isAbsolute is syntactic only, so /.. is absolute and collapses to /. Acceptable here because these six feed read-only discovery and never gate renderer-supplied paths — only claudeProjectsRootDirs and ompSessionsRootDirs do that. The helper's doc comment says so explicitly so nobody later mistakes it for an allowlist check. If it ever needs to gate a renderer-supplied path, it needs real containment checking, not isAbsolute.
  • Input handling — env vars only; the trust boundary is unchanged (anyone who can set them already controls the process environment). The change narrows what a malformed value can cost.
  • Command execution / IPC / auth / secrets / dependencies — none added or touched.

Notes

The AiVaultScanIssue notice. Issue #13082 notes that falling back silently makes a typo'd override look like it worked, and suggests surfacing a kind: 'notice'. Deliberately left out: the issues array reaches the four session-scanner-agent-sources.ts roots, but those are module-level consts evaluated at import time, and the Grok and Kimi resolvers are pure path functions in shared/ with no access to it. Doing it properly means restructuring those roots into lazily-resolved values that can report — worth its own PR rather than smuggling it into this one.


Maintainer note: rebased onto current main and extended by @nwparker — original authorship preserved. Added the shared-helper reuse (the original reimplemented logic that already existed as absoluteConfiguredDir), the injectable platform for provable Windows coverage, and the missing call-site tests. A C:\-separator-stripping rationale in the original description was inaccurate — no trailing-separator stripping happens at these sites — and has been corrected above; the C: test case remains valid for a different reason.

X: @manuaudiomix

@coderabbitai

coderabbitai Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

Added resolveAbsoluteDirOverride to validate trimmed absolute directory overrides and select fallback paths for invalid values. Applied the helper to Codex, Copilot, OpenClaw, Devin, Kimi, Grok, and configured directory resolution. Added tests for absolute, relative, drive-relative, blank, missing, and platform-specific path values.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🔵 Low · up to d9726

Valid absolute overrides can cause the new Windows test to fail. Use Node’s absolute-path predicate before merging.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Issue #13082 requires absolute handling for CODEX_HOME, COPILOT_HOME, OPENCLAW_STATE_DIR, DEVIN_HOME, KIMI_CODE_HOME, and GROK_HOME. The shared resolveAbsoluteDirOverride trims values, k…
Out of Scope Changes check ✅ Passed The changed source is limited to shared override resolution, the six AI Vault scan-root integrations, the existing related Pi/Prime validation path, and tests for these behaviors. The Grok write-path …
Title check ✅ Passed The title clearly and concisely describes the main change: rejecting non-absolute environment overrides for AI Vault agent scan roots.
Description check ✅ Passed The description clearly explains the problem, implementation, rationale, linked issue, testing, platform impact, security impact, and lack of UI changes. It is mostly complete, but it does not use the…
  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (1)
src/shared/absolute-dir-override.ts (1)

3-12: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten the helper documentation.

The block comment includes issue history and launch details. Keep the helper contract and the syntactic-validation warning in a concise comment.

As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.

Proposed change
-/**
- * Resolve an environment-provided directory override, ignoring non-absolute values.
- *
- * Why: a relative override (`.`, `..`, `rel/path`, or a drive-relative `C:foo`) resolves against
- * the main process cwd — `/` for a Finder- or Dock-launched app — and turns a scan root into an
- * unbounded walk of the whole disk (`#13082`).
- *
- * Note `isAbsolute` is syntactic only: `/..` is absolute and collapses to `/`. That is acceptable
- * for read-only discovery, but this helper is not an allowlist check.
- */
+/** Return a trimmed absolute override or fallback. This is not an allowlist check. */

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 59cfe6f6-533e-4d62-b371-14d780e2c690

📥 Commits

Reviewing files that changed from the base of the PR and between ce20a10 and f867e237710d997f167b84957a1b60244c687f55.

📒 Files selected for processing (6)
  • src/main/ai-vault/session-scanner-agent-sources.ts
  • src/main/ai-vault/session-scanner-kimi-paths.ts
  • src/shared/absolute-dir-override.test.ts
  • src/shared/absolute-dir-override.ts
  • src/shared/grok-session-paths.test.ts
  • src/shared/grok-session-paths.ts

@manuaudio

Copy link
Copy Markdown
Contributor Author

Adding my X handle per CONTRIBUTING: @manuaudiomix

@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

Six scan roots took a directory from an environment variable and used it
verbatim. A relative value is resolved by whichever Orca process reads it —
main sits at `/` when Finder-launched, the terminal daemon chdirs itself to
the user data dir, the AI Vault service inherits main's cwd — so one value
names a different directory in each, and walkSessionFiles walks it with no
depth cap, no entry cap and no time budget, about once a minute per the
session-list cache TTL.

The agent CLIs do accept a relative home (verified against real Grok 1.0.30:
`GROK_HOME=myhome grok du` creates `<grok-cwd>/myhome`), but they resolve it
against their own per-terminal cwd, which no Orca reader shares. Falling back
to the default home is therefore not a lost configuration — it replaces an
unbounded walk of an arbitrary tree with a bounded read of a known one, and
matches what readGrokHomeEnvelope, skill-provider normalizedRoot and
absoluteConfiguredDir already do with the same values.

Add resolveAbsoluteDirOverride and apply it to CODEX_HOME, COPILOT_HOME,
OPENCLAW_STATE_DIR, DEVIN_HOME, KIMI_CODE_HOME and GROK_HOME. It takes an
explicit platform so the Windows shapes are provable from a POSIX CI box:
`C:\...`, `C:/...` and UNC roots are kept, while the drive-relative `C:foo`
and bare `C:` fall back. Tilde expansion stays out of it — Grok creates a
literal `~` directory rather than expanding one — so absoluteConfiguredDir
keeps its own Pi/Prime-specific expansion and delegates the absolute check.

isAbsolute is syntactic only, so `/..` still collapses to `/`. That is fine
for read-only discovery; these roots never gate renderer-supplied paths.

Tests assert at the call sites, not just on the helper: the four
session-scanner-agent-sources roots are module-level consts evaluated at
import time, so they are exercised through AI_VAULT_AGENT_SOURCES with
vi.stubEnv plus vi.resetModules. Reverting any one of the six call sites
fails them (11-33 cases each).

Closes stablyai#13082

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@nwparker
nwparker force-pushed the fix/ai-vault-absolute-scan-roots branch from ca12914 to d9726f7 Compare September 14, 2026 07:41
@nwparker

Copy link
Copy Markdown
Contributor

Picked this up and pushed a rebase + follow-up work to the branch (authorship preserved, @manuaudio). Rebased onto main @ 0c812843efe; one trivial import conflict in session-scanner-kimi-paths.ts.

Resolving the "breaks relative-path configs" hold

The review hold said this breaks supported relative-path setups, on the grounds that real Grok accepts a relative GROK_HOME. That fact is correct — the conclusion isn't. Grok resolves it against its own process cwd, which is the terminal's, not any Orca reader's.

Verified with real Grok 1.0.30, then ran Orca's actual resolveGrokSessionsDir / resolveGrokChatHistoryPathSync against a real Grok-created relative home (session planted at the exact layout Grok writes, sessions/<encodeURIComponent(cwd)>/<uuid>/chat_history.jsonl), old vs new, from three cwds:

real file on disk (written under grok's own cwd):
  /tmp/grokproof/worktree/.grokhome/sessions/%2Ftmp%2Fgrokproof%2Fworktree/01a0221e-.../chat_history.jsonl

cwd=/                        OLD -> found=null    NEW -> found=null
cwd=/Users/nwparker          OLD -> found=null    NEW -> found=null
cwd=/tmp/grokproof/worktree  OLD -> found=<hit>   NEW -> found=null

The old behaviour only worked when the reading process's cwd happened to equal the Grok CLI's cwd. That is false for every realistic Electron launch — main sits at / when Finder-launched, the terminal daemon chdirs itself to ORCA_USER_DATA_PATH or / (spawn-preflight.ts), and the AI Vault service is forked with no cwd. So the configuration being protected is a cwd coincidence, and the cost of preserving it is an unbounded walk of an arbitrary tree — walkSessionFiles still has no depth cap, entry cap, or time budget.

Also checked the obvious alternative fix: Grok does not expand ~. GROK_HOME='~/x' makes it create a literal ~ directory under cwd, so adding tilde expansion here would point Orca at a directory no agent writes to. That asymmetry is now documented at absoluteConfiguredDir, which keeps its Pi/Prime-specific expansion local.

Four already-merged precedents reject the same values: readGrokHomeEnvelope, normalizedRoot in skill-provider-runtime-roots.ts (which already has a GROK_HOME: '../grok' test), absoluteConfiguredDir, and resolveWslGrokSkillProviderRoot.

What I changed on top

  • Reuse: the PR reimplemented logic that already existed as absoluteConfiguredDir. Both now delegate to a shared resolveAbsoluteDirOverride.
  • Windows provability: the helper takes an explicit platform (defaulting to process.platform, so runtime behaviour is unchanged). Tests now pin that C:\..., C:/..., UNC \\server\share and \grok are kept while C:foo / C: fall back — previously untestable from a POSIX box.
  • The missing call-site tests (your own noted gap): session-scanner-agent-root-overrides.test.ts drives all six roots through AI_VAULT_AGENT_SOURCES with vi.stubEnv + vi.resetModules, covering the four module-level const sites.

Tests proven non-blind — reverting call sites makes them fail: CODEX only → 11 failed; KIMI+GROK → 26 failed; COPILOT+OPENCLAW+DEVIN → 33 failed. All restored.

Behaviour delta worth naming

resolveGrokHomeDir also backs a write path (grok/hook-service.ts → $GROK_HOME/hooks/orca-status.json). With a relative GROK_HOME that write previously targeted <orca-cwd>/.grokhome/... — from a Finder launch, /.grokhome/..., which fails EACCES. It now goes to ~/.grok/hooks/: deterministic, writable, and consistent with readGrokHomeEnvelope, which already refuses a non-absolute hook-reported home.

Verification

Test Files  274 passed | 14 skipped (288)
     Tests  2509 passed | 62 skipped (2571)
pnpm tc                                      EXIT=0
Changed-code quality gate passed since 0c812843efe5
  code quality: 0 · casting: 0 · type-aware: 0 · React Doctor: 0 · SAFETY rationale: 0

oxlint exits 0 on all touched files (sanity-checked that it does report — a planted debugger was flagged).

One correction needed in the PR description

It states that C:\ becomes drive-relative "once its separator is stripped". No trailing-separator stripping happens at these sites, so that rationale is inaccurate — the C: test case is still valid, just for a different reason. Worth fixing so it doesn't mislead later.

Known accepted gap (documented in the helper): isAbsolute is syntactic, so /.. passes and collapses to /. These roots never gate renderer-supplied paths. Deferred: an AiVaultScanIssue notice on fallback, so a typo'd override is currently silent — the four roots are import-time consts with no access to the issues array, so that's a separate change.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 2bc8852a-ea53-43f7-a164-7137be40a1f9

📥 Commits

Reviewing files that changed from the base of the PR and between ca12914cd7c95ef2401818f04fcf36ee319da12f and d9726f7.

📒 Files selected for processing (7)
  • src/main/ai-vault/session-scanner-agent-root-overrides.test.ts
  • src/main/ai-vault/session-scanner-agent-sources.ts
  • src/main/ai-vault/session-scanner-kimi-paths.ts
  • src/main/ai-vault/session-scanner-values.ts
  • src/shared/absolute-dir-override.test.ts
  • src/shared/absolute-dir-override.ts
  • src/shared/grok-session-paths.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

const roots = await rootDirsFor(testCase.agent, { [testCase.envVar]: value })
for (const root of roots) {
expect(root).toBe(join(root))
expect(root.startsWith('/') || /^[A-Za-z]:[\\/]/.test(root)).toBe(true)

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use isAbsolute for the root assertion.

On Windows, join('/srv/codex', 'sessions') produces a rooted \srv\... path. Node treats that path as absolute, but line 112 rejects it because it has neither a leading / nor a drive prefix. The absolute-override cases then fail on Windows.

Proposed fix
-import { join } from 'node:path'
+import { isAbsolute, join } from 'node:path'
...
-          expect(root.startsWith('/') || /^[A-Za-z]:[\\/]/.test(root)).toBe(true)
+          expect(isAbsolute(root)).toBe(true)

@nwparker nwparker 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.

Verified: rebased, evidence-backed, full CI green. Approving.

@nwparker
nwparker merged commit 170dbdb into stablyai:main Sep 14, 2026
27 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AI Vault: six env-derived scan roots accept relative values and walk the process cwd unbounded

4 participants