1- import { randomUUID } from 'node:crypto' ;
2- import { chmodSync , mkdirSync , mkdtempSync , rmSync , writeFileSync } from 'node:fs' ;
1+ import { chmodSync , rmSync } from 'node:fs' ;
32import { tmpdir } from 'node:os' ;
43import { basename , dirname , join } from 'node:path' ;
5- import type { InvocationContext , InvocationInput , InvocationResult , StopReason } from '../agents/contract.ts' ;
6- import type { TaskFilesystems , TaskStorageLimits } from '../agents/container/storage.ts' ;
4+ import type { InvocationInput , InvocationResult , StopReason } from '../agents/contract.ts' ;
5+ import type { TaskStorageLimits } from '../agents/container/storage.ts' ;
76import type { AuthorProvider , AuthorRequest } from '../core/planning-author.ts' ;
8- import { allocations , RetainedStorage , stopOf , type ContainerDependencies , type LeftoverPolicy , type Provider } from './question-container.ts' ;
7+ import { allocations , exceedsStorage , RetainedStorage , runReadOnlyAgent , sameContext , type ContainerDependencies , type LeftoverPolicy , type Provider ,
8+ type ReadOnlyFeature , type RepositorySize } from './question-container.ts' ;
99
1010/** Ask's lane D dependencies, less startup recovery, which the runner owns for planning. */
1111export type PlanningDependencies = Omit < ContainerDependencies , 'recover' > ;
@@ -53,9 +53,10 @@ const ROOT_PREFIX = 'codeboost-planning-';
5353 */
5454export function removePlanningRoot ( root : string ) : void {
5555 if ( dirname ( root ) !== tmpdir ( ) || ! basename ( root ) . startsWith ( ROOT_PREFIX ) )
56- throw new Error ( `Refusing to remove a path that is not a planning root (${ root } ).` ) ;
56+ throw new Error ( `A copy of the planned code could not be deleted (${ root } ): it is not a planning root .` ) ;
5757 try { chmodSync ( join ( root , 'input' ) , 0o700 ) ; } catch { /* never created, or already removed */ }
58- rmSync ( root , { recursive : true , force : true , maxRetries : 3 , retryDelay : 50 } ) ;
58+ try { rmSync ( root , { recursive : true , force : true , maxRetries : 3 , retryDelay : 50 } ) ; }
59+ catch ( error ) { throw new Error ( `A copy of the planned code could not be deleted (${ root } ).` , { cause : error } ) ; }
5960}
6061
6162// Planning reads the code; it needs no room to write. The same ceilings as Ask.
@@ -79,9 +80,6 @@ const stopMessages: Record<StopReason, string> = {
7980 cancelled : 'Planning agent cancelled.' , timeout : 'Planning agent timed out.' , shutdown : 'Server stopped during planning.' ,
8081 'output-limit' : 'Planning agent output exceeded its limit.' , 'capture-failure' : 'Planning agent output could not be captured.' ,
8182} ;
82- const sameContext = ( left : InvocationContext , right : InvocationContext ) =>
83- ( Object . keys ( right ) as ( keyof InvocationContext ) [ ] ) . every ( key => left [ key ] === right [ key ] )
84- && Object . keys ( left ) . length === Object . keys ( right ) . length ;
8583/** Accept only this exact invocation's output, and only after a clean exit. The text is still unvalidated. */
8684export function planningOutput ( result : InvocationResult , invocation : InvocationInput ) : string {
8785 if ( result . attemptId !== invocation . attemptId || ! result . context || ! sameContext ( result . context , invocation . context ) )
@@ -96,6 +94,22 @@ export function planningOutput(result: InvocationResult, invocation: InvocationI
9694 return result . stdout ;
9795}
9896
97+ const text = ( error : unknown ) => error instanceof Error ? error . message : String ( error ) ;
98+ /** Planning's part of a read-only run (see `runReadOnlyAgent`). */
99+ export const PLANNING_FEATURE : ReadOnlyFeature = Object . freeze ( {
100+ phase : 'planning' , rootPrefix : ROOT_PREFIX , removeRoot : removePlanningRoot , storage : PLANNING_STORAGE ,
101+ credential : planningCredential , timedOut : stopMessages . timeout ,
102+ assertFits : ( size : RepositorySize ) => {
103+ if ( exceedsStorage ( size , PLANNING_STORAGE ) ) throw new Error ( 'The repository is too large for planning.' ) ;
104+ } ,
105+ output : ( _vendor : Provider , result : InvocationResult , invocation : InvocationInput ) => planningOutput ( result , invocation ) ,
106+ // What cleanup left is retained, and the next request names it. A successful request is refused rather than
107+ // returned, as Ask does, so a plan is never kept from an unsettled run. A failed one keeps its own message first.
108+ cleanupFailed : ( failures : readonly unknown [ ] , failure ?: { error : unknown } ) => failure
109+ ? new AggregateError ( [ failure . error , ...failures ] , `${ text ( failure . error ) } Cleanup also did not settle: ${ failures . map ( text ) . join ( '; ' ) } ` )
110+ : new AggregateError ( failures , 'Planning container cleanup did not settle.' ) ,
111+ } ) ;
112+
99113/**
100114 * E2's provider over lane D: each request runs in a fresh container on a read-only copy of `head`, in the "planning"
101115 * phase (read, list and search only; no commands) with vendor-only egress. The request's schema is the only file in
@@ -114,73 +128,12 @@ export function createPlanningProvider(options: PlanningProviderOptions): Planni
114128 if ( ! Number . isSafeInteger ( timeoutMs ) || timeoutMs < 1 ) throw new Error ( 'Planning timeout must be a positive integer.' ) ;
115129 return { async invoke ( request : AuthorRequest , signal : AbortSignal ) : Promise < string > {
116130 if ( request . phase !== 'planning' || request . access !== 'read-only' ) throw new Error ( 'Planning requests must be read-only.' ) ;
117- const deadline = Date . now ( ) + timeoutMs ;
118- const remaining = ( ) => {
119- signal . throwIfAborted ( ) ;
120- const value = deadline - Date . now ( ) ;
121- if ( value < 1 ) throw new Error ( stopMessages . timeout ) ;
122- return value ;
123- } ;
124131 signal . throwIfAborted ( ) ;
125- const credential = planningCredential ( vendor , deps . env ) ;
126- retained . release ( deps . removeFilesystems ) ;
127- image . id ??= deps . buildImage ( remaining ( ) ) ;
128- const root = mkdtempSync ( join ( tmpdir ( ) , ROOT_PREFIX ) ) ;
129- const staging = join ( root , 'staging' ) , input = join ( root , 'input' ) ;
130- let filesystems : TaskFilesystems | undefined , failure : { error : unknown } | undefined ;
131- try {
132- mkdirSync ( staging ) ; mkdirSync ( input ) ;
133- writeFileSync ( join ( input , 'schema.json' ) , request . schemaText , { mode : 0o444 } ) ;
134- chmodSync ( input , 0o555 ) ;
135- // The clone is a full host copy with no byte limit of its own, so the repository must fit before it is made.
136- const size = deps . measureRepository ( options . repository , options . head , Math . min ( 60_000 , remaining ( ) ) ) ;
137- if ( size . checkoutBytes > PLANNING_STORAGE . workBytes || size . entries > PLANNING_STORAGE . workInodes
138- || size . objectBytes > PLANNING_STORAGE . metadataBytes )
139- throw new Error ( 'The repository is too large for planning.' ) ;
140- const clone = deps . createClone ( { source : options . repository , parent : staging , taskId : `planning-${ request . requestId } ` ,
141- head : options . head , timeoutMs : Math . min ( 120_000 , remaining ( ) ) } ) ;
142- const owner = { runnerOwner : options . runnerOwner , attemptId : request . requestId , allocationId : randomUUID ( ) } ;
143- try { filesystems = deps . prepareFilesystems ( clone , PLANNING_STORAGE , image . id , owner , Math . min ( 60_000 , remaining ( ) ) ) ; }
144- catch ( error ) {
145- // D throws an AggregateError only when a failed allocation's own cleanup did not settle; it returns no handle.
146- if ( error instanceof AggregateError ) retained . markUntracked ( ) ;
147- throw error ;
148- }
149- remaining ( ) ;
150- const invocation = deps . capture ( { clone, phase : 'planning' , vendor : 'claude' , approvedArgv : [ ] , deadline,
151- attemptId : request . requestId , runnerOwner : options . runnerOwner ,
152- context : { snapshotId : options . snapshotId , planId : request . identity . planId , planRevision : request . revision ,
153- assignmentId : `${ request . mode } -${ request . issue } ` , referencedCodeHash : options . head , stateVersion : 0 } } ) ;
154- const adapterRequest = { invocation, filesystems, inputDirectory : input , imageId : image . id , prompt : request . prompt ,
155- networkAllocationId : randomUUID ( ) } ;
156- const handle = deps . startClaude ( adapterRequest , credential ) ;
157- const cancel = ( ) => handle . cancel ( stopOf ( signal . reason ) ) ;
158- if ( signal . aborted ) cancel ( ) ; else signal . addEventListener ( 'abort' , cancel , { once : true } ) ;
159- let result : InvocationResult ;
160- try { result = await handle . settled ; }
161- finally { signal . removeEventListener ( 'abort' , cancel ) ; }
162- // D stopped before confirming cleanup; the resources are found again by their labels after a restart.
163- if ( result . unreleased !== undefined ) retained . markUntracked ( ) ;
164- return planningOutput ( result , invocation ) ;
165- } catch ( error ) {
166- failure = { error } ;
167- throw error ;
168- } finally {
169- const failures : unknown [ ] = [ ] ;
170- if ( filesystems ) try { deps . removeFilesystems ( filesystems ) ; } catch ( error ) { retained . retain ( filesystems ) ; failures . push ( error ) ; }
171- try { removePlanningRoot ( root ) ; }
172- catch ( error ) {
173- retained . retainPath ( root ) ;
174- failures . push ( new Error ( `A copy of the planned code could not be deleted (${ root } ).` , { cause : error } ) ) ;
175- }
176- // What cleanup left is retained above, and the next request names it. A successful request is refused rather than
177- // returned, as Ask does, so a plan is never kept from an unsettled run. A failed one keeps its own message first.
178- if ( failures . length ) {
179- const text = ( error : unknown ) => error instanceof Error ? error . message : String ( error ) ;
180- throw failure
181- ? new AggregateError ( [ failure . error , ...failures ] , `${ text ( failure . error ) } Cleanup also did not settle: ${ failures . map ( text ) . join ( '; ' ) } ` )
182- : new AggregateError ( failures , 'Planning container cleanup did not settle.' ) ;
183- }
184- }
132+ return runReadOnlyAgent ( PLANNING_FEATURE , { provider : vendor , repository : options . repository , head : options . head ,
133+ runnerOwner : options . runnerOwner , attemptId : request . requestId , taskId : `planning-${ request . requestId } ` ,
134+ deadline : Date . now ( ) + timeoutMs , prompt : request . prompt , schemaText : request . schemaText ,
135+ context : { snapshotId : options . snapshotId , planId : request . identity . planId , planRevision : request . revision ,
136+ assignmentId : `${ request . mode } -${ request . issue } ` , referencedCodeHash : options . head , stateVersion : 0 } } ,
137+ deps , signal , image , retained ) ;
185138 } } ;
186139}
0 commit comments