gitSafety static method

ToolLifecycle gitSafety({
  1. List<String> protectedBranches = const ['main', 'master'],
  2. void onWarning(
    1. String warning
    )?,
})

Git safety lifecycle hooks.

Checks for destructive git operations in bash commands and warns or blocks them.

Implementation

static ToolLifecycle gitSafety({
  List<String> protectedBranches = const ['main', 'master'],
  void Function(String warning)? onWarning,
}) {
  final destructivePatterns = <RegExp>[
    RegExp(r'\bgit\s+push\s+.*--force\b'),
    RegExp(r'\bgit\s+push\s+-f\b'),
    RegExp(r'\bgit\s+reset\s+--hard\b'),
    RegExp(r'\bgit\s+clean\s+.*-f'),
    RegExp(r'\bgit\s+checkout\s+--\s+\.'),
    RegExp(r'\bgit\s+branch\s+(-d|-D)\s+'),
  ];

  return ToolLifecycle(
    onToolBeforeExecution: (event) async {
      if (event.toolName.toLowerCase() != 'bash') return null;

      final command = event.input['command'] as String? ?? '';

      for (final pattern in destructivePatterns) {
        if (pattern.hasMatch(command)) {
          // Check if targeting protected branch.
          for (final branch in protectedBranches) {
            if (command.contains(branch)) {
              onWarning?.call(
                'Destructive git operation targeting protected '
                'branch "$branch": $command',
              );
              // Return empty map to signal interception without modifying.
              return null;
            }
          }
          onWarning?.call('Destructive git operation detected: $command');
        }
      }
      return null;
    },
  );
}