1+ import fs from "node:fs/promises"
12import { Context , Duration , Effect , Exit , Layer , LayerMap , MutableHashMap , Option , Scope } from "effect"
23import { LayerNode } from "@opencode/util/effect/layer-node"
34import { Instance } from "./instance.js"
45import { Location } from "./location.js"
56import { LocationLifecycle } from "./location-lifecycle.js"
67import { LocationServiceMap } from "./location-service-map.js"
8+ import { Project } from "./project.js"
79
810export { LocationServiceMap } from "./location-service-map.js"
911
1012export type LocationServices = Instance . Services
1113
1214const 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+
1435export 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 = [
0 commit comments