flushDiagnosticsToSessionFile function
Flushes accumulated diagnostic events to a session-specific log file.
Returns the file path if events were written, null otherwise.
By default, only writes if the scope has DiagnosticsScopeOptions.debug
enabled; pass force = true to override.
Implementation
String? flushDiagnosticsToSessionFile({bool force = false}) {
final scope = _getCurrentScope();
if (scope == null) return null;
if (!force && !scope.debug) return null;
if (scope.events.isEmpty) return null;
try {
final sessionDir = _sanitizePathPart(scope.session ?? 'default');
final dayDir = DateTime.now().toUtc().toString().substring(0, 10);
final homeDir = Platform.environment['HOME'] ?? '';
final baseDir = p.join(
homeDir,
'.agent-device',
'logs',
sessionDir,
dayDir,
);
Directory(baseDir).createSync(recursive: true);
final timestamp = DateTime.now().toUtc().toIso8601String().replaceAll(
RegExp(r'[:.Z]'),
'-',
);
final filePath = p.join(baseDir, '$timestamp-${scope.diagnosticId}.ndjson');
final lines = scope.events
.map((event) => jsonEncode(redactDiagnosticData(event.toJson())))
.toList();
File(filePath).writeAsStringSync('${lines.join('\n')}\n');
scope.events.clear();
return filePath;
} catch (_) {
return null;
}
}