@@ -119,6 +119,158 @@ export function namesLabDirectly(source: string): boolean {
119119 || / \b i m p o r t \s * \( \s * [ " ' ] [ ^ " ' ] * \/ l a b (?: \/ | [ " ' ] ) / . test ( source ) ;
120120}
121121
122+
123+ /**
124+ * Guard 3: the activation window inside `startServer` must stay synchronous.
125+ *
126+ * `AGENTS.md` states this guarantee as if it were enforced, and
127+ * `devlog/_fin/260814_lab_core_decoupling/080_activation_is_synchronous.md:143` recorded it
128+ * as a Phase-4 test — but no such scan was ever written, so the invariant was held by
129+ * nothing except the current code being correct.
130+ *
131+ * The failure it guards against is silent. Everything between `Bun.serve` and the return
132+ * of `startServer` runs in one synchronous turn, which is what guarantees a policy route
133+ * can never be evaluated before its evidence provider is registered. Add one `await` in
134+ * that window and the synchronous subagent-fallback chain observes an empty slot and
135+ * routes subagents to a different model than the operator configured. Nothing goes red;
136+ * the wrong model simply answers.
137+ */
138+ const SERVE_ANCHOR = "server = Bun.serve<WsData>({ ...serveOptions, port: listenPort, hostname: bindHost });" ;
139+ const ACTIVATION_ANCHOR = "if (labActivationRequired(config, labConfigDir)) {" ;
140+ /**
141+ * The window ends at the RETURN, not at the activation check.
142+ *
143+ * Stopping at the activation anchor left two blind spots: an `await` inside the
144+ * `if (labActivationRequired(...))` body, and one between activation and `return server`.
145+ * AGENTS.md and `080_activation_is_synchronous.md` both state the guarantee as covering
146+ * everything from `Bun.serve` to the return, so a guard that stopped earlier was narrower
147+ * than the invariant it claimed to hold. Found by an independent review of this guard.
148+ */
149+ const RETURN_ANCHOR = " return server;" ;
150+
151+ /**
152+ * Blank comments and string bodies, preserving offsets and line breaks so reported line
153+ * numbers stay usable.
154+ *
155+ * This is not decoration. The window contains two comments that say the word "await" —
156+ * `src/server/index.ts:1853` ("this rollback cannot await") and `:1950` ("nowhere to
157+ * await") — so a naive text scan fails on correct code, and a guard that cries wolf on
158+ * `dev` gets deleted rather than fixed.
159+ *
160+ * Template interpolations are kept as code rather than blanked with the rest of the
161+ * template: `${await x()}` in a console.log is a real body-level await, and blanking the
162+ * whole template would hide exactly the violation this looks for.
163+ */
164+ export function blankCommentsAndStrings ( source : string ) : string {
165+ const out : string [ ] = [ ] ;
166+ // A stack, because a template interpolation can contain another template.
167+ const modes : Array < "code" | "template" > = [ "code" ] ;
168+ const depths : number [ ] = [ 0 ] ;
169+ let i = 0 ;
170+ const keep = ( ch : string ) => out . push ( ch === "\n" ? "\n" : " " ) ;
171+ while ( i < source . length ) {
172+ const ch = source [ i ] ! ;
173+ const next = source [ i + 1 ] ;
174+ if ( modes [ modes . length - 1 ] === "template" ) {
175+ if ( ch === "\\" ) { keep ( ch ) ; keep ( next ?? " " ) ; i += 2 ; continue ; }
176+ if ( ch === "`" ) { modes . pop ( ) ; depths . pop ( ) ; keep ( ch ) ; i ++ ; continue ; }
177+ if ( ch === "$" && next === "{" ) {
178+ modes . push ( "code" ) ;
179+ depths . push ( 0 ) ;
180+ keep ( ch ) ; keep ( next ) ; i += 2 ; continue ;
181+ }
182+ keep ( ch ) ; i ++ ; continue ;
183+ }
184+ if ( ch === "/" && next === "/" ) {
185+ while ( i < source . length && source [ i ] !== "\n" ) { keep ( source [ i ] ! ) ; i ++ ; }
186+ continue ;
187+ }
188+ if ( ch === "/" && next === "*" ) {
189+ keep ( ch ) ; keep ( next ) ; i += 2 ;
190+ while ( i < source . length && ! ( source [ i ] === "*" && source [ i + 1 ] === "/" ) ) { keep ( source [ i ] ! ) ; i ++ ; }
191+ if ( i < source . length ) { keep ( "*" ) ; keep ( "/" ) ; i += 2 ; }
192+ continue ;
193+ }
194+ if ( ch === "\"" || ch === "'" ) {
195+ keep ( ch ) ; i ++ ;
196+ while ( i < source . length ) {
197+ if ( source [ i ] === "\\" ) { keep ( source [ i ] ! ) ; keep ( source [ i + 1 ] ?? " " ) ; i += 2 ; continue ; }
198+ if ( source [ i ] === ch ) { keep ( source [ i ] ! ) ; i ++ ; break ; }
199+ keep ( source [ i ] ! ) ; i ++ ;
200+ }
201+ continue ;
202+ }
203+ if ( ch === "`" ) { modes . push ( "template" ) ; depths . push ( 0 ) ; keep ( ch ) ; i ++ ; continue ; }
204+ if ( ch === "{" ) { depths [ depths . length - 1 ] ! += 1 ; out . push ( ch ) ; i ++ ; continue ; }
205+ if ( ch === "}" ) {
206+ if ( depths [ depths . length - 1 ] === 0 && modes . length > 1 ) {
207+ // Closes a `${` interpolation, not a block.
208+ modes . pop ( ) ; depths . pop ( ) ; keep ( ch ) ; i ++ ; continue ;
209+ }
210+ depths [ depths . length - 1 ] ! -= 1 ;
211+ out . push ( ch ) ; i ++ ; continue ;
212+ }
213+ out . push ( ch ) ; i ++ ;
214+ }
215+ return out . join ( "" ) ;
216+ }
217+
218+ /**
219+ * True when the `{` at `braceIndex` opens a function body rather than a block or an object
220+ * literal. Brace depth alone cannot answer this: the window contains try/catch and an `if`,
221+ * and the three legitimate awaits sit inside the async arrow assigned to `server.stop`,
222+ * which runs at shutdown rather than during startup.
223+ */
224+ function opensFunctionBody ( code : string , braceIndex : number ) : boolean {
225+ let j = braceIndex - 1 ;
226+ while ( j >= 0 && / \s / . test ( code [ j ] ! ) ) j -- ;
227+ if ( j >= 1 && code [ j ] === ">" && code [ j - 1 ] === "=" ) return true ;
228+ if ( code [ j ] !== ")" ) return false ;
229+ let depth = 0 ;
230+ let k = j ;
231+ for ( ; k >= 0 ; k -- ) {
232+ if ( code [ k ] === ")" ) depth ++ ;
233+ else if ( code [ k ] === "(" ) { depth -- ; if ( depth === 0 ) break ; }
234+ }
235+ if ( k < 0 ) return false ;
236+ let m = k - 1 ;
237+ while ( m >= 0 && / \s / . test ( code [ m ] ! ) ) m -- ;
238+ const end = m + 1 ;
239+ while ( m >= 0 && / [ \w $ ] / . test ( code [ m ] ! ) ) m -- ;
240+ const token = code . slice ( m + 1 , end ) ;
241+ return ! [ "if" , "for" , "while" , "switch" , "catch" , "do" , "with" ] . includes ( token ) ;
242+ }
243+
244+ /**
245+ * 1-based line numbers (relative to `region`) of every `await` that would suspend
246+ * `startServer` itself. An await inside a nested function is fine — that code runs later.
247+ *
248+ * Stated limits: a computed member named `await`, and a regex literal containing the word,
249+ * are out of scope. Neither form is reachable in this window, and both would have to be
250+ * written deliberately.
251+ */
252+ export function bodyLevelAwaitLines ( region : string ) : number [ ] {
253+ const code = blankCommentsAndStrings ( region ) ;
254+ const hits : number [ ] = [ ] ;
255+ const stack : boolean [ ] = [ ] ;
256+ let line = 1 ;
257+ for ( let i = 0 ; i < code . length ; i ++ ) {
258+ const ch = code [ i ] ! ;
259+ if ( ch === "\n" ) { line ++ ; continue ; }
260+ if ( ch === "{" ) { stack . push ( opensFunctionBody ( code , i ) ) ; continue ; }
261+ if ( ch === "}" ) { stack . pop ( ) ; continue ; }
262+ if ( ch !== "a" || code . slice ( i , i + 5 ) !== "await" ) continue ;
263+ const before = i > 0 ? code [ i - 1 ] ! : " " ;
264+ const after = code [ i + 5 ] ?? " " ;
265+ if ( / [ \w $ ] / . test ( before ) || / [ \w $ ] / . test ( after ) ) continue ;
266+ // `.await` would be a property access, not the operator.
267+ if ( before === "." ) continue ;
268+ if ( ! stack . some ( isFunctionBody => isFunctionBody ) ) hits . push ( line ) ;
269+ i += 4 ;
270+ }
271+ return hits ;
272+ }
273+
122274describe ( "core / Compatibility Lab boundary" , ( ) => {
123275 // Guard 1: the obvious case, a direct import.
124276 test . each ( PROTECTED ) ( "%s has no direct src/lab import" , file => {
@@ -196,3 +348,87 @@ describe("boundary guard cannot be defeated", () => {
196348 }
197349 } ) ;
198350} ) ;
351+
352+ describe ( "activation window stays synchronous" , ( ) => {
353+ const indexPath = resolve ( repoRoot , "src/server/index.ts" ) ;
354+ const source = readFileSync ( indexPath , "utf8" ) ;
355+
356+ test ( "startServer is not async" , ( ) => {
357+ // An async startServer returns a Promise, so every caller treating the return value as a
358+ // live Server would break. The subtler cost is that it makes a body-level await legal,
359+ // which is the ordering this describe block exists to protect.
360+ // Assert on a boolean, not on `source`: a raw `expect(source)` failure prints the whole
361+ // 5000-line file and buries the finding it just made.
362+ const declaration = / e x p o r t \s + ( a s y n c \s + ) ? f u n c t i o n \s + s t a r t S e r v e r \s * \( / . exec ( source ) ;
363+ expect ( declaration ?. [ 0 ] ?? "startServer declaration not found" ) . toBe (
364+ "export function startServer(" ,
365+ ) ;
366+ } ) ;
367+
368+ test ( "no body-level await sits between Bun.serve and Lab activation" , ( ) => {
369+ const start = source . indexOf ( SERVE_ANCHOR ) ;
370+ const end = source . indexOf ( RETURN_ANCHOR , start ) ;
371+ const activation = source . indexOf ( ACTIVATION_ANCHOR ) ;
372+
373+ // Fail loudly if any anchor moves. A window that silently collapses to nothing is the
374+ // way this guard would rot into a test that passes by measuring an empty string.
375+ expect ( start ) . toBeGreaterThan ( - 1 ) ;
376+ expect ( end ) . toBeGreaterThan ( start ) ;
377+
378+ // The activation check must sit INSIDE the window. If it drifted out, the scan would
379+ // still be green while no longer covering the ordering it exists to protect.
380+ expect ( activation ) . toBeGreaterThan ( start ) ;
381+ expect ( activation ) . toBeLessThan ( end ) ;
382+
383+ const region = source . slice ( start , end ) ;
384+ const offsetLine = source . slice ( 0 , start ) . split ( "\n" ) . length ;
385+ const absolute = bodyLevelAwaitLines ( region ) . map ( relative => offsetLine + relative - 1 ) ;
386+
387+ expect ( absolute ) . toEqual ( [ ] ) ;
388+ } ) ;
389+
390+ test ( "the scan ignores comments, strings, and nested functions but catches a real await" , ( ) => {
391+ // Guard-on-the-guard. The window really does contain the word "await" twice in prose
392+ // (src/server/index.ts:1853 and :1950) and three real awaits inside the server.stop
393+ // closure, so a scan that cannot tell those apart either fails on correct code or
394+ // passes on broken code. Both directions are pinned here.
395+ expect ( bodyLevelAwaitLines ( "// cannot await here\nvoid 0;\n" ) ) . toEqual ( [ ] ) ;
396+ expect ( bodyLevelAwaitLines ( "/* nowhere to await */\nvoid 0;\n" ) ) . toEqual ( [ ] ) ;
397+ expect ( bodyLevelAwaitLines ( "const s = \"await x\";\n" ) ) . toEqual ( [ ] ) ;
398+ expect ( bodyLevelAwaitLines ( "const t = `await ${y}`;\n" ) ) . toEqual ( [ ] ) ;
399+
400+ // Inside a later-running function: allowed, exactly like the server.stop closure.
401+ expect ( bodyLevelAwaitLines ( "value: async () => {\n await stop();\n},\n" ) ) . toEqual ( [ ] ) ;
402+ expect ( bodyLevelAwaitLines ( "f(async () => {\n await g();\n});\n" ) ) . toEqual ( [ ] ) ;
403+
404+ // Blocks are not function bodies, so an await inside if/try/for still suspends the
405+ // enclosing function and must be reported.
406+ expect ( bodyLevelAwaitLines ( "await first();\n" ) ) . toEqual ( [ 1 ] ) ;
407+ expect ( bodyLevelAwaitLines ( "if (flag) {\n await gate();\n}\n" ) ) . toEqual ( [ 2 ] ) ;
408+ const emptyCatch = `catch ${ "{" } ${ "}" } ` ;
409+ expect ( bodyLevelAwaitLines ( `try {\n await risky();\n} ${ emptyCatch } \n` ) ) . toEqual ( [ 2 ] ) ;
410+ expect ( bodyLevelAwaitLines ( "for (const x of xs) {\n await x;\n}\n" ) ) . toEqual ( [ 2 ] ) ;
411+ expect ( bodyLevelAwaitLines ( "for await (const x of xs) {\n void x;\n}\n" ) ) . toEqual ( [ 1 ] ) ;
412+
413+ // A template interpolation is code, not string body.
414+ expect ( bodyLevelAwaitLines ( "console.log(`${await port()}`);\n" ) ) . toEqual ( [ 1 ] ) ;
415+
416+ // Identifiers that merely contain the word are not the operator.
417+ expect ( bodyLevelAwaitLines ( "const awaited = 1;\nvoid awaited;\n" ) ) . toEqual ( [ ] ) ;
418+ expect ( bodyLevelAwaitLines ( "thing.await();\n" ) ) . toEqual ( [ ] ) ;
419+ } ) ;
420+
421+ test ( "the real window contains the awaits it is supposed to tolerate" , ( ) => {
422+ // If the server.stop closure were ever moved out of the window, the tolerance branch
423+ // above would stop being exercised by real code and this suite would quietly narrow to
424+ // synthetic strings only.
425+ const start = source . indexOf ( SERVE_ANCHOR ) ;
426+ const end = source . indexOf ( RETURN_ANCHOR , start ) ;
427+ const region = source . slice ( start , end ) ;
428+
429+ expect ( region . includes ( "await runListenerShutdown(" ) ) . toBe ( true ) ;
430+ expect ( region . includes ( "await backgroundLifecycle.release();" ) ) . toBe ( true ) ;
431+ expect ( bodyLevelAwaitLines ( region ) ) . toEqual ( [ ] ) ;
432+ } ) ;
433+ } ) ;
434+
0 commit comments