Compare commits

...
Author SHA1 Message Date
Kit Langton 58ad84d53e refactor(snapshot): effectify SnapshotService as scoped service
Convert Snapshot from a promise-based namespace with Instance ALS reads
to an Effect service on the Instances LayerMap.

- SnapshotService with ChildProcessSpawner for git subprocess execution
  and Effect FileSystem for file operations (replaces Process.run and
  raw fs calls)
- Nothrow git helper that always returns { code, text, stderr }, with
  spawn failure details preserved in stderr
- Hourly cleanup via Effect.forkScoped + Schedule.spaced (replaces
  Scheduler.register)
- Promise facade preserved for all existing callers
- Parallelized before/after git show in diffFull
- Add worktree to InstanceContext.Shape (needed for --work-tree flag)
- Add Instance.current getter for single ALS read
- Extract repeated git config flags into GIT_CORE/GIT_CFG/GIT_CFG_QUOTE
  constants
- Platform layers (NodeChildProcessSpawner, NodeFileSystem, NodePath)
  provided directly on the service layer
2026-03-16 21:44:17 -04:00
5 changed files with 776 additions and 627 deletions
@@ -1,13 +1,15 @@
import { ServiceMap } from "effect" import { ServiceMap } from "effect";
import type { Project } from "@/project/project" import type { Project } from "@/project/project";
export declare namespace InstanceContext { export declare namespace InstanceContext {
export interface Shape { export interface Shape {
readonly directory: string readonly directory: string;
readonly project: Project.Info readonly worktree: string;
} readonly project: Project.Info;
}
} }
export class InstanceContext extends ServiceMap.Service<InstanceContext, InstanceContext.Shape>()( export class InstanceContext extends ServiceMap.Service<
"opencode/InstanceContext", InstanceContext,
) {} InstanceContext.Shape
>()("opencode/InstanceContext") {}
+74 -55
View File
@@ -1,64 +1,83 @@
import { Effect, Layer, LayerMap, ServiceMap } from "effect" import { Effect, Layer, LayerMap, ServiceMap } from "effect";
import { registerDisposer } from "./instance-registry" import { FileService } from "@/file";
import { InstanceContext } from "./instance-context" import { FileTimeService } from "@/file/time";
import { ProviderAuthService } from "@/provider/auth-service" import { FileWatcherService } from "@/file/watcher";
import { QuestionService } from "@/question/service" import { FormatService } from "@/format";
import { PermissionService } from "@/permission/service" import { PermissionService } from "@/permission/service";
import { FileWatcherService } from "@/file/watcher" import { Instance } from "@/project/instance";
import { VcsService } from "@/project/vcs" import { VcsService } from "@/project/vcs";
import { FileTimeService } from "@/file/time" import { ProviderAuthService } from "@/provider/auth-service";
import { FormatService } from "@/format" import { QuestionService } from "@/question/service";
import { FileService } from "@/file" import { SkillService } from "@/skill/skill";
import { SkillService } from "@/skill/skill" import { SnapshotService } from "@/snapshot";
import { Instance } from "@/project/instance" import { InstanceContext } from "./instance-context";
import { registerDisposer } from "./instance-registry";
export { InstanceContext } from "./instance-context" export { InstanceContext } from "./instance-context";
export type InstanceServices = export type InstanceServices =
| QuestionService | QuestionService
| PermissionService | PermissionService
| ProviderAuthService | ProviderAuthService
| FileWatcherService | FileWatcherService
| VcsService | VcsService
| FileTimeService | FileTimeService
| FormatService | FormatService
| FileService | FileService
| SkillService | SkillService
| SnapshotService;
function lookup(directory: string) { // NOTE: LayerMap only passes the key (directory string) to lookup, but we need
const project = Instance.project // the full instance context (directory, worktree, project). We read from the
const ctx = Layer.sync(InstanceContext, () => InstanceContext.of({ directory, project })) // legacy Instance ALS here, which is safe because lookup is only triggered via
return Layer.mergeAll( // runPromiseInstance -> Instances.get, which always runs inside Instance.provide.
Layer.fresh(QuestionService.layer), // This should go away once the old Instance type is removed and lookup can load
Layer.fresh(PermissionService.layer), // the full context directly.
Layer.fresh(ProviderAuthService.layer), function lookup(_key: string) {
Layer.fresh(FileWatcherService.layer).pipe(Layer.orDie), const ctx = Layer.sync(InstanceContext, () =>
Layer.fresh(VcsService.layer), InstanceContext.of(Instance.current),
Layer.fresh(FileTimeService.layer).pipe(Layer.orDie), );
Layer.fresh(FormatService.layer), return Layer.mergeAll(
Layer.fresh(FileService.layer), Layer.fresh(QuestionService.layer),
Layer.fresh(SkillService.layer), Layer.fresh(PermissionService.layer),
).pipe(Layer.provide(ctx)) Layer.fresh(ProviderAuthService.layer),
Layer.fresh(FileWatcherService.layer).pipe(Layer.orDie),
Layer.fresh(VcsService.layer),
Layer.fresh(FileTimeService.layer).pipe(Layer.orDie),
Layer.fresh(FormatService.layer),
Layer.fresh(FileService.layer),
Layer.fresh(SkillService.layer),
Layer.fresh(SnapshotService.layer),
).pipe(Layer.provide(ctx));
} }
export class Instances extends ServiceMap.Service<Instances, LayerMap.LayerMap<string, InstanceServices>>()( export class Instances extends ServiceMap.Service<
"opencode/Instances", Instances,
) { LayerMap.LayerMap<string, InstanceServices>
static readonly layer = Layer.effect( >()("opencode/Instances") {
Instances, static readonly layer = Layer.effect(
Effect.gen(function* () { Instances,
const layerMap = yield* LayerMap.make(lookup, { idleTimeToLive: Infinity }) Effect.gen(function* () {
const unregister = registerDisposer((directory) => Effect.runPromise(layerMap.invalidate(directory))) const layerMap = yield* LayerMap.make(lookup, {
yield* Effect.addFinalizer(() => Effect.sync(unregister)) idleTimeToLive: Infinity,
return Instances.of(layerMap) });
}), const unregister = registerDisposer((directory) =>
) Effect.runPromise(layerMap.invalidate(directory)),
);
yield* Effect.addFinalizer(() => Effect.sync(unregister));
return Instances.of(layerMap);
}),
);
static get(directory: string): Layer.Layer<InstanceServices, never, Instances> { static get(
return Layer.unwrap(Instances.use((map) => Effect.succeed(map.get(directory)))) directory: string,
} ): Layer.Layer<InstanceServices, never, Instances> {
return Layer.unwrap(
Instances.use((map) => Effect.succeed(map.get(directory))),
);
}
static invalidate(directory: string): Effect.Effect<void, never, Instances> { static invalidate(directory: string): Effect.Effect<void, never, Instances> {
return Instances.use((map) => map.invalidate(directory)) return Instances.use((map) => map.invalidate(directory));
} }
} }
+164 -142
View File
@@ -1,163 +1,185 @@
import { Log } from "@/util/log" import { GlobalBus } from "@/bus/global";
import { Context } from "../util/context" import { disposeInstance } from "@/effect/instance-registry";
import { Project } from "./project" import { Filesystem } from "@/util/filesystem";
import { State } from "./state" import { iife } from "@/util/iife";
import { iife } from "@/util/iife" import { Log } from "@/util/log";
import { GlobalBus } from "@/bus/global" import { Context } from "../util/context";
import { Filesystem } from "@/util/filesystem" import { Project } from "./project";
import { disposeInstance } from "@/effect/instance-registry" import { State } from "./state";
interface Context { interface Context {
directory: string directory: string;
worktree: string worktree: string;
project: Project.Info project: Project.Info;
} }
const context = Context.create<Context>("instance") const context = Context.create<Context>("instance");
const cache = new Map<string, Promise<Context>>() const cache = new Map<string, Promise<Context>>();
const disposal = { const disposal = {
all: undefined as Promise<void> | undefined, all: undefined as Promise<void> | undefined,
} };
function emit(directory: string) { function emit(directory: string) {
GlobalBus.emit("event", { GlobalBus.emit("event", {
directory, directory,
payload: { payload: {
type: "server.instance.disposed", type: "server.instance.disposed",
properties: { properties: {
directory, directory,
}, },
}, },
}) });
} }
function boot(input: { directory: string; init?: () => Promise<any>; project?: Project.Info; worktree?: string }) { function boot(input: {
return iife(async () => { directory: string;
const ctx = init?: () => Promise<any>;
input.project && input.worktree project?: Project.Info;
? { worktree?: string;
directory: input.directory, }) {
worktree: input.worktree, return iife(async () => {
project: input.project, const ctx =
} input.project && input.worktree
: await Project.fromDirectory(input.directory).then(({ project, sandbox }) => ({ ? {
directory: input.directory, directory: input.directory,
worktree: sandbox, worktree: input.worktree,
project, project: input.project,
})) }
await context.provide(ctx, async () => { : await Project.fromDirectory(input.directory).then(
await input.init?.() ({ project, sandbox }) => ({
}) directory: input.directory,
return ctx worktree: sandbox,
}) project,
}),
);
await context.provide(ctx, async () => {
await input.init?.();
});
return ctx;
});
} }
function track(directory: string, next: Promise<Context>) { function track(directory: string, next: Promise<Context>) {
const task = next.catch((error) => { const task = next.catch((error) => {
if (cache.get(directory) === task) cache.delete(directory) if (cache.get(directory) === task) cache.delete(directory);
throw error throw error;
}) });
cache.set(directory, task) cache.set(directory, task);
return task return task;
} }
export const Instance = { export const Instance = {
async provide<R>(input: { directory: string; init?: () => Promise<any>; fn: () => R }): Promise<R> { async provide<R>(input: {
const directory = Filesystem.resolve(input.directory) directory: string;
let existing = cache.get(directory) init?: () => Promise<any>;
if (!existing) { fn: () => R;
Log.Default.info("creating instance", { directory }) }): Promise<R> {
existing = track( const directory = Filesystem.resolve(input.directory);
directory, let existing = cache.get(directory);
boot({ if (!existing) {
directory, Log.Default.info("creating instance", { directory });
init: input.init, existing = track(
}), directory,
) boot({
} directory,
const ctx = await existing init: input.init,
return context.provide(ctx, async () => { }),
return input.fn() );
}) }
}, const ctx = await existing;
get directory() { return context.provide(ctx, async () => {
return context.use().directory return input.fn();
}, });
get worktree() { },
return context.use().worktree get current() {
}, return context.use();
get project() { },
return context.use().project get directory() {
}, return context.use().directory;
/** },
* Check if a path is within the project boundary. get worktree() {
* Returns true if path is inside Instance.directory OR Instance.worktree. return context.use().worktree;
* Paths within the worktree but outside the working directory should not trigger external_directory permission. },
*/ get project() {
containsPath(filepath: string) { return context.use().project;
if (Filesystem.contains(Instance.directory, filepath)) return true },
// Non-git projects set worktree to "/" which would match ANY absolute path. /**
// Skip worktree check in this case to preserve external_directory permissions. * Check if a path is within the project boundary.
if (Instance.worktree === "/") return false * Returns true if path is inside Instance.directory OR Instance.worktree.
return Filesystem.contains(Instance.worktree, filepath) * Paths within the worktree but outside the working directory should not trigger external_directory permission.
}, */
/** containsPath(filepath: string) {
* Captures the current instance ALS context and returns a wrapper that if (Filesystem.contains(Instance.directory, filepath)) return true;
* restores it when called. Use this for callbacks that fire outside the // Non-git projects set worktree to "/" which would match ANY absolute path.
* instance async context (native addons, event emitters, timers, etc.). // Skip worktree check in this case to preserve external_directory permissions.
*/ if (Instance.worktree === "/") return false;
bind<F extends (...args: any[]) => any>(fn: F): F { return Filesystem.contains(Instance.worktree, filepath);
const ctx = context.use() },
return ((...args: any[]) => context.provide(ctx, () => fn(...args))) as F /**
}, * Captures the current instance ALS context and returns a wrapper that
state<S>(init: () => S, dispose?: (state: Awaited<S>) => Promise<void>): () => S { * restores it when called. Use this for callbacks that fire outside the
return State.create(() => Instance.directory, init, dispose) * instance async context (native addons, event emitters, timers, etc.).
}, */
async reload(input: { directory: string; init?: () => Promise<any>; project?: Project.Info; worktree?: string }) { bind<F extends (...args: any[]) => any>(fn: F): F {
const directory = Filesystem.resolve(input.directory) const ctx = context.use();
Log.Default.info("reloading instance", { directory }) return ((...args: any[]) => context.provide(ctx, () => fn(...args))) as F;
await Promise.all([State.dispose(directory), disposeInstance(directory)]) },
cache.delete(directory) state<S>(
const next = track(directory, boot({ ...input, directory })) init: () => S,
emit(directory) dispose?: (state: Awaited<S>) => Promise<void>,
return await next ): () => S {
}, return State.create(() => Instance.directory, init, dispose);
async dispose() { },
const directory = Instance.directory async reload(input: {
Log.Default.info("disposing instance", { directory }) directory: string;
await Promise.all([State.dispose(directory), disposeInstance(directory)]) init?: () => Promise<any>;
cache.delete(directory) project?: Project.Info;
emit(directory) worktree?: string;
}, }) {
async disposeAll() { const directory = Filesystem.resolve(input.directory);
if (disposal.all) return disposal.all Log.Default.info("reloading instance", { directory });
await Promise.all([State.dispose(directory), disposeInstance(directory)]);
cache.delete(directory);
const next = track(directory, boot({ ...input, directory }));
emit(directory);
return await next;
},
async dispose() {
const directory = Instance.directory;
Log.Default.info("disposing instance", { directory });
await Promise.all([State.dispose(directory), disposeInstance(directory)]);
cache.delete(directory);
emit(directory);
},
async disposeAll() {
if (disposal.all) return disposal.all;
disposal.all = iife(async () => { disposal.all = iife(async () => {
Log.Default.info("disposing all instances") Log.Default.info("disposing all instances");
const entries = [...cache.entries()] const entries = [...cache.entries()];
for (const [key, value] of entries) { for (const [key, value] of entries) {
if (cache.get(key) !== value) continue if (cache.get(key) !== value) continue;
const ctx = await value.catch((error) => { const ctx = await value.catch((error) => {
Log.Default.warn("instance dispose failed", { key, error }) Log.Default.warn("instance dispose failed", { key, error });
return undefined return undefined;
}) });
if (!ctx) { if (!ctx) {
if (cache.get(key) === value) cache.delete(key) if (cache.get(key) === value) cache.delete(key);
continue continue;
} }
if (cache.get(key) !== value) continue if (cache.get(key) !== value) continue;
await context.provide(ctx, async () => { await context.provide(ctx, async () => {
await Instance.dispose() await Instance.dispose();
}) });
} }
}).finally(() => { }).finally(() => {
disposal.all = undefined disposal.all = undefined;
}) });
return disposal.all return disposal.all;
}, },
} };
+489 -389
View File
@@ -1,416 +1,516 @@
import path from "path" import {
import fs from "fs/promises" NodeChildProcessSpawner,
import { Filesystem } from "../util/filesystem" NodeFileSystem,
import { Log } from "../util/log" NodePath,
import { Flag } from "../flag/flag" } from "@effect/platform-node";
import { Global } from "../global" import {
import z from "zod" Cause,
import { Config } from "../config/config" Duration,
import { Instance } from "../project/instance" Effect,
import { Scheduler } from "../scheduler" FileSystem,
import { Process } from "@/util/process" Layer,
Schedule,
ServiceMap,
Stream,
} from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import path from "path";
import z from "zod";
import { InstanceContext } from "@/effect/instance-context";
import { runPromiseInstance } from "@/effect/runtime";
import { Config } from "../config/config";
import { Global } from "../global";
import { Log } from "../util/log";
const log = Log.create({ service: "snapshot" });
const PRUNE = "7.days";
// Common git config flags shared across snapshot operations
const GIT_CORE = ["-c", "core.longpaths=true", "-c", "core.symlinks=true"];
const GIT_CFG = ["-c", "core.autocrlf=false", ...GIT_CORE];
const GIT_CFG_QUOTE = [...GIT_CFG, "-c", "core.quotepath=false"];
interface GitResult {
readonly code: ChildProcessSpawner.ExitCode;
readonly text: string;
readonly stderr: string;
}
export namespace Snapshot { export namespace Snapshot {
const log = Log.create({ service: "snapshot" }) export const Patch = z.object({
const hour = 60 * 60 * 1000 hash: z.string(),
const prune = "7.days" files: z.string().array(),
});
export type Patch = z.infer<typeof Patch>;
function args(git: string, cmd: string[]) { export const FileDiff = z
return ["--git-dir", git, "--work-tree", Instance.worktree, ...cmd] .object({
} file: z.string(),
before: z.string(),
after: z.string(),
additions: z.number(),
deletions: z.number(),
status: z.enum(["added", "deleted", "modified"]).optional(),
})
.meta({
ref: "FileDiff",
});
export type FileDiff = z.infer<typeof FileDiff>;
export function init() { // Promise facade — existing callers use these
Scheduler.register({ export function init() {
id: "snapshot.cleanup", void runPromiseInstance(SnapshotService.use((s) => s.init()));
interval: hour, }
run: cleanup,
scope: "instance",
})
}
export async function cleanup() { export async function cleanup() {
if (Instance.project.vcs !== "git") return return runPromiseInstance(SnapshotService.use((s) => s.cleanup()));
const cfg = await Config.get() }
if (cfg.snapshot === false) return
const git = gitdir()
const exists = await fs
.stat(git)
.then(() => true)
.catch(() => false)
if (!exists) return
const result = await Process.run(["git", ...args(git, ["gc", `--prune=${prune}`])], {
cwd: Instance.directory,
nothrow: true,
})
if (result.code !== 0) {
log.warn("cleanup failed", {
exitCode: result.code,
stderr: result.stderr.toString(),
stdout: result.stdout.toString(),
})
return
}
log.info("cleanup", { prune })
}
export async function track() { export async function track() {
if (Instance.project.vcs !== "git") return return runPromiseInstance(SnapshotService.use((s) => s.track()));
const cfg = await Config.get() }
if (cfg.snapshot === false) return
const git = gitdir()
if (await fs.mkdir(git, { recursive: true })) {
await Process.run(["git", "init"], {
env: {
...process.env,
GIT_DIR: git,
GIT_WORK_TREE: Instance.worktree,
},
nothrow: true,
})
// Configure git to not convert line endings on Windows export async function patch(hash: string) {
await Process.run(["git", "--git-dir", git, "config", "core.autocrlf", "false"], { nothrow: true }) return runPromiseInstance(SnapshotService.use((s) => s.patch(hash)));
await Process.run(["git", "--git-dir", git, "config", "core.longpaths", "true"], { nothrow: true }) }
await Process.run(["git", "--git-dir", git, "config", "core.symlinks", "true"], { nothrow: true })
await Process.run(["git", "--git-dir", git, "config", "core.fsmonitor", "false"], { nothrow: true })
log.info("initialized")
}
await add(git)
const hash = await Process.text(["git", ...args(git, ["write-tree"])], {
cwd: Instance.directory,
nothrow: true,
}).then((x) => x.text)
log.info("tracking", { hash, cwd: Instance.directory, git })
return hash.trim()
}
export const Patch = z.object({ export async function restore(snapshot: string) {
hash: z.string(), return runPromiseInstance(SnapshotService.use((s) => s.restore(snapshot)));
files: z.string().array(), }
})
export type Patch = z.infer<typeof Patch>
export async function patch(hash: string): Promise<Patch> { export async function revert(patches: Patch[]) {
const git = gitdir() return runPromiseInstance(SnapshotService.use((s) => s.revert(patches)));
await add(git) }
const result = await Process.text(
[
"git",
"-c",
"core.autocrlf=false",
"-c",
"core.longpaths=true",
"-c",
"core.symlinks=true",
"-c",
"core.quotepath=false",
...args(git, ["diff", "--no-ext-diff", "--name-only", hash, "--", "."]),
],
{
cwd: Instance.directory,
nothrow: true,
},
)
// If git diff fails, return empty patch export async function diff(hash: string) {
if (result.code !== 0) { return runPromiseInstance(SnapshotService.use((s) => s.diff(hash)));
log.warn("failed to get diff", { hash, exitCode: result.code }) }
return { hash, files: [] }
}
const files = result.text export async function diffFull(from: string, to: string) {
return { return runPromiseInstance(SnapshotService.use((s) => s.diffFull(from, to)));
hash, }
files: files }
.trim()
.split("\n")
.map((x) => x.trim())
.filter(Boolean)
.map((x) => path.join(Instance.worktree, x).replaceAll("\\", "/")),
}
}
export async function restore(snapshot: string) { export namespace SnapshotService {
log.info("restore", { commit: snapshot }) export interface Service {
const git = gitdir() readonly init: () => Effect.Effect<void>;
const result = await Process.run( readonly cleanup: () => Effect.Effect<void>;
["git", "-c", "core.longpaths=true", "-c", "core.symlinks=true", ...args(git, ["read-tree", snapshot])], readonly track: () => Effect.Effect<string | undefined>;
{ readonly patch: (hash: string) => Effect.Effect<Snapshot.Patch>;
cwd: Instance.worktree, readonly restore: (snapshot: string) => Effect.Effect<void>;
nothrow: true, readonly revert: (patches: Snapshot.Patch[]) => Effect.Effect<void>;
}, readonly diff: (hash: string) => Effect.Effect<string>;
) readonly diffFull: (
if (result.code === 0) { from: string,
const checkout = await Process.run( to: string,
["git", "-c", "core.longpaths=true", "-c", "core.symlinks=true", ...args(git, ["checkout-index", "-a", "-f"])], ) => Effect.Effect<Snapshot.FileDiff[]>;
{ }
cwd: Instance.worktree, }
nothrow: true,
},
)
if (checkout.code === 0) return
log.error("failed to restore snapshot", {
snapshot,
exitCode: checkout.code,
stderr: checkout.stderr.toString(),
stdout: checkout.stdout.toString(),
})
return
}
log.error("failed to restore snapshot", { export class SnapshotService extends ServiceMap.Service<
snapshot, SnapshotService,
exitCode: result.code, SnapshotService.Service
stderr: result.stderr.toString(), >()("@opencode/Snapshot") {
stdout: result.stdout.toString(), static readonly layer = Layer.effect(
}) SnapshotService,
} Effect.gen(function* () {
const ctx = yield* InstanceContext;
const fileSystem = yield* FileSystem.FileSystem;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const { directory, worktree, project } = ctx;
const isGit = project.vcs === "git";
const snapshotGit = path.join(Global.Path.data, "snapshot", project.id);
export async function revert(patches: Patch[]) { const gitArgs = (cmd: string[]) => [
const files = new Set<string>() "--git-dir",
const git = gitdir() snapshotGit,
for (const item of patches) { "--work-tree",
for (const file of item.files) { worktree,
if (files.has(file)) continue ...cmd,
log.info("reverting", { file, hash: item.hash }) ];
const result = await Process.run(
[
"git",
"-c",
"core.longpaths=true",
"-c",
"core.symlinks=true",
...args(git, ["checkout", item.hash, "--", file]),
],
{
cwd: Instance.worktree,
nothrow: true,
},
)
if (result.code !== 0) {
const relativePath = path.relative(Instance.worktree, file)
const checkTree = await Process.text(
[
"git",
"-c",
"core.longpaths=true",
"-c",
"core.symlinks=true",
...args(git, ["ls-tree", item.hash, "--", relativePath]),
],
{
cwd: Instance.worktree,
nothrow: true,
},
)
if (checkTree.code === 0 && checkTree.text.trim()) {
log.info("file existed in snapshot but checkout failed, keeping", {
file,
})
} else {
log.info("file did not exist in snapshot, deleting", { file })
await fs.unlink(file).catch(() => {})
}
}
files.add(file)
}
}
}
export async function diff(hash: string) { // Run git with nothrow semantics — always returns a result, never fails
const git = gitdir() const git = (
await add(git) args: string[],
const result = await Process.text( opts?: { cwd?: string; env?: Record<string, string> },
[ ): Effect.Effect<GitResult> =>
"git", Effect.gen(function* () {
"-c", const command = ChildProcess.make("git", args, {
"core.autocrlf=false", cwd: opts?.cwd,
"-c", env: opts?.env,
"core.longpaths=true", extendEnv: true,
"-c", });
"core.symlinks=true", const handle = yield* spawner.spawn(command);
"-c", const [text, stderr] = yield* Effect.all(
"core.quotepath=false", [
...args(git, ["diff", "--no-ext-diff", hash, "--", "."]), Stream.mkString(Stream.decodeText(handle.stdout)),
], Stream.mkString(Stream.decodeText(handle.stderr)),
{ ],
cwd: Instance.worktree, { concurrency: 2 },
nothrow: true, );
}, const code = yield* handle.exitCode;
) return { code, text, stderr };
}).pipe(
Effect.scoped,
Effect.catch((err) =>
Effect.succeed({
code: ChildProcessSpawner.ExitCode(1),
text: "",
stderr: String(err),
}),
),
);
if (result.code !== 0) { // FileSystem helpers — orDie converts PlatformError to defects
log.warn("failed to get diff", { const exists = (p: string) => fileSystem.exists(p).pipe(Effect.orDie);
hash, const mkdir = (p: string) =>
exitCode: result.code, fileSystem.makeDirectory(p, { recursive: true }).pipe(Effect.orDie);
stderr: result.stderr.toString(), const writeFile = (p: string, content: string) =>
stdout: result.stdout.toString(), fileSystem.writeFileString(p, content).pipe(Effect.orDie);
}) const readFile = (p: string) =>
return "" fileSystem
} .readFileString(p)
.pipe(Effect.catch(() => Effect.succeed("")));
const removeFile = (p: string) =>
fileSystem.remove(p).pipe(Effect.catch(() => Effect.void));
return result.text.trim() // --- internal Effect helpers ---
}
export const FileDiff = z const isEnabled = Effect.gen(function* () {
.object({ if (!isGit) return false;
file: z.string(), const cfg = yield* Effect.promise(() => Config.get());
before: z.string(), return cfg.snapshot !== false;
after: z.string(), });
additions: z.number(),
deletions: z.number(),
status: z.enum(["added", "deleted", "modified"]).optional(),
})
.meta({
ref: "FileDiff",
})
export type FileDiff = z.infer<typeof FileDiff>
export async function diffFull(from: string, to: string): Promise<FileDiff[]> {
const git = gitdir()
const result: FileDiff[] = []
const status = new Map<string, "added" | "deleted" | "modified">()
const statuses = await Process.text( const excludesPath = Effect.gen(function* () {
[ const result = yield* git(
"git", ["rev-parse", "--path-format=absolute", "--git-path", "info/exclude"],
"-c", {
"core.autocrlf=false", cwd: worktree,
"-c", },
"core.longpaths=true", );
"-c", const file = result.text.trim();
"core.symlinks=true", if (!file) return undefined;
"-c", if (!(yield* exists(file))) return undefined;
"core.quotepath=false", return file;
...args(git, ["diff", "--no-ext-diff", "--name-status", "--no-renames", from, to, "--", "."]), });
],
{
cwd: Instance.directory,
nothrow: true,
},
).then((x) => x.text)
for (const line of statuses.trim().split("\n")) { const syncExclude = Effect.gen(function* () {
if (!line) continue const file = yield* excludesPath;
const [code, file] = line.split("\t") const target = path.join(snapshotGit, "info", "exclude");
if (!code || !file) continue yield* mkdir(path.join(snapshotGit, "info"));
const kind = code.startsWith("A") ? "added" : code.startsWith("D") ? "deleted" : "modified" if (!file) {
status.set(file, kind) yield* writeFile(target, "");
} return;
}
const text = yield* readFile(file);
yield* writeFile(target, text);
});
for (const line of await Process.lines( const add = Effect.gen(function* () {
[ yield* syncExclude;
"git", yield* git([...GIT_CFG, ...gitArgs(["add", "."])], { cwd: directory });
"-c", });
"core.autocrlf=false",
"-c",
"core.longpaths=true",
"-c",
"core.symlinks=true",
"-c",
"core.quotepath=false",
...args(git, ["diff", "--no-ext-diff", "--no-renames", "--numstat", from, to, "--", "."]),
],
{
cwd: Instance.directory,
nothrow: true,
},
)) {
if (!line) continue
const [additions, deletions, file] = line.split("\t")
const isBinaryFile = additions === "-" && deletions === "-"
const before = isBinaryFile
? ""
: await Process.text(
[
"git",
"-c",
"core.autocrlf=false",
"-c",
"core.longpaths=true",
"-c",
"core.symlinks=true",
...args(git, ["show", `${from}:${file}`]),
],
{ nothrow: true },
).then((x) => x.text)
const after = isBinaryFile
? ""
: await Process.text(
[
"git",
"-c",
"core.autocrlf=false",
"-c",
"core.longpaths=true",
"-c",
"core.symlinks=true",
...args(git, ["show", `${to}:${file}`]),
],
{ nothrow: true },
).then((x) => x.text)
const added = isBinaryFile ? 0 : parseInt(additions)
const deleted = isBinaryFile ? 0 : parseInt(deletions)
result.push({
file,
before,
after,
additions: Number.isFinite(added) ? added : 0,
deletions: Number.isFinite(deleted) ? deleted : 0,
status: status.get(file) ?? "modified",
})
}
return result
}
function gitdir() { // --- service methods ---
const project = Instance.project
return path.join(Global.Path.data, "snapshot", project.id)
}
async function add(git: string) { const cleanup = Effect.fn("SnapshotService.cleanup")(function* () {
await syncExclude(git) if (!(yield* isEnabled)) return;
await Process.run( if (!(yield* exists(snapshotGit))) return;
[ const result = yield* git(gitArgs(["gc", `--prune=${PRUNE}`]), {
"git", cwd: directory,
"-c", });
"core.autocrlf=false", if (result.code !== 0) {
"-c", log.warn("cleanup failed", {
"core.longpaths=true", exitCode: result.code,
"-c", stderr: result.stderr,
"core.symlinks=true", });
...args(git, ["add", "."]), return;
], }
{ log.info("cleanup", { prune: PRUNE });
cwd: Instance.directory, });
nothrow: true,
},
)
}
async function syncExclude(git: string) { const track = Effect.fn("SnapshotService.track")(function* () {
const file = await excludes() if (!(yield* isEnabled)) return undefined;
const target = path.join(git, "info", "exclude") const existed = yield* exists(snapshotGit);
await fs.mkdir(path.join(git, "info"), { recursive: true }) yield* mkdir(snapshotGit);
if (!file) { if (!existed) {
await Filesystem.write(target, "") yield* git(["init"], {
return env: { GIT_DIR: snapshotGit, GIT_WORK_TREE: worktree },
} });
const text = await Filesystem.readText(file).catch(() => "") yield* git([
"--git-dir",
snapshotGit,
"config",
"core.autocrlf",
"false",
]);
yield* git([
"--git-dir",
snapshotGit,
"config",
"core.longpaths",
"true",
]);
yield* git([
"--git-dir",
snapshotGit,
"config",
"core.symlinks",
"true",
]);
yield* git([
"--git-dir",
snapshotGit,
"config",
"core.fsmonitor",
"false",
]);
log.info("initialized");
}
yield* add;
const result = yield* git(gitArgs(["write-tree"]), { cwd: directory });
const hash = result.text.trim();
log.info("tracking", { hash, cwd: directory, git: snapshotGit });
return hash;
});
await Filesystem.write(target, text) const patch = Effect.fn("SnapshotService.patch")(function* (
} hash: string,
) {
yield* add;
const result = yield* git(
[
...GIT_CFG_QUOTE,
...gitArgs([
"diff",
"--no-ext-diff",
"--name-only",
hash,
"--",
".",
]),
],
{ cwd: directory },
);
async function excludes() { if (result.code !== 0) {
const file = await Process.text(["git", "rev-parse", "--path-format=absolute", "--git-path", "info/exclude"], { log.warn("failed to get diff", { hash, exitCode: result.code });
cwd: Instance.worktree, return { hash, files: [] } as Snapshot.Patch;
nothrow: true, }
}).then((x) => x.text)
if (!file.trim()) return return {
const exists = await fs hash,
.stat(file.trim()) files: result.text
.then(() => true) .trim()
.catch(() => false) .split("\n")
if (!exists) return .map((x: string) => x.trim())
return file.trim() .filter(Boolean)
} .map((x: string) => path.join(worktree, x).replaceAll("\\", "/")),
} as Snapshot.Patch;
});
const restore = Effect.fn("SnapshotService.restore")(function* (
snapshot: string,
) {
log.info("restore", { commit: snapshot });
const result = yield* git(
[...GIT_CORE, ...gitArgs(["read-tree", snapshot])],
{ cwd: worktree },
);
if (result.code === 0) {
const checkout = yield* git(
[...GIT_CORE, ...gitArgs(["checkout-index", "-a", "-f"])],
{ cwd: worktree },
);
if (checkout.code === 0) return;
log.error("failed to restore snapshot", {
snapshot,
exitCode: checkout.code,
stderr: checkout.stderr,
});
return;
}
log.error("failed to restore snapshot", {
snapshot,
exitCode: result.code,
stderr: result.stderr,
});
});
const revert = Effect.fn("SnapshotService.revert")(function* (
patches: Snapshot.Patch[],
) {
const seen = new Set<string>();
for (const item of patches) {
for (const file of item.files) {
if (seen.has(file)) continue;
log.info("reverting", { file, hash: item.hash });
const result = yield* git(
[...GIT_CORE, ...gitArgs(["checkout", item.hash, "--", file])],
{
cwd: worktree,
},
);
if (result.code !== 0) {
const relativePath = path.relative(worktree, file);
const checkTree = yield* git(
[
...GIT_CORE,
...gitArgs(["ls-tree", item.hash, "--", relativePath]),
],
{
cwd: worktree,
},
);
if (checkTree.code === 0 && checkTree.text.trim()) {
log.info(
"file existed in snapshot but checkout failed, keeping",
{ file },
);
} else {
log.info("file did not exist in snapshot, deleting", { file });
yield* removeFile(file);
}
}
seen.add(file);
}
}
});
const diff = Effect.fn("SnapshotService.diff")(function* (hash: string) {
yield* add;
const result = yield* git(
[
...GIT_CFG_QUOTE,
...gitArgs(["diff", "--no-ext-diff", hash, "--", "."]),
],
{
cwd: worktree,
},
);
if (result.code !== 0) {
log.warn("failed to get diff", {
hash,
exitCode: result.code,
stderr: result.stderr,
});
return "";
}
return result.text.trim();
});
const diffFull = Effect.fn("SnapshotService.diffFull")(function* (
from: string,
to: string,
) {
const result: Snapshot.FileDiff[] = [];
const status = new Map<string, "added" | "deleted" | "modified">();
const statuses = yield* git(
[
...GIT_CFG_QUOTE,
...gitArgs([
"diff",
"--no-ext-diff",
"--name-status",
"--no-renames",
from,
to,
"--",
".",
]),
],
{ cwd: directory },
);
for (const line of statuses.text.trim().split("\n")) {
if (!line) continue;
const [code, file] = line.split("\t");
if (!code || !file) continue;
const kind = code.startsWith("A")
? "added"
: code.startsWith("D")
? "deleted"
: "modified";
status.set(file, kind);
}
const numstat = yield* git(
[
...GIT_CFG_QUOTE,
...gitArgs([
"diff",
"--no-ext-diff",
"--no-renames",
"--numstat",
from,
to,
"--",
".",
]),
],
{ cwd: directory },
);
for (const line of numstat.text.trim().split("\n")) {
if (!line) continue;
const [additions, deletions, file] = line.split("\t");
const isBinaryFile = additions === "-" && deletions === "-";
const [before, after] = isBinaryFile
? ["", ""]
: yield* Effect.all(
[
git([
...GIT_CFG,
...gitArgs(["show", `${from}:${file}`]),
]).pipe(Effect.map((r) => r.text)),
git([...GIT_CFG, ...gitArgs(["show", `${to}:${file}`])]).pipe(
Effect.map((r) => r.text),
),
],
{ concurrency: 2 },
);
const added = isBinaryFile ? 0 : parseInt(additions!);
const deleted = isBinaryFile ? 0 : parseInt(deletions!);
result.push({
file: file!,
before,
after,
additions: Number.isFinite(added) ? added : 0,
deletions: Number.isFinite(deleted) ? deleted : 0,
status: status.get(file!) ?? "modified",
});
}
return result;
});
// Start hourly cleanup fiber — scoped to instance lifetime
yield* cleanup().pipe(
Effect.catchCause((cause) => {
log.error("cleanup loop failed", { cause: Cause.pretty(cause) });
return Effect.void;
}),
Effect.repeat(Schedule.spaced(Duration.hours(1))),
Effect.forkScoped,
);
return SnapshotService.of({
init: Effect.fn("SnapshotService.init")(function* () {}),
cleanup,
track,
patch,
restore,
revert,
diff,
diffFull,
});
}),
).pipe(
Layer.provide(NodeChildProcessSpawner.layer),
Layer.provide(NodeFileSystem.layer),
Layer.provide(NodePath.layer),
);
} }
+38 -32
View File
@@ -1,14 +1,14 @@
import { ConfigProvider, Layer, ManagedRuntime } from "effect" import { ConfigProvider, Layer, ManagedRuntime } from "effect";
import { InstanceContext } from "../../src/effect/instance-context" import { InstanceContext } from "../../src/effect/instance-context";
import { Instance } from "../../src/project/instance" import { Instance } from "../../src/project/instance";
/** ConfigProvider that enables the experimental file watcher. */ /** ConfigProvider that enables the experimental file watcher. */
export const watcherConfigLayer = ConfigProvider.layer( export const watcherConfigLayer = ConfigProvider.layer(
ConfigProvider.fromUnknown({ ConfigProvider.fromUnknown({
OPENCODE_EXPERIMENTAL_FILEWATCHER: "true", OPENCODE_EXPERIMENTAL_FILEWATCHER: "true",
OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER: "false", OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER: "false",
}), }),
) );
/** /**
* Boot an Instance with the given service layers and run `body` with * Boot an Instance with the given service layers and run `body` with
@@ -19,29 +19,35 @@ export const watcherConfigLayer = ConfigProvider.layer(
* Pass extra layers via `options.provide` (e.g. ConfigProvider.layer). * Pass extra layers via `options.provide` (e.g. ConfigProvider.layer).
*/ */
export function withServices<S>( export function withServices<S>(
directory: string, directory: string,
layer: Layer.Layer<S, any, InstanceContext>, layer: Layer.Layer<S, any, InstanceContext>,
body: (rt: ManagedRuntime.ManagedRuntime<S, never>) => Promise<void>, body: (rt: ManagedRuntime.ManagedRuntime<S, never>) => Promise<void>,
options?: { provide?: Layer.Layer<never>[] }, options?: { provide?: Layer.Layer<never>[] },
) { ) {
return Instance.provide({ return Instance.provide({
directory, directory,
fn: async () => { fn: async () => {
const ctx = Layer.sync(InstanceContext, () => const ctx = Layer.sync(InstanceContext, () =>
InstanceContext.of({ directory: Instance.directory, project: Instance.project }), InstanceContext.of({
) directory: Instance.directory,
let resolved: Layer.Layer<S> = Layer.fresh(layer).pipe(Layer.provide(ctx)) as any worktree: Instance.worktree,
if (options?.provide) { project: Instance.project,
for (const l of options.provide) { }),
resolved = resolved.pipe(Layer.provide(l)) as any );
} let resolved: Layer.Layer<S> = Layer.fresh(layer).pipe(
} Layer.provide(ctx),
const rt = ManagedRuntime.make(resolved) ) as any;
try { if (options?.provide) {
await body(rt) for (const l of options.provide) {
} finally { resolved = resolved.pipe(Layer.provide(l)) as any;
await rt.dispose() }
} }
}, const rt = ManagedRuntime.make(resolved);
}) try {
await body(rt);
} finally {
await rt.dispose();
}
},
});
} }