Skip to content

Commit c20ce8d

Browse files
committed
fix(core): rebuild a location after its directory becomes a git repo
A location graph is cached for its whole life and resolves its project once, so opening a folder before `git init` pinned the markerless identity and its sessions kept being reported under it. Record the resolved project id and re-resolve before a borrow only when the identity could not be pinned yet: a directory without a VCS marker, or a repository without a commit or remote (`global`). The graph is invalidated only when that id changes. Without a VCS, Project.root decides whether a marker appeared at or above the location with async probes, which also covers opening a subfolder before its parent becomes a repo. The check never runs while the location is borrowed or retained, and the detach is a deferred invalidation instead of `lifecycle.shutdown`, so a running step keeps its graph until it hands off.
1 parent 1bf08ae commit c20ce8d

3 files changed

Lines changed: 211 additions & 37 deletions

File tree

‎packages/core/src/location-lifecycle.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ export class Service extends Context.Service<
2727
/** Keeps the idle sweep from evicting the Location for the calling scope, for open client connections. */
2828
readonly retain: Effect.Effect<void, never, Scope.Scope>
2929
readonly isRetained: () => boolean
30+
/** Resolves the Project this Location belongs to again, without persisting it. */
31+
readonly resolveProject: Effect.Effect<Project.Resolved>
3032
}
3133
>()("@opencode/LocationLifecycle") {}
3234

@@ -86,6 +88,7 @@ const layer = Layer.effect(
8688
}),
8789
),
8890
isRetained: () => retained > 0,
91+
resolveProject: project.resolve(location.directory, { persist: false }),
8992
})
9093
}),
9194
)

‎packages/core/src/location-services.ts‎

Lines changed: 120 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,48 @@
1+
import fs from "node:fs/promises"
12
import { Context, Duration, Effect, Exit, Layer, LayerMap, MutableHashMap, Option, Scope } from "effect"
23
import { LayerNode } from "@opencode/util/effect/layer-node"
34
import { Instance } from "./instance.js"
45
import { Location } from "./location.js"
56
import { LocationLifecycle } from "./location-lifecycle.js"
67
import { LocationServiceMap } from "./location-service-map.js"
8+
import { Project } from "./project.js"
79

810
export { LocationServiceMap } from "./location-service-map.js"
911

1012
export type LocationServices = Instance.Services
1113

1214
const HELD_WARNING_AFTER = "30 seconds"
1315

16+
// An identity that could not be pinned when the graph booted: the directory had no VCS yet, or
17+
// the repository has no commit or remote to name it. Only these graphs can become stale.
18+
type Provisional = {
19+
readonly id: Project.ID
20+
readonly vcs: boolean
21+
readonly resolve: Effect.Effect<Project.Resolved>
22+
}
23+
24+
const exists = (target: string) =>
25+
Effect.tryPromise(() => fs.access(target)).pipe(
26+
Effect.as(true),
27+
Effect.orElseSucceed(() => false),
28+
)
29+
30+
type Build = {
31+
close?: Effect.Effect<void>
32+
provisional?: Provisional
33+
}
34+
1435
export function buildLocationServiceMap(
1536
replacements: LayerNode.Replacements = [],
1637
): Layer.Layer<LocationServiceMap.Service> {
1738
return Layer.effect(
1839
LocationServiceMap.Service,
1940
Effect.gen(function* () {
2041
const owner = yield* Effect.scope
21-
const builds = MutableHashMap.empty<Location.Ref, { close?: Effect.Effect<void> }>()
42+
const builds = MutableHashMap.empty<Location.Ref, Build>()
2243
const inner: LayerMap.LayerMap<Location.Ref, LocationServices, Instance.Error> = yield* LayerMap.make(
2344
(ref: Location.Ref) => {
24-
const build: { close?: Effect.Effect<void> } = {}
45+
const build: Build = {}
2546
MutableHashMap.set(builds, ref, build)
2647
return Layer.fromBuild((memoMap, scope) =>
2748
Effect.suspend(() =>
@@ -36,6 +57,13 @@ export function buildLocationServiceMap(
3657
if (Option.getOrUndefined(MutableHashMap.get(builds, ref)) !== build)
3758
return yield* lifecycle.shutdown
3859
build.close = lifecycle.shutdown
60+
const location = Context.get(exit.value, Location.Service)
61+
if (location.vcs !== undefined && location.project.id !== Project.ID.global) return
62+
build.provisional = {
63+
id: location.project.id,
64+
vcs: location.vcs !== undefined,
65+
resolve: lifecycle.resolveProject,
66+
}
3967
})
4068
}
4169
// An explicitly invalidated build must not evict its replacement.
@@ -69,45 +97,100 @@ export function buildLocationServiceMap(
6997
}),
7098
),
7199
)
100+
// Detach routing first, then cancel interactions and notify clients. Running
101+
// steps retain their borrowed graph until they can hand off at a boundary.
102+
// Do not await a boot here: failed/in-flight builds have their own cleanup path.
103+
const drop = (key: Location.Ref) =>
104+
Effect.suspend(() => {
105+
const build = Option.getOrUndefined(MutableHashMap.get(builds, key))
106+
MutableHashMap.remove(builds, key)
107+
const state = inner.rcMap.state
108+
const held = state._tag === "Open" ? Option.getOrUndefined(MutableHashMap.get(state.map, key)) : undefined
109+
return inner.invalidate(key).pipe(
110+
Effect.andThen(build?.close ?? Effect.void),
111+
Effect.andThen(
112+
// Borrowers release on shutdown; one that does not keeps every service of this Location running.
113+
// The timer lives in the Location's scope, so it stops as soon as the last borrower lets go
114+
// (forking into an already closed scope never starts it).
115+
held
116+
? Effect.sleep(HELD_WARNING_AFTER).pipe(
117+
Effect.andThen(
118+
Effect.suspend(() =>
119+
Effect.logWarning("location still held after shutdown", {
120+
directory: key.directory,
121+
workspaceID: key.workspaceID,
122+
holders: held.refCount,
123+
}),
124+
),
125+
),
126+
Effect.forkIn(held.scope),
127+
Effect.asVoid,
128+
)
129+
: Effect.void,
130+
),
131+
)
132+
}).pipe(Effect.uninterruptible)
133+
// A directory can turn into a VCS root after its graph was built (git init in a folder that
134+
// opencode already opened). Nothing re-resolves a cached graph, so the graphs whose identity
135+
// could not be pinned are re-resolved before a borrow. Only unborrowed locations are touched:
136+
// a running step keeps the graph it resolved and hands off once it releases it.
137+
const refresh = (key: Location.Ref) =>
138+
Effect.suspend(() => {
139+
const build = Option.getOrUndefined(MutableHashMap.get(builds, key))
140+
const provisional = build?.provisional
141+
if (!build || !provisional) return Effect.void
142+
const state = inner.rcMap.state
143+
const held = state._tag === "Open" ? Option.getOrUndefined(MutableHashMap.get(state.map, key)) : undefined
144+
if (held && held.refCount > 0) return Effect.void
145+
return Effect.gen(function* () {
146+
// A graph without a VCS only changes once a marker appears at or above its directory
147+
// (opening `proj/src` before `proj` becomes a repo). Project.root walks up with async
148+
// probes; graphs that already resolved a VCS skip it.
149+
if (!provisional.vcs) {
150+
const root = yield* Project.root({ exists }, key.directory)
151+
if (root === undefined) return
152+
}
153+
// An open terminal or client socket keeps its Location loaded; rebuilding would end it.
154+
const retained = yield* Effect.scoped(
155+
inner.contextEffectOption(key).pipe(
156+
Effect.map((context) =>
157+
Option.exists(context, (context) =>
158+
Option.exists(Context.getOption(context, LocationLifecycle.Service), (lifecycle) =>
159+
lifecycle.isRetained(),
160+
),
161+
),
162+
),
163+
Effect.orElseSucceed(() => false),
164+
),
165+
)
166+
if (retained) return
167+
const resolved = yield* provisional.resolve
168+
if (resolved.id === provisional.id) return
169+
// Another refresh may have replaced this build while the identity resolved.
170+
if (Option.getOrUndefined(MutableHashMap.get(builds, key)) !== build) return
171+
MutableHashMap.remove(builds, key)
172+
// Detach without shutting the old graph down. Invalidate releases it when its last
173+
// borrower lets go, so a running step is never interrupted mid-turn.
174+
yield* inner.invalidate(key)
175+
})
176+
})
72177
const map = {
73178
...inner,
74-
get: (ref: Location.Ref) => inner.get(LocationServiceMap.canonical(ref)),
75-
contextEffect: (ref: Location.Ref) => inner.contextEffect(LocationServiceMap.canonical(ref)),
76-
contextEffectOption: (ref: Location.Ref) => inner.contextEffectOption(LocationServiceMap.canonical(ref)),
77-
invalidate: (ref: Location.Ref) =>
179+
get: (ref: Location.Ref) => {
180+
const key = LocationServiceMap.canonical(ref)
181+
return Layer.unwrap(Effect.suspend(() => refresh(key).pipe(Effect.as(inner.get(key)))))
182+
},
183+
contextEffect: (ref: Location.Ref) =>
78184
Effect.suspend(() => {
79185
const key = LocationServiceMap.canonical(ref)
80-
const build = Option.getOrUndefined(MutableHashMap.get(builds, key))
81-
MutableHashMap.remove(builds, key)
82-
const state = inner.rcMap.state
83-
const held = state._tag === "Open" ? Option.getOrUndefined(MutableHashMap.get(state.map, key)) : undefined
84-
// Detach routing first, then cancel interactions and notify clients. Running
85-
// steps retain their borrowed graph until they can hand off at a boundary.
86-
// Do not await a boot here: failed/in-flight builds have their own cleanup path.
87-
return inner.invalidate(key).pipe(
88-
Effect.andThen(build?.close ?? Effect.void),
89-
Effect.andThen(
90-
// Borrowers release on shutdown; one that does not keeps every service of this Location running.
91-
// The timer lives in the Location's scope, so it stops as soon as the last borrower lets go
92-
// (forking into an already closed scope never starts it).
93-
held
94-
? Effect.sleep(HELD_WARNING_AFTER).pipe(
95-
Effect.andThen(
96-
Effect.suspend(() =>
97-
Effect.logWarning("location still held after shutdown", {
98-
directory: key.directory,
99-
workspaceID: key.workspaceID,
100-
holders: held.refCount,
101-
}),
102-
),
103-
),
104-
Effect.forkIn(held.scope),
105-
Effect.asVoid,
106-
)
107-
: Effect.void,
108-
),
109-
)
110-
}).pipe(Effect.uninterruptible),
186+
return refresh(key).pipe(Effect.andThen(inner.contextEffect(key)))
187+
}),
188+
contextEffectOption: (ref: Location.Ref) =>
189+
Effect.suspend(() => {
190+
const key = LocationServiceMap.canonical(ref)
191+
return refresh(key).pipe(Effect.andThen(inner.contextEffectOption(key)))
192+
}),
193+
invalidate: (ref: Location.Ref) => drop(LocationServiceMap.canonical(ref)),
111194
}
112195
// Cached instances borrow their owner instead of retaining its Layer scope.
113196
const bindings: LayerNode.Replacements = [

‎packages/core/test/location-layer.test.ts‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { FileSystem } from "@opencode/core/filesystem"
22
import fs from "fs/promises"
33
import path from "path"
44
import { describe, expect } from "bun:test"
5+
import { $ } from "bun"
56
import { Event } from "@opencode/schema/config"
67
import { Money } from "@opencode/schema/money"
78
import {
@@ -510,6 +511,93 @@ describe("LocationServiceMap", () => {
510511
),
511512
)
512513

514+
it.live("rebuilds a cached location when its directory becomes a git repo", () =>
515+
Effect.gen(function* () {
516+
const dir = yield* tmpdirScoped()
517+
const directory = AbsolutePath.make(dir.path)
518+
const ref = Location.Ref.make({ directory })
519+
const locations = yield* LocationServiceMap.Service
520+
const borrow = Effect.gen(function* () {
521+
return Context.get(yield* locations.contextEffect(ref), Location.Service)
522+
}).pipe(Effect.scoped)
523+
524+
// A location built before the directory is a repo keeps the markerless identity.
525+
const before = yield* borrow
526+
expect(before.vcs).toBeUndefined()
527+
528+
yield* Effect.promise(() => $`git init -q`.cwd(dir.path).quiet())
529+
530+
// Borrowing between init and the first commit resolves a git graph that has no identity yet.
531+
const pending = yield* borrow
532+
expect(pending.vcs?.type).toBe("git")
533+
expect(pending.project.id).toBe(Project.ID.global)
534+
535+
yield* Effect.promise(() =>
536+
$`git -c user.name=Test -c [email protected] -c commit.gpgsign=false commit --allow-empty -qm root`
537+
.cwd(dir.path)
538+
.quiet(),
539+
)
540+
const head = (yield* Effect.promise(() => $`git rev-parse HEAD`.cwd(dir.path).text())).trim()
541+
542+
// The commit pins the identity; the next borrow must report it instead of keeping `global`.
543+
const after = yield* borrow
544+
expect(after.vcs?.type).toBe("git")
545+
expect(after.project.id).toBe(Project.ID.make(head))
546+
}),
547+
)
548+
549+
it.live("keeps a borrowed location on its identity until the borrow is released", () =>
550+
Effect.gen(function* () {
551+
const dir = yield* tmpdirScoped()
552+
const directory = AbsolutePath.make(dir.path)
553+
const ref = Location.Ref.make({ directory })
554+
const locations = yield* LocationServiceMap.Service
555+
const hold = Effect.gen(function* () {
556+
return Context.get(yield* locations.contextEffect(ref), Location.Service)
557+
})
558+
const borrow = hold.pipe(Effect.scoped)
559+
560+
const before = yield* borrow
561+
expect(before.vcs).toBeUndefined()
562+
563+
// A running step keeps the graph it resolved: the repo appearing underneath it must wait for
564+
// the borrow to be released instead of shutting the location down mid-turn.
565+
yield* Effect.scoped(
566+
Effect.gen(function* () {
567+
expect((yield* hold).project.id).toBe(before.project.id)
568+
yield* Effect.promise(() => $`git init -q`.cwd(dir.path).quiet())
569+
expect((yield* hold).project.id).toBe(before.project.id)
570+
}),
571+
)
572+
573+
const after = yield* borrow
574+
expect(after.vcs?.type).toBe("git")
575+
}),
576+
)
577+
578+
it.live("rebuilds a location when a parent directory becomes a git repo", () =>
579+
Effect.gen(function* () {
580+
const dir = yield* tmpdirScoped()
581+
const directory = AbsolutePath.make(path.join(dir.path, "src"))
582+
yield* Effect.promise(() => fs.mkdir(directory, { recursive: true }))
583+
const ref = Location.Ref.make({ directory })
584+
const locations = yield* LocationServiceMap.Service
585+
const borrow = Effect.gen(function* () {
586+
return Context.get(yield* locations.contextEffect(ref), Location.Service)
587+
}).pipe(Effect.scoped)
588+
589+
// Opened in a subfolder while nothing above it is a repo.
590+
expect((yield* borrow).vcs).toBeUndefined()
591+
592+
// The repo appears above the opened folder rather than in it.
593+
yield* Effect.promise(() => $`git init -q`.cwd(dir.path).quiet())
594+
595+
const after = yield* borrow
596+
expect(after.vcs?.type).toBe("git")
597+
expect(after.project.id).toBe(Project.ID.global)
598+
}),
599+
)
600+
513601
it.live("isolates provider state by location", () =>
514602
Effect.acquireRelease(
515603
Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),

0 commit comments

Comments
 (0)