Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

6.6 KB
Raw Blame
import 'error_burst_filter.dart';
import 'log_file.dart';

/// Severity of an [AppLog] event, in ascending order.
enum AppLogLevel { debug, info, warn, error }

/// The app's own diagnostic logger — a durable, human-readable timeline written
/// to `~/.harness/logs/app-YYYYMMDD.log`.
///
/// Ported from Grid, with one change: Riverpod out, a singleton in. The call
/// sites here are `main`, `AppNotifier`, `WsConn` and the CLI runner, and most
/// were never handed a `Ref`.
///
/// **Distinct from [CrashLog], and both are kept.** `CrashLog` answers "what
/// threw", in one file, forever, with a full stack; this answers "what was the
/// app *doing*", per day, pruned after two weeks. A crash whose stack names a
/// line still needs the ten lines before it to be explicable — that is what this
/// is for. `installFileLogs` wires errors into both.
///
/// [category] is a short, stable tag grouping related events — `app`
/// (lifecycle), `ws` (the socket this app lives on), `cli`, `api`, `flutter` —
/// so the timeline can be skimmed or filtered by concern.
abstract interface class AppLog {
  /// Append one structured event. [error]/[stackTrace] are included when present
  /// (the stack trace is indented on following lines).
  void record(
    AppLogLevel level,
    String category,
    String message, {
    Object? error,
    StackTrace? stackTrace,
  });
}

/// File-backed sinks expose their pending diagnostics without requiring
/// in-memory sinks or test recorders to manage a buffer.
abstract interface class FlushableAppLog implements AppLog {
  /// Writes what is pending; [durable] also fsyncs what is already written.
  void flush({bool durable = false});
}

/// [durable] is for quit and the updater's handoff, the last chance before
/// the process goes: on the UI isolate an fsync can take hundreds of
/// milliseconds on Linux, so export and backgrounding (every focus change on
/// a desktop) only write.
void flushAppLog({bool durable = false}) {
  final sink = appLog;
  if (sink is FlushableAppLog) sink.flush(durable: durable);
}

/// Level-named conveniences over [AppLog.record], kept as extensions so every
/// [AppLog] implementation gets them for free without re-declaring the surface.
extension AppLogX on AppLog {
  void debug(String category, String message) =>
      record(AppLogLevel.debug, category, message);

  void info(String category, String message) =>
      record(AppLogLevel.info, category, message);

  void warn(String category, String message, {Object? error}) =>
      record(AppLogLevel.warn, category, message, error: error);

  void failure(
    String category,
    String message, {
    Object? error,
    StackTrace? stackTrace,
  }) => record(
    AppLogLevel.error,
    category,
    message,
    error: error,
    stackTrace: stackTrace,
  );
}

/// [AppLog] backed by a per-day file under `~/.harness/logs`. Writes are
/// synchronous except when [bufferDebug] is enabled for routine debug
/// entries; INFO and WARN also write the pending context. Only an admitted
/// ERROR (a crash included) is fsynced with it, since an fsync on the UI
/// isolate can stall a frame for hundreds of milliseconds on Linux (see
/// `appendLog`); a killed process still loses none of what was written.
class FileAppLog implements FlushableAppLog {
  FileAppLog(
    this._file, {
    this.bufferDebug = false,
    ErrorBurstFilter? burst,
    DateTime Function()? clock,
  }) : _burst = burst ?? ErrorBurstFilter(),
       _clock = clock ?? DateTime.now;

  final DailyLogFile _file;
  final bool bufferDebug;

  @override
  void flush({bool durable = false}) => _file.flush(durable: durable);

  /// Injected so the stamp this writes is a thing a test can assert, rather than
  /// a thing a test has to watch happen. Same reason [ErrorBurstFilter] takes one.
  final DateTime Function() _clock;

  /// Applied to ERROR only. An exception thrown from `build` or a frame callback
  /// repeats every frame, and each copy costs an fsync on the UI isolate — which
  /// is how a glitch becomes a hang. Lower levels are things this app chose to
  /// say once, so they are not filtered.
  final ErrorBurstFilter _burst;

  @override
  void record(
    AppLogLevel level,
    String category,
    String message, {
    Object? error,
    StackTrace? stackTrace,
  }) {
    // The body is built WITHOUT the timestamp, and the stamp is put on last.
    // ErrorBurstFilter signs an error by its first line, so handing it a stamped
    // line would make every copy a different error the moment the clock ticked —
    // suppression would work inside one second and never report a count.
    final body = StringBuffer(
      '${_levelTag(level)} ${_categoryTag(category)} $message',
    );
    if (error != null) body.write('  err=$error');

    if (level != AppLogLevel.error) {
      final buffered = bufferDebug && level == AppLogLevel.debug;
      _file.append('[${logStamp(_clock())}] $body', buffered: buffered);
      _appendStack(stackTrace, buffered: buffered);
      return;
    }
    // A suppressed per-frame error must not turn interleaved debug traffic
    // back into a per-frame fsync. Its context keeps the normal batch deadline.
    final admitted = _burst.admit(body.toString());
    if (admitted == null) return;
    final line = '[${logStamp(_clock())}] $admitted';
    // The line and its stack in one durable write: one fsync, not two.
    _file.append(
      stackTrace == null ? line : '$line\n${_stackBlock(stackTrace)}',
      durable: true,
    );
  }

  void _appendStack(StackTrace? stackTrace, {bool buffered = false}) {
    if (stackTrace == null) return;
    _file.append(_stackBlock(stackTrace), buffered: buffered);
  }

  static String _stackBlock(StackTrace stackTrace) => stackTrace
      .toString()
      .trimRight()
      .split('\n')
      .map((l) => '    $l')
      .join('\n');

  /// Five-wide upper-case level so message columns line up.
  static String _levelTag(AppLogLevel level) => switch (level) {
    AppLogLevel.debug => 'DEBUG',
    AppLogLevel.info => 'INFO ',
    AppLogLevel.warn => 'WARN ',
    AppLogLevel.error => 'ERROR',
  };

  /// Pad short categories to a common width for a readable second column.
  static String _categoryTag(String category) =>
      category.length >= 7 ? category : category.padRight(7);
}

/// No-op [AppLog]. The default, so a `flutter test` run never writes into a real
/// `~/.harness`.
class NoopAppLog implements AppLog {
  const NoopAppLog();

  @override
  void record(
    AppLogLevel level,
    String category,
    String message, {
    Object? error,
    StackTrace? stackTrace,
  }) {}
}

/// The app-log sink. Muted until [installFileLogs] swaps in the file sink.
AppLog appLog = const NoopAppLog();