Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 111 additions & 9 deletions packages/opencode/src/snapshot/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,77 @@ const limit = 2 * 1024 * 1024
const core = ["-c", "core.longpaths=true", "-c", "core.symlinks=true"]
const cfg = ["-c", "core.autocrlf=false", ...core]
const quote = [...cfg, "-c", "core.quotepath=false"]

// Persistent tuning for a fresh snapshot gitdir. `git config` sets one key per
// invocation and GIT_CONFIG_* env vars and `-c` flags are ephemeral, so there
// is no supported batched set. Two paths:
// - Configs carrying include directives, or ones git cannot parse, keep the
// original eight `git config <key> <value>` spawns: git's own writers keep
// git's own include precedence and tolerated-failure behavior, unchanged.
// - Otherwise the eight values are appended in one atomic write (tmp file +
// rename), then any pre-existing assignments of the same keys (Windows git
// init writes core.symlinks=false) are collapsed by git itself via
// --replace-all. No config syntax is parsed here, so this cannot corrupt
// the file: the worst tolerated outcome is a leftover duplicate key, which
// keeps reads correct (last assignment wins) and only makes a later plain
// `git config <key> <value>` fail.
// The write bypasses git's config.lock protocol; this module is the only
// writer of the file, track() serializes access per gitdir, and a
// cross-process race converges to the same appended block. Every snapshot
// git call also passes the core values as -c flags, so this file only
// carries performance tuning.
const SNAPSHOT_CONFIG_APPEND = `
[core]
autocrlf = false
longpaths = true
symlinks = true
fsmonitor = false
untrackedCache = true
[feature]
manyFiles = true
[index]
version = 4
threads = true
`

// Disambiguates the tmp config file across concurrent configure calls; the
// pid already disambiguates across processes.
let snapshotConfigTmpCounter = 0

// Canonical lowercase section.key form and value for each appended key.
const SNAPSHOT_CONFIG_VALUES: ReadonlyMap<string, string> = new Map([
["core.autocrlf", "false"],
["core.longpaths", "true"],
["core.symlinks", "true"],
["core.fsmonitor", "false"],
["core.untrackedcache", "true"],
["feature.manyfiles", "true"],
["index.version", "4"],
["index.threads", "true"],
])

// Joins existing config content with the appended block. A missing trailing
// newline is added first: an unterminated continuation on the last line then
// consumes only the empty line SNAPSHOT_CONFIG_APPEND starts with, instead of
// swallowing the [core] header into the previous value.
export function joinSnapshotConfig(previous: string): string {
return (previous.endsWith("\n") ? previous : previous + "\n") + SNAPSHOT_CONFIG_APPEND
}

// Tuning keys assigned more than once in `git config --list -z` output, as
// [key, value] pairs for --replace-all. Entry format is "key\nvalue\0", or
// "key\0" for a bare key; git already lowercases key names and resolves
// continuations, quoting, subsections ("index.x.version", a different key)
// and comments.
export function duplicatedSnapshotConfigKeys(listZ: string): [string, string][] {
const counts = new Map<string, number>()
for (const entry of listZ.split("\0")) {
const newline = entry.indexOf("\n")
const key = newline === -1 ? entry : entry.slice(0, newline)
if (SNAPSHOT_CONFIG_VALUES.has(key)) counts.set(key, (counts.get(key) ?? 0) + 1)
}
return [...SNAPSHOT_CONFIG_VALUES].filter(([key]) => (counts.get(key) ?? 0) > 1)
}
interface GitResult {
readonly code: ChildProcessSpawner.ExitCode
readonly text: string
Expand Down Expand Up @@ -315,6 +386,45 @@ const layer: Layer.Layer<Service, never, FSUtil.Service | AppProcess.Service | C
)
})

// Write the persistent gitdir config atomically. Failures are tolerated
// like the previous per-key `git config` spawns (unchecked results): the
// gitdir keeps git's init defaults and every later git call still works.
const configure = Effect.fnUntraced(function* (gitdir: string) {
const file = path.join(gitdir, "config")
yield* Effect.gen(function* () {
// --get-regexp exits 1 on no match, 0 on match, >1 on a file git
// cannot parse. Any include directive (include.path, includeIf.*)
// or an unparsable file keeps the original git-owned spawns.
const includes = yield* git(["--git-dir", gitdir, "config", "--local", "--get-regexp", "^include"])
if (includes.code !== 1) {
for (const [key, value] of SNAPSHOT_CONFIG_VALUES) {
yield* git(["--git-dir", gitdir, "config", key, value])
}
return
}
const info = yield* fs.stat(file)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

SUGGESTION: TOCTOU race between config read and overwrite

fs.stat/fs.readFileString read the previous config, then fs.rename(tmp, file) overwrites it. Concurrent modification between read and rename could be lost. Runs once per fresh gitdir under an in-memory lock, so cross-process risk is low but real.

const previous = yield* fs.readFileString(file)
const tmp = `${file}.tmp-${process.pid}-${snapshotConfigTmpCounter++}`
yield* fs.writeFileString(tmp, joinSnapshotConfig(previous))
if (typeof info.mode === "number") yield* fs.chmod(tmp, info.mode).pipe(Effect.ignore)
yield* fs.rename(tmp, file).pipe(Effect.tapError(() => fs.remove(tmp).pipe(Effect.ignore)))
// No -c flags on these spawns: injected values would show up in
// --list output and masquerade as assignments.
const list = yield* git(["config", "--local", "--list", "-z"], { env: { GIT_DIR: gitdir } })
if (list.code === 0) {
for (const [key, value] of duplicatedSnapshotConfigKeys(list.text)) {
yield* git(["config", "--local", "--replace-all", key, value], { env: { GIT_DIR: gitdir } })
}
}
}).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to persist snapshot git config; keeping init defaults", {
error: String(error),
}),
),
)
})

const track = Effect.fnUntraced(function* () {
return yield* locked(
Effect.gen(function* () {
Expand All @@ -325,15 +435,7 @@ const layer: Layer.Layer<Service, never, FSUtil.Service | AppProcess.Service | C
yield* git(["init"], {
env: { GIT_DIR: state.gitdir, GIT_WORK_TREE: state.worktree },
})
yield* git(["--git-dir", state.gitdir, "config", "core.autocrlf", "false"])
yield* git(["--git-dir", state.gitdir, "config", "core.longpaths", "true"])
yield* git(["--git-dir", state.gitdir, "config", "core.symlinks", "true"])
yield* git(["--git-dir", state.gitdir, "config", "core.fsmonitor", "false"])
// Tuning for very large worktrees so the first add stays bounded.
yield* git(["--git-dir", state.gitdir, "config", "feature.manyFiles", "true"])
yield* git(["--git-dir", state.gitdir, "config", "index.version", "4"])
yield* git(["--git-dir", state.gitdir, "config", "index.threads", "true"])
yield* git(["--git-dir", state.gitdir, "config", "core.untrackedCache", "true"])
yield* configure(state.gitdir)
yield* seed()
yield* Effect.logInfo("initialized")
}
Expand Down
95 changes: 94 additions & 1 deletion packages/opencode/test/snapshot/snapshot.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { afterEach, expect } from "bun:test"
import { afterEach, expect, test } from "bun:test"
import { $ } from "bun"
import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner"
import { Global } from "@opencode-ai/core/global"
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
import { FSUtil } from "@opencode-ai/core/fs-util"
import fs from "fs/promises"
import os from "os"
import path from "path"
import { Effect, Fiber, Layer } from "effect"
import { Snapshot } from "../../src/snapshot"
Expand Down Expand Up @@ -163,6 +165,97 @@ it.instance(
{ git: true },
)

it.instance(
"fresh gitdir persists the snapshot tuning config",
Effect.gen(function* () {
const tmp = yield* bootstrap()
const snapshot = yield* Snapshot.Service
const before = yield* snapshot.track()
expect(before).toBeTruthy()
const config = yield* Effect.promise(async () => {
const root = path.join(Global.Path.data, "snapshot")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

SUGGESTION: test walks entire snapshot root tree

The test recursively walks Global.Path.data/snapshot looking for config files and expects exactly one match. In environments with many snapshot gitdirs (CI, parallel test runs), this could be slow or flaky. Consider narrowing the search to the known gitdir path.

const matches: string[] = []
const walk = async (dir: string): Promise<void> => {
for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name)
if (entry.isDirectory()) await walk(full)
else if (entry.name === "config") {
const raw = await fs.readFile(full, "utf8")
if (raw.includes(path.basename(tmp.path))) matches.push(raw)
}
}
}
await walk(root)
expect(matches.length).toBe(1)
return matches[0]!
})
for (const line of [
"autocrlf = false",
"longpaths = true",
"symlinks = true",
"fsmonitor = false",
"untrackedCache = true",
"manyFiles = true",
"version = 4",
"threads = true",
"repositoryformatversion",
"worktree = ",
]) {
expect(config).toContain(line)
}
}),
{ git: true },
)

test("joinSnapshotConfig preserves a trailing unterminated continuation", async () => {
// A template/user config whose last line is an unterminated continuation
// must not swallow the appended [core] header into its value.
const file = path.join(await fs.mkdtemp(path.join(os.tmpdir(), "snapshot-config-")), "config")
await fs.writeFile(file, Snapshot.joinSnapshotConfig("[user]\n\tname = val\\"))
const out = await $`git config --file ${file} --list`.text()
const entries = out.trim().split("\n")
expect(entries).toContain("user.name=val")
for (const entry of [
"core.autocrlf=false",
"core.longpaths=true",
"core.symlinks=true",
"core.fsmonitor=false",
"core.untrackedcache=true",
"feature.manyfiles=true",
"index.version=4",
"index.threads=true",
]) {
expect(entries).toContain(entry)
}
})

test("duplicatedSnapshotConfigKeys finds only multiply-assigned tuning keys", () => {
// Real `git config --list -z` output: "key\nvalue\0" per entry, "key\0"
// for bare keys, key names already lowercased by git, continuation and
// quoted values decoded (may contain newlines), subsections shown as
// "index.x.version" (a different key from index.version).
const listZ =
[
"core.repositoryformatversion\n0",
"core.symlinks\nfalse", // Windows init default
"core.symlinks\ntrue", // the appended assignment
"core.fsmonitor\nfirst second", // continuation value from a template
"core.fsmonitor\nfalse",
"index.x.version\n3",
"core.bare", // bare key, not a tuning key
"feature.manyfiles\ntrue",
"index.version\n4",
"core.untrackedcache\ntrue",
"core.autocrlf\nline one\nline two", // quoted value with an embedded newline
"core.autocrlf\nfalse",
].join("\0") + "\0"
expect(Snapshot.duplicatedSnapshotConfigKeys(listZ)).toEqual([
["core.autocrlf", "false"],
["core.symlinks", "true"],
["core.fsmonitor", "false"],
])
})

it.instance(
"empty directory handling",
withTrackedSnapshot(({ tmp, snapshot, before }) =>
Expand Down
Loading