@@ -46,6 +46,7 @@ type DiagnosticsScope = DiagnosticsScopeOptions & {
4646 // events are streamed out and reset mid-flight.
4747 phaseCounts : Map < string , number > ;
4848 sensitiveValues : Set < string > ;
49+ ensuredDirectories : Set < string > ;
4950 // Sorted-longest-first view of `sensitiveValues`, recomputed lazily after a
5051 // registration invalidates it so replacement order stays deterministic.
5152 sortedSensitiveValues ?: string [ ] ;
@@ -72,6 +73,7 @@ export async function withDiagnosticsScope<T>(
7273 liveWrittenEventCount : 0 ,
7374 phaseCounts : new Map ( ) ,
7475 sensitiveValues : new Set ( ) ,
76+ ensuredDirectories : new Set ( ) ,
7577 } ;
7678 return await diagnosticsStorage . run ( scope , fn ) ;
7779}
@@ -145,11 +147,11 @@ export function emitDiagnostic(event: {
145147 const fileLine = `${ JSON . stringify ( payload ) } \n` ;
146148 try {
147149 if ( scope . debug && scope . logPath ) {
148- appendDiagnosticLine ( scope . logPath , fileLine ) ;
150+ appendDiagnosticLine ( scope , scope . logPath , fileLine ) ;
149151 scope . liveWrittenEventCount = scope . events . length ;
150152 }
151153 if ( scope . traceLogPath ) {
152- appendDiagnosticLine ( scope . traceLogPath , fileLine ) ;
154+ appendDiagnosticLine ( scope , scope . traceLogPath , fileLine ) ;
153155 }
154156 if ( scope . debug && ! scope . logPath && ! scope . traceLogPath ) {
155157 process . stderr . write ( `[agent-device][diag] ${ fileLine } ` ) ;
@@ -221,7 +223,7 @@ export function flushDiagnosticsToSessionFile(
221223 const lines = pendingEvents . map ( ( entry ) =>
222224 JSON . stringify ( replaceSensitiveValues ( entry , values ) ) ,
223225 ) ;
224- appendDiagnosticLine ( scope . logPath , `${ lines . join ( '\n' ) } \n` ) ;
226+ appendDiagnosticLine ( scope , scope . logPath , `${ lines . join ( '\n' ) } \n` ) ;
225227 }
226228 const logRecord = scope . logRecord ;
227229 scope . events = [ ] ;
@@ -283,14 +285,11 @@ function sanitizePathPart(value: string): string {
283285 return value . replace ( / [ ^ a - z A - Z 0 - 9 . _ - ] / g, '_' ) ;
284286}
285287
286- // Directories already ensured by appendDiagnosticLine; debug mode would mkdir per line otherwise.
287- const ensuredDiagnosticDirs = new Set < string > ( ) ;
288-
289- function appendDiagnosticLine ( logPath : string , line : string ) : void {
288+ function appendDiagnosticLine ( scope : DiagnosticsScope , logPath : string , line : string ) : void {
290289 const dir = path . dirname ( logPath ) ;
291- if ( ! ensuredDiagnosticDirs . has ( dir ) ) {
290+ if ( ! scope . ensuredDirectories . has ( dir ) ) {
292291 fs . mkdirSync ( dir , { recursive : true } ) ;
293- ensuredDiagnosticDirs . add ( dir ) ;
292+ scope . ensuredDirectories . add ( dir ) ;
294293 }
295294 fs . appendFileSync ( logPath , line , 'utf8' ) ;
296295}
0 commit comments