diff --git a/README.md b/README.md index 88634b7..a1f91c0 100644 --- a/README.md +++ b/README.md @@ -225,17 +225,15 @@ Linked Git working folders appear under the same project. Filter by activity, se chat name, and open the matching conversation. Recent shows up to 20 chats. **Usage profiles** shows the last observed limits and their time for the default Claude profile and configured Codex folders. -In **Settings… → Git Protection**, select the client and profile, then click **Install Git Hook**. -In Codex desktop, open **Settings → Hooks** and click **Trust**. In the terminal, use `/hooks`. -Start a new chat in each client. Install the -hook before updating from a Mothership version that provides Git protection. Keep Agent Watch -at the same path when updating. Both clients continue using the existing project rules. - -Choose a Git working folder and enter a branch name. You can -require the repository name before deleting that branch on the remote, or remove a rule saved -directly in that repository. The change applies to its linked working folders. The installed -Git guard enforces the rule. If the outcome depends on the remote’s default branch, the preview -explains both possibilities. +In **Settings… → Git Protection**, check the hook status beside each Claude Code or Codex +profile. Click **Install…** to connect a profile or **Repair…** to fix an outdated hook. +In Codex, approve the hook in **Settings → Hooks** or `/hooks`, then open a new chat. Keep +Agent Watch at the same path when updating. + +**Protect Git commands** turns checks on or off for all connected profiles. Turning them off +requires confirmation and keeps the hooks and rules. Under **Branch rules**, select **Push**, +**Force Push**, or **Delete Remote Branch**. A repository can require a stricter check than +the shared rule. Use **Preview a Branch** to see which check applies. In **Settings… → Working Copies**, scan a repository to see its working copies, largest first. Expand a copy to see local changes, build folders and what Agent Watch can safely move to the @@ -258,7 +256,7 @@ Details: [installing into the agents](docs/agent-install.md), [architecture](doc ## Uninstall -1. In **Settings… → Git Protection**, use **Remove Git Hook…** for each protected profile. +1. In **Settings… → Git Protection**, use **Remove…** beside each installed profile. In **Settings… → Tooling**, press **Remove** for each agent, **Forget Folder** for every folder you added. If you connected the old Claude status-line relay, restore your command before moving the support folder to the Trash. [Restore the status-line command](TROUBLESHOOTING.md#claude-still-runs-the-agent-watch-status-line-relay). diff --git a/Sources/AgentWatchApp/GitBranchTypesSection.swift b/Sources/AgentWatchApp/GitBranchTypesSection.swift deleted file mode 100644 index c754cb0..0000000 --- a/Sources/AgentWatchApp/GitBranchTypesSection.swift +++ /dev/null @@ -1,115 +0,0 @@ -import AgentWatchGit -import SwiftUI - -/// The table of branch types and the rows no type can lower. -struct GitBranchTypesSection: View { - @Binding var table: GitBranchTypes - let error: String? - - var body: some View { - Section("Branch types") { - Footnote( - "The first type whose pattern matches a branch decides how a force push or a remote deletion of it is checked, in every repository. * matches any characters, / included." - ) - ForEach($table.types) { $type in - GitBranchTypeRow( - type: $type, - canMoveUp: type.id != table.types.first?.id, - canMoveDown: type.id != table.types.last?.id, - move: { offset in move(type.id, by: offset) }, - remove: { table.types.removeAll { $0.id == type.id } }) - } - Button("Add Type") { - table.types.append(GitBranchType(name: "New type", patterns: [], level: .click)) - } - if let error { Text(error).foregroundStyle(.red) } - // Fixed rows stay visible, greyed, with the reason beside them. - LabeledContent("main, master, the remote’s default branch, tags") { - Text("At least \(GitCheckLevel.name.title)") - } - .foregroundStyle(.secondary) - LabeledContent("Branches without a type") { - Text("Delete: \(GitCheckLevel.click.title) · Force push: \(GitCheckLevel.name.title)") - } - .foregroundStyle(.secondary) - Footnote( - "No type lowers the first row, nor a branch a repository marks with Require Repository Name: an agent can edit any settings file, so these are the checks it cannot remove." - ) - } - } - - private func move(_ id: UUID, by offset: Int) { - guard let index = table.types.firstIndex(where: { $0.id == id }), - table.types.indices.contains(index + offset) - else { return } - table.types.swapAt(index, index + offset) - } -} - -private struct GitBranchTypeRow: View { - @Binding var type: GitBranchType - let canMoveUp: Bool - let canMoveDown: Bool - let move: (Int) -> Void - let remove: () -> Void - // Kept apart from the patterns so a space typed between two of them is not split away. - @State private var patterns = "" - - var body: some View { - VStack(alignment: .leading) { - HStack { - TextField("Name", text: $type.name) - Picker("Check", selection: $type.level) { - ForEach(GitCheckLevel.allCases, id: \.self) { level in - Text(level.title).tag(level) - } - } - .labelsHidden() - .fixedSize() - Button { - move(-1) - } label: { - Image(systemName: "chevron.up") - } - .disabled(!canMoveUp) - .help("Check this type earlier") - Button { - move(1) - } label: { - Image(systemName: "chevron.down") - } - .disabled(!canMoveDown) - .help("Check this type later") - Button(role: .destructive, action: remove) { Image(systemName: "trash") } - .help("Remove this type") - } - .buttonStyle(.borderless) - TextField("Patterns", text: $patterns, prompt: Text("feature/* fix/*")) - Text(type.level.explanation).font(.caption).foregroundStyle(.secondary) - } - .onAppear { patterns = type.patterns.joined(separator: " ") } - .onChange(of: patterns) { - type.patterns = patterns.split(whereSeparator: \.isWhitespace).map(String.init) - } - } -} - -extension GitCheckLevel { - var title: String { - switch self { - case .none: "No Window" - case .click: "Click" - case .name: "Click + Name" - case .forbid: "Forbid" - } - } - - var explanation: String { - switch self { - case .none: "The agent’s own force push or deletion goes through without asking." - case .click: "One confirmation window." - case .name: "A confirmation, then the repository name typed in." - case .forbid: "Always refused; run the command from a terminal yourself." - } - } -} diff --git a/Sources/AgentWatchApp/GitHookInstaller.swift b/Sources/AgentWatchApp/GitHookInstaller.swift index 3a67e3a..9725bd5 100644 --- a/Sources/AgentWatchApp/GitHookInstaller.swift +++ b/Sources/AgentWatchApp/GitHookInstaller.swift @@ -85,6 +85,9 @@ struct GitHookInstaller { try FileManager.default.createDirectory( at: profile, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) } + // Status is a snapshot of an atomically replaced file. Concurrent status reads + // for Claude and Codex can share a profile directory without taking the write lock. + if action == .status { return try edit(action, source: source, url: url) } let lock = try AgentProfileLock(profile) defer { withExtendedLifetime(lock) {} } return try edit(action, source: source, url: url) diff --git a/Sources/AgentWatchApp/GitProtectionPane.swift b/Sources/AgentWatchApp/GitProtectionPane.swift index 9fc3665..fbe0459 100644 --- a/Sources/AgentWatchApp/GitProtectionPane.swift +++ b/Sources/AgentWatchApp/GitProtectionPane.swift @@ -5,158 +5,384 @@ import UniformTypeIdentifiers struct GitProtectionPane: View { let profiles: AgentFolders - @State private var folder: URL? - @State private var branch = "release" + var rulesURL = AgentWatchPaths.supportDirectory()?.appendingPathComponent(GitProtectionRules.fileName) + + private enum Scope: Hashable { case all, repository } + private enum FolderUse { case rules, preview } + private struct PreviewRequest: Equatable { + let repository: GitProtectionRepository? + let branch: String + } + private struct EditorSelection: Identifiable { + let id = UUID() + let operation: GitBranchOperation + let repository: GitProtectionRepository? + let rule: GitBranchType? + let index: Int? + let count: Int + } + + @State private var rules: GitProtectionRules? + @State private var settingsError: String? + @State private var confirmsDisable = false + @State private var operation = GitBranchOperation.delete + @State private var scope = Scope.all + @State private var rulesRepository: GitProtectionRepository? + @State private var previewRepository: GitProtectionRepository? + @State private var folderError: String? @State private var choosingFolder = false - @State private var reading = false - @State private var previewTask: Task? - @State private var confirmingRemoval = false + @State private var folderUse = FolderUse.rules + @State private var readingFolder = false + @State private var branch = "" @State private var preview: GitDeletionPreview? - @State private var errorMessage: String? - @State private var table = GitBranchTypes() - /// What the file holds, so opening the page does not write it back. - @State private var savedTable: GitBranchTypes? - @State private var tableError: String? + @State private var previewError: String? + @State private var readingPreview = false + @State private var confirmsLegacyRemoval = false + @State private var editor: EditorSelection? - /// Where `AgentWatchGit` reads the table: `~/Library/Application Support/AgentWatch`. - private var tableURL: URL? { - AgentWatchPaths.supportDirectory()?.appendingPathComponent(GitBranchTypes.fileName) + private var enabled: Bool { rules?.enabled ?? true } + private var activeRepository: GitProtectionRepository? { scope == .repository ? rulesRepository : nil } + private var currentRules: [GitBranchType] { + if scope == .repository { + guard let key = activeRepository?.key else { return [] } + return rules?.repositories[key]?[operation] ?? [] + } + return rules?.global[operation] ?? [] + } + private var canAddRule: Bool { + rules != nil && operation != .push && (scope == .all || activeRepository != nil) } + private var previewRequest: PreviewRequest { PreviewRequest(repository: previewRepository, branch: branch) } + var body: some View { - Form { - GitProtectionProfiles(folders: profiles) - GitBranchTypesSection(table: $table, error: tableError) - Section("Remote branch deletion") { - LabeledContent("Repository") { - Button(folder?.path ?? "Choose Folder…") { choosingFolder = true } + ScrollViewReader { proxy in + Form { + protectionSwitch + GitProtectionProfiles(folders: profiles) + branchRules { withAnimation { proxy.scrollTo("branch-preview", anchor: .top) } } + branchPreview.id("branch-preview") + } + } + .task { loadRules() } + .task(id: previewRequest) { await readPreview(previewRequest) } + .onChange(of: operation) { if operation == .push { scope = .all } } + .fileImporter(isPresented: $choosingFolder, allowedContentTypes: [.folder], onCompletion: acceptFolder) + .sheet(item: $editor) { selection in + GitProtectionRuleEditor( + operation: selection.operation, + repository: selection.repository, + rule: selection.rule, + canMoveEarlier: (selection.index ?? 0) > 0, + canMoveLater: selection.index.map { $0 + 1 < selection.count } ?? false, + change: { try edit(selection, change: $0) } + ) + } + .alert("Turn off Git Protection?", isPresented: $confirmsDisable) { + Button("Cancel", role: .cancel) {}.keyboardShortcut(.defaultAction) + Button("Turn Off Protection", role: .destructive) { setEnabled(false) } + } message: { + Text( + "Agent Watch will stop checking Git commands in all connected profiles. Agents can push to protected branches, rewrite history, or delete remote branches without an Agent Watch confirmation. Your hooks and rules are saved." + ) + } + .alert("Remove this repository’s existing protection for this branch?", isPresented: $confirmsLegacyRemoval) { + Button("Cancel", role: .cancel) {} + Button("Remove Rule", role: .destructive) { removeLegacyRule() } + } message: { + Text("Other rules and the remote’s default branch can still require the repository name.") + } + } + + private var protectionSwitch: some View { + Section { + Toggle( + isOn: Binding( + get: { enabled }, + set: { value in + if value { setEnabled(true) } else { confirmsDisable = true } + }) + ) { + Label { + Heading( + title: "Protect Git commands", + hint: enabled + ? "Checks Git commands from connected agent profiles." + : "Protection is off for all profiles. Hooks and rules are saved.") + } icon: { + Image(systemName: enabled ? "checkmark.shield" : "shield.slash") + .foregroundStyle(enabled ? Color.accentColor : Color.secondary) } - TextField("Branch", text: $branch) - Button(reading ? "Reading…" : "Preview Confirmation") { - guard let folder else { return } - load(folder: folder, branch: branch) + } + .toggleStyle(.switch) + .disabled(rules == nil) + if let settingsError { + Text(settingsError).font(.caption).foregroundStyle(.red) + } + } + } + + private func branchRules(openPreview: @escaping () -> Void) -> some View { + Section { + Picker("Git operation", selection: $operation) { + ForEach(GitBranchOperation.allCases) { operation in + Text(operation.title).tag(operation) } - .disabled(folder == nil || branch.isEmpty) } - .disabled(reading) - if let errorMessage { - Text(errorMessage).foregroundStyle(.red) - } else if let preview { - Section("Confirmation for this branch") { - Text(summary(of: preview)) - switch preview { - case .builtIn: - Text("This branch has built-in protection.") - case .projectRule: - Text("This repository lists the branch as protected.") - Button("Remove Project Rule…") { confirmingRemoval = true } - case .includedRule: - Text("This rule comes from an included Git configuration file.") - case .dependsOnRemote: - Button("Require Repository Name") { - if let folder { load(folder: folder, branch: branch, protected: true) } - } + .pickerStyle(.segmented) + .labelsHidden() + + if operation != .push { + Picker("Rule scope", selection: $scope) { + Text("All repositories").tag(Scope.all) + Text("One repository…").tag(Scope.repository) + } + if scope == .repository { + LabeledContent("Repository") { + repositoryButton(rulesRepository, use: .rules) } + if let folderError, folderUse == .rules { errorText(folderError) } + } + } + LabeledContent { + Text(operation.defaultLevel.title) + } label: { + Heading(title: scope == .all ? "Default" : "Inherited default", hint: "Branches with no matching rule") + } + LabeledContent { + Text(GitCheckLevel.name.title) + } label: { + Heading( + title: "Protected branches", + hint: operation == .push + ? "main and master" + : "main, master, the remote’s default branch, and branches protected in Git") + } + ForEach(currentRules) { rule in + let patterns = rule.patterns.joined(separator: " ") + HStack { + Text(patterns) + .font(.system(.body, design: .monospaced)) + .lineLimit(2) + .help(patterns) + Spacer() + Text(rule.level.title) + .foregroundStyle(.secondary) + .fixedSize(horizontal: true, vertical: false) + Button("Edit…") { openEditor(for: rule) } + .accessibilityLabel("Edit rule for \(patterns)") + .disabled(rules == nil) + } + } + if operation != .push { + Button { + openEditor() + } label: { + Label("Add \(operation.ruleTitle)…", systemImage: "plus") } - .disabled(reading) + .disabled(!canAddRule) } + } header: { + HStack { + Text("Branch rules") + Spacer() + Button("Preview a Branch", systemImage: "arrow.down", action: openPreview) + .labelStyle(.titleAndIcon) + .buttonStyle(.borderless) + } + } footer: { Footnote( - "Edits apply to this repository and its linked working folders. The Git protection tool also checks the remote’s default branch when deletion is requested." + operation == .push + ? "These built-in checks apply to ordinary pushes. Git can also require confirmation when it cannot determine the destination from the command." + : scope == .all + ? "The first matching rule applies. Protected branches always require at least the check shown above." + : "The first matching repository rule can make the global check stricter. Linked working copies use the same rules." ) } - .fileImporter(isPresented: $choosingFolder, allowedContentTypes: [.folder]) { selection in - switch selection { - case .success(let url): - folder = url - clearResult() - case .failure(let error): - if (error as NSError).code != NSUserCancelledError { errorMessage = error.localizedDescription } + } + + private var branchPreview: some View { + Section("Preview a branch") { + LabeledContent("Repository") { + repositoryButton(previewRepository, use: .preview) + } + TextField("Branch", text: $branch, prompt: Text("release/2026.11")) + if !enabled { + Heading(title: "Protection is off", hint: "Agent Watch skips this check while Git Protection is off.") + } else if let folderError, folderUse == .preview { + errorText(folderError) + } else if let previewError { + errorText(previewError) + } else if readingPreview { + ProgressView().controlSize(.small) + } else if let preview { + let result = previewResult(preview) + Heading(title: result.level.title, hint: result.reason) + if operation != .push && preview == .projectRule { + Button("Remove Repository’s Existing Rule…", role: .destructive) { confirmsLegacyRemoval = true } + } + } else { + Footnote("Choose a repository and enter a branch name to preview \(operation.title).") } } - .confirmationDialog("Remove this project’s rule for “\(branch)”?", isPresented: $confirmingRemoval) { - Button("Remove Project Rule", role: .destructive) { - if let folder { load(folder: folder, branch: branch, protected: false) } + } + + private func previewResult(_ evidence: GitDeletionPreview) -> (level: GitCheckLevel, reason: String) { + let choice = (rules ?? GitProtectionRules()).level( + for: operation, branch: branch, repository: previewRepository?.key) + let protected = evidence == .builtIn || (operation != .push && evidence != .dependsOnRemote) + if protected && choice.level <= .name { + switch evidence { + case .builtIn: return (.name, "Built-in protection for \(branch).") + case .projectRule: return (.name, "This branch is protected in the repository’s Git configuration.") + case .includedRule: return (.name, "This branch is protected in an included Git configuration file.") + case .dependsOnRemote: break } - Button("Cancel", role: .cancel) {} - } message: { - Text( - "An included rule, built-in protection, or the remote’s default branch can still require the repository name." - ) } - .onChange(of: branch) { clearResult() } - .onAppear(perform: loadTable) - .onChange(of: table) { saveTable() } - .onDisappear { - previewTask?.cancel() - previewTask = nil - reading = false + var reason = choice.source.map { "Matches rule “\($0)”." } ?? "Uses the default for \(operation.title)." + if operation != .push && choice.level < .name { + reason += " If this is the remote’s default branch, the repository name is also required." } + return (choice.level, reason) } - private func summary(of preview: GitDeletionPreview) -> String { - let (level, type) = preview.deletionLevel(in: table, branch: branch) - let source = type.map { " (branch type “\($0)”)" } ?? "" - let text: String - switch level { - case .forbid: return "Deletion is refused without a window\(source). Run it from a terminal." - case .name: return "Confirm deletion, then enter the repository name\(source)." - case .click: text = "Confirm deletion once\(source)." - case .none: text = "No window: the agent’s deletion goes through\(source)." + private func repositoryButton(_ repository: GitProtectionRepository?, use: FolderUse) -> some View { + Button(repository?.folder.lastPathComponent ?? "Choose Folder…") { + folderUse = use + choosingFolder = true } - return text + " If this is the remote’s default branch, also confirm and enter the repository name." + .help(repository?.folder.path ?? "Choose a folder in a Git repository") + .disabled(readingFolder) } - private func loadTable() { - guard savedTable == nil, let url = tableURL else { return } - do { - table = try GitBranchTypes.load(from: url) - savedTable = table - } catch { - savedTable = GitBranchTypes() - tableError = - "\(url.path) could not be read (\(error.localizedDescription)). Until it is fixed, branches keep the checks they had without types; editing the table here replaces the file." - } + private func errorText(_ error: String) -> some View { + Text(error).font(.caption).foregroundStyle(.red) } - private func saveTable() { - guard let savedTable, savedTable != table, let url = tableURL else { return } - do { - try table.save(to: url) - self.savedTable = table - tableError = nil - } catch { - tableError = "The branch types could not be saved: \(error.localizedDescription)" + private func acceptFolder(_ selection: Result) { + switch selection { + case .success(let folder): + folderError = nil + readingFolder = true + let purpose = folderUse + Task { + let result = await Task.detached(priority: .userInitiated) { + Result { try GitProtectionRepository(folder: folder) } + }.value + readingFolder = false + switch result { + case .success(let repository): + if purpose == .rules { rulesRepository = repository } + previewRepository = repository + case .failure(let error): folderError = error.localizedDescription + } + } + case .failure(let error): + if (error as NSError).code != NSUserCancelledError { folderError = error.localizedDescription } } } - private func clearResult() { + private func readPreview(_ request: PreviewRequest) async { preview = nil - errorMessage = nil + previewError = nil + readingPreview = false + guard let repository = request.repository, !request.branch.isEmpty else { return } + readingPreview = true + do { + try await Task.sleep(for: .milliseconds(250)) + } catch { return } + let worker = Task.detached(priority: .userInitiated) { + try GitDeletionPreview.read(in: repository.folder, branch: request.branch) + } + let result = await withTaskCancellationHandler { + await worker.result + } onCancel: { + worker.cancel() + } + guard !Task.isCancelled else { return } + readingPreview = false + switch result { + case .success(let value): preview = value + case .failure(let error): previewError = error.localizedDescription + } } - private func load(folder: URL, branch: String, protected: Bool? = nil) { - clearResult() - reading = true - let worker = Task.detached(priority: .userInitiated) { - if let protected { - return try GitDeletionPreview.setProjectRule(in: folder, branch: branch, protected: protected) - } - return try GitDeletionPreview.read(in: folder, branch: branch) - } - previewTask = Task { - let result = await withTaskCancellationHandler { - await worker.result - } onCancel: { - // A confirmed edit can finish after the settings page closes. - if protected == nil { worker.cancel() } - } - guard !Task.isCancelled else { return } + private func removeLegacyRule() { + guard let repository = previewRepository else { return } + let request = previewRequest + Task { + let result = await Task.detached(priority: .userInitiated) { + Result { + try GitDeletionPreview.setProjectRule( + in: repository.folder, branch: request.branch, protected: false) + } + }.value + guard previewRequest == request else { return } switch result { case .success(let value): preview = value - case .failure(let error): errorMessage = error.localizedDescription + case .failure(let error): previewError = error.localizedDescription } - reading = false - previewTask = nil } } + + private func loadRules() { + do { + rules = try GitProtectionRules.load(from: settingsPath()) + settingsError = nil + } catch { + settingsError = "Could not read Git protection rules. Built-in checks apply. \(error.localizedDescription)" + } + } + + private func settingsPath() throws -> URL { + guard let rulesURL else { throw SettingsError.missingDirectory } + return rulesURL + } + + private func save(_ updated: GitProtectionRules) throws { + try updated.save(to: settingsPath()) + rules = updated + settingsError = nil + } + + private func setEnabled(_ value: Bool) { + guard var updated = rules else { return } + updated.enabled = value + do { try save(updated) } catch { + settingsError = "Could not change Git Protection. \(error.localizedDescription)" + } + } + + private func openEditor(for rule: GitBranchType? = nil) { + editor = EditorSelection( + operation: operation, repository: activeRepository, rule: rule, + index: rule.flatMap { rule in currentRules.firstIndex { $0.id == rule.id } }, count: currentRules.count) + } + + private func edit(_ selection: EditorSelection, change: GitProtectionRuleEditor.Change) throws { + guard var updated = rules else { throw SettingsError.missingDirectory } + let key = selection.repository?.key + var scoped = key.map { updated.repositories[$0] ?? GitProtectionRules.Rules() } ?? updated.global + var list = scoped[selection.operation] + switch change { + case .save(let rule): + if let index = selection.index { list[index] = rule } else { list.insert(rule, at: 0) } + case .move(let offset): + if let index = selection.index { list.swapAt(index, index + offset) } + case .remove: + if let index = selection.index { list.remove(at: index) } + } + scoped[selection.operation] = list + if let key { + updated.repositories[key] = scoped.forcePush.isEmpty && scoped.delete.isEmpty ? nil : scoped + } else { + updated.global = scoped + } + try save(updated) + } + + private enum SettingsError: LocalizedError { + case missingDirectory + var errorDescription: String? { "Agent Watch could not locate its Application Support folder." } + } } diff --git a/Sources/AgentWatchApp/GitProtectionProfiles.swift b/Sources/AgentWatchApp/GitProtectionProfiles.swift index ca21ac6..241b432 100644 --- a/Sources/AgentWatchApp/GitProtectionProfiles.swift +++ b/Sources/AgentWatchApp/GitProtectionProfiles.swift @@ -3,72 +3,117 @@ import SwiftUI struct GitProtectionProfiles: View { let folders: AgentFolders - @State private var source = AgentSource.claude - @State private var selected: URL? - @State private var state: GitHookInstaller.State? - @State private var error: String? - @State private var legacy: MothershipGitRegistration.State? - @State private var confirmRemoval = false - private var profile: URL { selected ?? folders.defaultFolder(for: source) } var body: some View { - Section("Protect Git commands") { - Picker("Client", selection: $source) { - Text("Claude").tag(AgentSource.claude) - Text("Codex").tag(AgentSource.codex) - }.pickerStyle(.segmented) - Picker("Profile", selection: Binding(get: { profile }, set: { selected = $0 })) { - ForEach(folders.folders(for: source), id: \.self) { path in - Text(path.path).tag(path) + Section("Agent profiles") { + ForEach(AgentSource.allCases, id: \.self) { source in + ForEach(folders.folders(for: source), id: \.self) { profile in + GitProtectionProfile( + source: source, profile: profile, + displayPath: folders.isDefault(profile, for: source) + ? "~/" + profile.lastPathComponent : profile.path + ) } } - if state == .registered { - Text("Git hook registered in this profile.") - Button("Remove Git Hook…") { confirmRemoval = true } - } else { - Button(state == .needsRepair ? "Repair Git Hook" : "Install Git Hook") { apply(.install) } - } - if let error { Text(error).foregroundStyle(.red) } - Footnote( - source == .codex - ? "In Codex desktop, open Settings → Hooks and click Trust for this PreToolUse hook. In the terminal, open /hooks. Start a new chat to use it." - : "Open a new Claude conversation to load the registered hook.") - if legacy == .registered { - Label( - "This profile still registers Git protection through Mothership.", - systemImage: "exclamationmark.triangle") - } - Footnote( - "Moving from Mothership? Register the Agent Watch hook first and review it in your client. Then update Mothership to the version without its Git hook and reopen the client." - ) } - .task(id: source.rawValue + profile.path) { - let source = source - let folder = profile - legacy = nil - let state = await Task.detached(priority: .utility) { - MothershipGitRegistration.check(source: source, profile: folder) - }.value - if !Task.isCancelled { legacy = state } + } +} + +private struct GitProtectionProfile: View { + let source: AgentSource + let profile: URL + let displayPath: String + @State private var state: GitHookInstaller.State? + @State private var errorMessage: String? + @State private var busy = false + @State private var confirmsRemoval = false + + private var client: String { source == .claude ? "Claude Code" : "Codex" } + + private var status: (title: String, color: Color) { + switch state { + case .registered: ("Installed", .green) + case .needsRepair: ("Needs repair", .orange) + case .absent: ("Not installed", .secondary) + case nil: (errorMessage == nil ? "Checking…" : "Status unavailable", .secondary) } - .onAppear { apply(.status) } - .onChange(of: source) { - selected = nil - apply(.status) + } + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + HStack(spacing: 12) { + VStack(alignment: .leading, spacing: 2) { + Text(client) + Text(displayPath).font(.caption).foregroundStyle(.secondary) + .truncationMode(.middle).lineLimit(1).help(profile.path) + } + Spacer(minLength: 4) + Label { + Text(status.title).fixedSize() + } icon: { + Circle().fill(status.color).frame(width: 6, height: 6) + } + .foregroundStyle(.secondary) + .font(.caption) + .accessibilityLabel(status.title) + switch state { + case .registered: + Button("Remove…") { confirmsRemoval = true } + case .needsRepair: + Button("Repair…") { start(.install) } + case .absent: + Button("Install…") { start(.install) } + case nil: + if errorMessage != nil { + Button("Retry") { start(.status) } + } else { + ProgressView().controlSize(.small).accessibilityHidden(true) + } + } + } + .disabled(busy) + if let errorMessage { + Text(errorMessage).font(.caption).foregroundStyle(.red) + } else if state == .registered { + Text( + source == .codex + ? "In Codex, review hook trust in Settings → Hooks or /hooks, then open a new chat." + : "Open a new Claude Code chat to load the installed hook." + ) + .font(.caption).foregroundStyle(.secondary) + } else if state == .needsRepair { + Text("Agent Watch found an outdated or customized Git hook in this profile.") + .font(.caption).foregroundStyle(.secondary) + } } - .onChange(of: selected) { apply(.status) } - .confirmationDialog("Remove Git protection from this profile?", isPresented: $confirmRemoval) { - Button("Remove Git Hook", role: .destructive) { apply(.remove) } + .task { await apply(.status) } + .alert("Remove Git hook?", isPresented: $confirmsRemoval) { + Button("Cancel", role: .cancel) {} + Button("Remove Hook", role: .destructive) { start(.remove) } + } message: { + Text("Commands from this \(client) profile will stop going through Agent Watch’s Git checks.") } } - private func apply(_ action: GitHookInstaller.Action) { - error = nil - do { - state = try GitHookInstaller(bundle: Bundle.main.bundleURL).apply(action, source: source, profile: profile) - } catch { - state = nil - self.error = error.localizedDescription + private func start(_ action: GitHookInstaller.Action) { + busy = true + Task { await apply(action) } + } + + private func apply(_ action: GitHookInstaller.Action) async { + let installer = GitHookInstaller(bundle: Bundle.main.bundleURL) + let result = await Task.detached(priority: .utility) { [source, profile] in + Result { try installer.apply(action, source: source, profile: profile) } + }.value + guard !Task.isCancelled else { return } + busy = false + switch result { + case .success(let state): + self.state = state + errorMessage = nil + case .failure(let error): + if action == .status { state = nil } + errorMessage = error.localizedDescription } } } diff --git a/Sources/AgentWatchApp/GitProtectionRuleEditor.swift b/Sources/AgentWatchApp/GitProtectionRuleEditor.swift new file mode 100644 index 0000000..abf4ec0 --- /dev/null +++ b/Sources/AgentWatchApp/GitProtectionRuleEditor.swift @@ -0,0 +1,124 @@ +import AgentWatchGit +import SwiftUI + +struct GitProtectionRuleEditor: View { + enum Change { + case save(GitBranchType) + case move(Int) + case remove + } + + let operation: GitBranchOperation + let repository: GitProtectionRepository? + let rule: GitBranchType? + let canMoveEarlier: Bool + let canMoveLater: Bool + let change: (Change) throws -> Void + @Environment(\.dismiss) private var dismiss + @State private var patterns = "" + @State private var level = GitCheckLevel.click + @State private var errorMessage: String? + @State private var confirmsRemoval = false + + private var patternList: [String] { patterns.split(whereSeparator: \.isWhitespace).map(String.init) } + private var choices: [GitCheckLevel] { repository == nil ? GitCheckLevel.allCases : [.click, .name, .forbid] } + + var body: some View { + VStack(alignment: .leading, spacing: 14) { + VStack(alignment: .leading, spacing: 4) { + Text((rule == nil ? "Add " : "Edit ") + operation.ruleTitle).font(.headline) + Text("\(repository?.folder.lastPathComponent ?? "All repositories") · \(operation.title)") + .foregroundStyle(.secondary) + } + Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 8) { + GridRow { + Text("Branch pattern") + TextField("Branch pattern", text: $patterns, prompt: Text("release/*")).labelsHidden() + } + GridRow { + Text("Agent action") + Picker("Agent action", selection: $level) { + ForEach(choices, id: \.self) { level in + Text(level.title).tag(level) + } + }.labelsHidden() + } + } + Text("Use * for any characters, including /. Separate multiple patterns with spaces.") + .font(.caption).foregroundStyle(.secondary) + if let errorMessage { Text(errorMessage).font(.caption).foregroundStyle(.red) } + if rule != nil { + HStack { + Button("Move Earlier") { submit(.move(-1)) }.disabled(!canMoveEarlier) + Button("Move Later") { submit(.move(1)) }.disabled(!canMoveLater) + Spacer() + Button("Remove Rule…", role: .destructive) { confirmsRemoval = true } + } + } + HStack { + Spacer() + Button("Cancel", role: .cancel) { dismiss() }.keyboardShortcut(.cancelAction) + Button(rule == nil ? "Add Rule" : "Save Rule") { saveRule() } + .keyboardShortcut(.defaultAction) + .disabled(patternList.isEmpty) + } + } + .padding(20) + .frame(width: 420) + .onAppear { + patterns = rule?.patterns.joined(separator: " ") ?? "" + level = rule?.level ?? (repository == nil ? operation.defaultLevel : .name) + } + .alert("Remove this branch rule?", isPresented: $confirmsRemoval) { + Button("Cancel", role: .cancel) {} + Button("Remove Rule", role: .destructive) { submit(.remove) } + } + } + + private func saveRule() { + let name = patternList.joined(separator: " ") + var updated = rule ?? GitBranchType(name: name, patterns: [], level: level) + if let rule, rule.name == rule.patterns.joined(separator: " ") { updated.name = name } + updated.patterns = patternList + updated.level = level + submit(.save(updated)) + } + + private func submit(_ action: Change) { + do { + try change(action) + dismiss() + } catch { + errorMessage = "Could not save the rule. \(error.localizedDescription)" + } + } +} + +extension GitBranchOperation { + var title: String { + switch self { + case .push: "Push" + case .forcePush: "Force Push" + case .delete: "Delete Remote Branch" + } + } + + var ruleTitle: String { + switch self { + case .push: "Push Rule" + case .forcePush: "Force-Push Rule" + case .delete: "Deletion Rule" + } + } +} + +extension GitCheckLevel { + var title: String { + switch self { + case .none: "Allow" + case .click: "Confirm" + case .name: "Confirm + type repository name" + case .forbid: "Block" + } + } +} diff --git a/Sources/AgentWatchApp/MothershipGitRegistration.swift b/Sources/AgentWatchApp/MothershipGitRegistration.swift deleted file mode 100644 index c133e8a..0000000 --- a/Sources/AgentWatchApp/MothershipGitRegistration.swift +++ /dev/null @@ -1,81 +0,0 @@ -import AgentWatchCore -import AgentWatchGit -import AgentWatchLookup -import Foundation - -enum MothershipGitRegistration { - enum State { case registered, absent, unknown } - - static func check(source: AgentSource, profile: URL) -> State { - let id = "mothership@mothership" - do { - let plugin: URL - switch source { - case .claude: - let settings = try object(in: profile.appendingPathComponent("settings.json")) - guard let enabled = settings["enabledPlugins"] as? [String: Any], enabled[id] as? Bool == true else { - return .absent - } - let registry = try object(in: profile.appendingPathComponent("plugins/installed_plugins.json")) - guard let records = registry["plugins"] as? [String: [[String: Any]]], - let path = records[id]?.first(where: { $0["scope"] as? String == "user" })?["installPath"] - as? String - else { return .unknown } - plugin = URL(fileURLWithPath: path) - case .codex: - let cache = profile.appendingPathComponent("plugins/cache/mothership/mothership") - guard FileManager.default.fileExists(atPath: cache.path) else { return .absent } - guard let executable = AgentInstallationLookup.executable(for: .codex) else { return .unknown } - let result = try BoundedCommand.run( - executable: URL(fileURLWithPath: executable), - arguments: ["plugin", "list", "--json", "--marketplace", "mothership"], in: profile, - environment: [ - "CODEX_HOME": profile.path, "HOME": profile.deletingLastPathComponent().path, - "PATH": "/usr/bin:/bin", - ], - timeout: 5) - guard result.status == 0, - let records = try JSONSerialization.jsonObject(with: result.output) as? [String: Any], - let installed = records["installed"] as? [[String: Any]] - else { return .unknown } - guard - let record = installed.first(where: { - $0["pluginId"] as? String == id && $0["enabled"] as? Bool == true - }) - else { return .absent } - guard let version = record["version"] as? String, !version.contains("/"), !version.hasPrefix(".") else { - return .unknown - } - plugin = cache.appendingPathComponent(version) - } - let manifest = try object(in: plugin.appendingPathComponent(".\(source.rawValue)-plugin/plugin.json")) - let hooks: [String: Any] - if let inline = manifest["hooks"] as? [String: Any] { - hooks = inline - } else { - let path = manifest["hooks"] as? String ?? "hooks/hooks.json" - guard !path.hasPrefix("/"), !path.split(separator: "/").contains("..") else { return .unknown } - let file = try object(in: plugin.appendingPathComponent(path)) - hooks = file["hooks"] as? [String: Any] ?? [:] - } - let groups = hooks["PreToolUse"] as? [[String: Any]] ?? [] - let registered = groups.contains { group in - (group["hooks"] as? [[String: Any]] ?? []).contains { - ($0["command"] as? String)?.contains("${CLAUDE_PLUGIN_ROOT}/hooks/git-guard.sh") == true - } - } - return registered ? .registered : .absent - } catch { return .unknown } - } - - private static func object(in url: URL) throws -> [String: Any] { - let data: Data - do { data = try Data(contentsOf: url) } catch let error as CocoaError where error.code == .fileReadNoSuchFile { - return [:] - } - guard let value = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { - throw CocoaError(.fileReadCorruptFile) - } - return value - } -} diff --git a/Sources/AgentWatchApp/SettingsWindowController.swift b/Sources/AgentWatchApp/SettingsWindowController.swift index cb31e59..5778de7 100644 --- a/Sources/AgentWatchApp/SettingsWindowController.swift +++ b/Sources/AgentWatchApp/SettingsWindowController.swift @@ -31,14 +31,14 @@ final class SettingsWindowController: NSWindowController, NSWindowDelegate { host: host, version: version ) + // Keep the form below the title bar so scrolling cannot draw behind the toolbar. let window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 760, height: 560), - styleMask: [.titled, .closable, .resizable, .miniaturizable, .fullSizeContentView], + styleMask: [.titled, .closable, .resizable, .miniaturizable], backing: .buffered, defer: false ) window.title = "Agent Watch Settings" - window.titlebarAppearsTransparent = true window.toolbarStyle = .unified window.isReleasedWhenClosed = false window.contentMinSize = NSSize(width: 680, height: 460) diff --git a/Sources/AgentWatchGit/GitProtectionRules.swift b/Sources/AgentWatchGit/GitProtectionRules.swift new file mode 100644 index 0000000..c11ad7e --- /dev/null +++ b/Sources/AgentWatchGit/GitProtectionRules.swift @@ -0,0 +1,140 @@ +import Foundation + +public enum GitBranchOperation: String, CaseIterable, Identifiable, Sendable { + case push, forcePush, delete + + public var id: Self { self } + + public var defaultLevel: GitCheckLevel { + switch self { + case .push: .none + case .forcePush: .name + case .delete: .click + } + } +} + +/// Shared with AgentWatchGit. Version 1 applied each type to both editable operations. +public struct GitProtectionRules: Codable, Equatable, Sendable { + public struct Rules: Codable, Equatable, Sendable { + public var forcePush: [GitBranchType] = [] + public var delete: [GitBranchType] = [] + + public init() {} + + public subscript(operation: GitBranchOperation) -> [GitBranchType] { + get { + switch operation { + case .push: [] + case .forcePush: forcePush + case .delete: delete + } + } + set { + switch operation { + case .push: break + case .forcePush: forcePush = newValue + case .delete: delete = newValue + } + } + } + } + + public static let fileName = GitBranchTypes.fileName + private static let maxBytes = 1024 * 1024 + private let version: Int + public var enabled: Bool + public var global: Rules + public var repositories: [String: Rules] + + public init() { + version = 2 + enabled = true + global = Rules() + repositories = [:] + } + + public static func load(from url: URL) throws -> Self { + let file: FileHandle + do { + file = try FileHandle(forReadingFrom: url) + } catch let error as CocoaError where error.code == .fileNoSuchFile || error.code == .fileReadNoSuchFile { + return Self() + } + defer { try? file.close() } + let data = try file.read(upToCount: maxBytes + 1) ?? Data() + guard data.count <= maxBytes else { throw Failure.tooLarge } + let decoder = JSONDecoder() + switch try decoder.decode(Version.self, from: data).version { + case 1: + let old = try decoder.decode(GitBranchTypes.self, from: data) + var rules = Self() + rules.global.forcePush = old.types + // The editor uses the rule ID to locate changes. Each operation owns its copy. + rules.global.delete = old.types.map { GitBranchType(name: $0.name, patterns: $0.patterns, level: $0.level) } + return rules + case 2: + return try decoder.decode(Self.self, from: data) + case let version: + throw GitBranchTypes.TableError.unknownVersion(version) + } + } + + public func save(to url: URL) throws { + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] + let data = try encoder.encode(self) + guard data.count <= Self.maxBytes else { throw Failure.tooLarge } + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: url, options: .atomic) + } + + public func level( + for operation: GitBranchOperation, branch: String, repository: String? + ) -> (level: GitCheckLevel, source: String?) { + func match(_ rules: [GitBranchType]) -> GitBranchType? { + rules.first { $0.patterns.contains { GitBranchTypes.matches(pattern: $0, name: branch) } } + } + let globalRule = match(global[operation]) + let level = globalRule?.level ?? operation.defaultLevel + if let repository, let rules = repositories[repository], let local = match(rules[operation]), + local.level > level + { + return (local.level, local.name) + } + return (level, globalRule?.name) + } + + private struct Version: Decodable { let version: Int } + + private enum Failure: LocalizedError { + case tooLarge + + var errorDescription: String? { "The Git protection rules file is too large (maximum 1 MB)." } + } +} + +public struct GitProtectionRepository: Equatable, Sendable { + public let folder: URL + public let key: String + + public init(folder: URL) throws { + let result = try GitCommand.run(["rev-parse", "--git-common-dir"], in: folder) + guard result.status == 0, var path = String(data: result.output, encoding: .utf8) + else { throw Failure.invalidRepository } + if path.hasSuffix("\n") { path.removeLast() } + guard !path.isEmpty else { throw Failure.invalidRepository } + let directory = + path.hasPrefix("/") + ? URL(fileURLWithPath: path, isDirectory: true) + : folder.appendingPathComponent(path, isDirectory: true) + self.folder = folder + key = directory.resolvingSymlinksInPath().standardizedFileURL.path + } + + private enum Failure: LocalizedError { + case invalidRepository + + var errorDescription: String? { "Choose a folder in a Git repository." } + } +} diff --git a/Tests/AgentWatchAppTests/GitHookInstallerTests.swift b/Tests/AgentWatchAppTests/GitHookInstallerTests.swift index 935ade0..c464f11 100644 --- a/Tests/AgentWatchAppTests/GitHookInstallerTests.swift +++ b/Tests/AgentWatchAppTests/GitHookInstallerTests.swift @@ -138,25 +138,16 @@ final class GitHookInstallerTests: XCTestCase { XCTAssertEqual(try Data(contentsOf: file), content) } - func testLegacyWarningRequiresAnEnabledPluginWithTheGitHook() throws { - let profile = root.appendingPathComponent("legacy") - let plugin = profile.appendingPathComponent("plugins/cache/mothership/mothership/1") - let manifest = plugin.appendingPathComponent(".claude-plugin/plugin.json") - try FileManager.default.createDirectory( - at: manifest.deletingLastPathComponent(), withIntermediateDirectories: true) - let hook = - #"{"hooks":{"PreToolUse":[{"hooks":[{"command":"bash \"${CLAUDE_PLUGIN_ROOT}/hooks/git-guard.sh\""}]}]}}"# - try Data(hook.utf8).write(to: manifest) - let registry = try JSONSerialization.data(withJSONObject: [ - "plugins": ["mothership@mothership": [["scope": "user", "installPath": plugin.path]]] - ]) - try registry.write(to: profile.appendingPathComponent("plugins/installed_plugins.json")) - XCTAssertEqual(MothershipGitRegistration.check(source: .claude, profile: profile), .absent) - try Data(#"{"enabledPlugins":{"mothership@mothership":true}}"#.utf8) - .write(to: profile.appendingPathComponent("settings.json")) - XCTAssertEqual(MothershipGitRegistration.check(source: .claude, profile: profile), .registered) - try Data(#"{"hooks":{"PreToolUse":[]}}"#.utf8).write(to: manifest) - XCTAssertEqual(MothershipGitRegistration.check(source: .claude, profile: profile), .absent) + func testStatusReadsBothProfilesInTheSameFolderDuringAWriteLock() throws { + for source in AgentSource.allCases { + XCTAssertEqual(try installer.apply(.install, source: source, profile: root), .registered) + } + let lock = try AgentProfileLock(root) + defer { withExtendedLifetime(lock) {} } + for source in AgentSource.allCases { + XCTAssertEqual(try installer.apply(.status, source: source, profile: root), .registered) + XCTAssertThrowsError(try installer.apply(.remove, source: source, profile: root)) + } } func testCustomGroupIsNotOverwrittenOrDuplicated() throws { diff --git a/Tests/AgentWatchAppTests/SettingsRenderProbe.swift b/Tests/AgentWatchAppTests/SettingsRenderProbe.swift index b2965ee..ad63fb7 100644 --- a/Tests/AgentWatchAppTests/SettingsRenderProbe.swift +++ b/Tests/AgentWatchAppTests/SettingsRenderProbe.swift @@ -7,7 +7,7 @@ import XCTest @testable import AgentWatchApp /// Draws settings pages into PNG files, for a person to look at: the ones that show a theme, -/// the two whose switches say beside them why one is greyed, `General` and the branch types. +/// the two whose switches say beside them why one is greyed, `General` and Git Protection. /// /// Skipped unless `SETTINGS_RENDER_DIR` names a directory. Drawn in a window that is never /// shown, so nothing appears on screen and nothing takes the focus from whoever is working. @@ -140,20 +140,22 @@ final class SettingsRenderProbe: XCTestCase { try draw(AnyView(ToolingPane(tooling: here)), height: 1700, named: "settings-tooling-here", in: directory) } - func testDrawTheBranchTypes() throws { + func testDrawGitProtection() throws { let requested = ProcessInfo.processInfo.environment["SETTINGS_RENDER_DIR"] try XCTSkipIf(requested == nil, "a drawing probe, not a check: set SETTINGS_RENDER_DIR") let directory = try XCTUnwrap(requested) - // The section alone: the whole pane would read and write the person's real table. - let table = GitBranchTypes(types: [ - GitBranchType(name: "Features", patterns: ["feature/*", "fix/*"], level: .click), - GitBranchType(name: "Releases", patterns: ["release/*", "hotfix/*"], level: .name), - GitBranchType(name: "Agent drafts", patterns: ["agent/*", "tmp/*"], level: .none), - GitBranchType(name: "Archive", patterns: ["archive/*"], level: .forbid), - ]) + let scratch = FileManager.default.temporaryDirectory.appendingPathComponent("AgentWatchGit.\(UUID())") + addTeardownBlock { try? FileManager.default.trashItem(at: scratch, resultingItemURL: nil) } + let url = scratch.appendingPathComponent(GitProtectionRules.fileName) + let folders = AgentFolders(home: scratch) + var rules = GitProtectionRules() + rules.global.delete = [ + GitBranchType(name: "Releases", patterns: ["release/*"], level: .name) + ] + try rules.save(to: url) try draw( - AnyView(Form { GitBranchTypesSection(table: .constant(table), error: nil) }), height: 900, - named: "settings-git-branch-types", in: directory) + AnyView(GitProtectionPane(profiles: folders, rulesURL: url)), height: 720, + width: 510, named: "settings-git-protection", in: directory) } /// Three IDEs standing in the three places that read differently: one running with an diff --git a/Tests/AgentWatchGitTests/GitBranchTypesTests.swift b/Tests/AgentWatchGitTests/GitBranchTypesTests.swift index 55d8b0c..ccd789f 100644 --- a/Tests/AgentWatchGitTests/GitBranchTypesTests.swift +++ b/Tests/AgentWatchGitTests/GitBranchTypesTests.swift @@ -81,6 +81,41 @@ final class GitBranchTypesTests: XCTestCase { } } + func testV1RulesCarryOverToBothOperationsAndCanBeEditedIndependently() throws { + let url = try scratch().appendingPathComponent(GitProtectionRules.fileName) + try fixture("branch-types.json").write(to: url) + var config = try GitProtectionRules.load(from: url) + XCTAssertTrue(config.enabled) + XCTAssertEqual(config.global.forcePush, config.global.delete) + XCTAssertEqual(config.level(for: .forcePush, branch: "tmp/x", repository: nil).level, .none) + config.enabled = false + config.global.delete[2].level = .forbid + try config.save(to: url) + let reopened = try GitProtectionRules.load(from: url) + XCTAssertEqual(reopened, config) + XCTAssertEqual(reopened.level(for: .forcePush, branch: "tmp/x", repository: nil).level, .none) + XCTAssertEqual(reopened.level(for: .delete, branch: "tmp/x", repository: nil).level, .forbid) + } + + func testOperationAndRepositoryChecksAgreeWithTheNativeFixture() throws { + let url = try scratch().appendingPathComponent(GitProtectionRules.fileName) + XCTAssertEqual(try GitProtectionRules.load(from: url), GitProtectionRules()) + try fixture("branch-rules-v2.json").write(to: url) + let config = try GitProtectionRules.load(from: url) + XCTAssertTrue(config.enabled) + let repo = "/work/agent-watch/.git" + XCTAssertEqual(config.level(for: .forcePush, branch: "release/1", repository: repo).level, .forbid) + XCTAssertEqual(config.level(for: .delete, branch: "release/1", repository: repo).level, .name) + XCTAssertEqual(config.level(for: .forcePush, branch: "agent/kept", repository: repo).level, .name) + XCTAssertEqual(config.level(for: .delete, branch: "agent/kept", repository: repo).level, .forbid) + XCTAssertEqual(config.level(for: .delete, branch: "agent/kept", repository: nil).level, .none) + XCTAssertEqual(config.level(for: .push, branch: "release/1", repository: repo).level, .none) + try config.save(to: url) + let written = try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? NSDictionary + let expected = try JSONSerialization.jsonObject(with: fixture("branch-rules-v2.json")) as? NSDictionary + XCTAssertEqual(written, expected) + } + func testThePreviewAppliesTheFloorToTheType() { let table = GitBranchTypes(types: [ GitBranchType(name: "Drafts", patterns: ["agent/*", "main"], level: .none), diff --git a/docs/adr/0025-a-branch-type-chooses-the-check-above-a-floor.md b/docs/adr/0025-a-branch-type-chooses-the-check-above-a-floor.md index 32f0b1d..05a5310 100644 --- a/docs/adr/0025-a-branch-type-chooses-the-check-above-a-floor.md +++ b/docs/adr/0025-a-branch-type-chooses-the-check-above-a-floor.md @@ -2,12 +2,15 @@ **Статус:** принято 2026-11-23. +Общий переключатель и отдельные правила операций описаны в +[ADR-0028](0028-git-protection-settings-are-shared-by-agent-profiles.md). + До типов защита Git знала два класса веток, заданных в коде: обычные и защищённые (`main`, `master`, основная ветка сервера и ветки из `mothership.protectedBranch`). Владелец попросил настраиваемые типы веток: имя, шаблоны имени ветки и уровень проверки для принудительной отправки (force push) и удаления ветки на сервере. Уровней четыре: `none` — окна нет, `click` — одно подтверждение, `name` — подтверждение и ввод имени репозитория, `forbid` — отказ без окна. Как это -выглядит для человека — [«Типы веток»](../git-protection.md#типы-веток). +выглядит для человека — [«Правила веток»](../git-protection.md#правила-веток). ## Решение @@ -100,7 +103,10 @@ Git. Первая версия доверяла коротким именам и сторону и проверяется старыми тестами без правок. Явный тип `click` даёт одно окно для обеих операций. -## Почему файл через `HOME`, а нечитаемый файл — это «типов нет» +## Почему файл сначала читали через `HOME` + +Путь установленного исполнителя изменён в +[ADR-0028](0028-git-protection-settings-are-shared-by-agent-profiles.md). Агенты читают свои настройки через `HOME`, и `AgentWatchGit` запускается в их окружении. Тестовое окружение с другим `HOME` получает свою таблицу, а без файла — прежнее поведение. Отладочная diff --git a/docs/adr/0028-git-protection-settings-are-shared-by-agent-profiles.md b/docs/adr/0028-git-protection-settings-are-shared-by-agent-profiles.md new file mode 100644 index 0000000..6245b06 --- /dev/null +++ b/docs/adr/0028-git-protection-settings-are-shared-by-agent-profiles.md @@ -0,0 +1,24 @@ +# Защита Git использует общие настройки профилей агента + +**Статус:** принято 2026-11-26. + +[ADR-0025](0025-a-branch-type-chooses-the-check-above-a-floor.md) задаёт нижнюю границу проверки +защищённых веток. В интерфейсе одна строка меняла два разных действия, а правило репозитория +настраивалось в другом месте. При временном выключении приходилось удалять обработчики и затем +восстанавливать доверие Codex. + +Приложение хранит общий переключатель и отдельные правила принудительной отправки и удаления. +При выключении установленный обработчик пропускает команды со следующего вызова. Регистрации +и доверие в профилях сохраняются. При включённой защите ветки из ADR-0025 сохраняют нижнюю +границу. Прямой вызов исполнителя сохраняет проверку, даже если обработчик выключен. + +Переключатель и правила записываются атомарно в один файл. Если он недоступен, действуют +встроенные проверки. Вариант с отдельным переключателем в каждом профиле потребовал бы +согласования нескольких файлов. Удаление регистрации при выключении потребовало бы заново +подтверждать доверие при включении. Единый пользовательский файл также читается при закрытом +приложении. Он доступен тому же пользователю, от которого работают агенты, поэтому переключатель +защищает от случайного выключения в интерфейсе, а не от намеренной правки файла. + +Правило репозитория может поднять уровень, выбранный первым совпавшим общим правилом. Ключ — +канонический путь общей папки Git. Связанные рабочие копии получают те же правила. Перенос +репозитория меняет его ключ, а копия с тем же сервером получает собственный набор правил. diff --git a/docs/git-protection.md b/docs/git-protection.md index 6a6d692..84c48ab 100644 --- a/docs/git-protection.md +++ b/docs/git-protection.md @@ -1,102 +1,84 @@ # Защита Git в Agent Watch -Здесь описаны установка обработчиков Claude и Codex, правила веток, типы веток и проверка обновления -на macOS. -Чего здесь нет: подключение наблюдения за сессиями описано в [Tooling](agent-install.md). - -## Подключение и переход с Mothership - -1. Поместите сборку с защитой Git в постоянное место, например `/Applications/AgentWatch.app`. -2. В `Settings… → Git Protection → Protect Git commands` выберите клиент и профиль. Нажмите - `Install Git Hook`. Повторите для каждого профиля, в котором нужна защита. -3. В настольном Codex откройте `Settings → Hooks` и нажмите `Trust` у обработчика `PreToolUse` - из Agent Watch. В терминальном Codex та же настройка доступна через `/hooks`. - Откройте новый чат в каждом клиенте. Для проверки используйте локальный учебный репозиторий - и отмените запрос удаления ветки. -4. Если раньше защиту предоставлял Mothership, обновите его до версии без обработчика Git - после подключения Agent Watch. Затем откройте новые чаты. Остальные функции Mothership - обновляются обычным способом. +Здесь описаны подключение защиты Git для Claude Code и Codex, правила веток и проверка +обновления на macOS. Чего здесь нет: наблюдение за сессиями описано в [Tooling](agent-install.md). + +## Подключение профиля + +1. Поместите Agent Watch в постоянное место, например `/Applications/AgentWatch.app`. +2. В `Settings… → Git Protection → Agent profiles` нажмите `Install…` рядом с нужным профилем. + `Installed` означает, что в профиле записана актуальная команда Agent Watch. `Needs repair` + означает, что запись устарела или настроена вручную. `Remove…` удаляет запись выбранного профиля. +3. В Codex откройте `Settings → Hooks` или `/hooks` в терминале и нажмите `Trust` у обработчика + `PreToolUse` от Agent Watch. Затем откройте новый чат. В Claude Code также откройте новый чат. Claude хранит команду в `settings.json` своего профиля, Codex — в `hooks.json`. Команда указывает -на файл внутри установленного приложения. При замене приложения по тому же пути следующий -вызов запускает новую версию. Проект хранит правила в своей конфигурации Git. Обычное обновление -сохраняет и команду, и правила. Если вы перенесли само приложение, восстановите привязку через -`Repair Git Hook` и проверьте доверие в Codex. Для отключения выберите профиль и нажмите -`Remove Git Hook…`. Пока обработчик недоступен по указанному пути или не укладывается -в отведённое время, клиент получает отказ с предложением восстановить привязку. +на файл внутри установленного приложения. При обновлении по тому же пути следующий вызов запускает +новую версию. Если приложение перенесли, восстановите привязку через `Repair…` и проверьте доверие +в Codex. Если обработчик недоступен по указанному пути, клиент получает отказ со ссылкой на ремонт. -Обработчик проверяет команду оболочки перед её запуском. Для рискованной отправки он возвращает -клиенту причину отказа и команду для однократного запуска `AgentWatchGit push`. Обработчик -написан на Rust. Если настройки Git могут направить отправку на другое назначение, обработчик -просит указать его явно. -Исполнитель на Rust сам проверяет репозиторий и назначение, показывает окно macOS и завершает -работу после решения пользователя. Сервер MCP и запущенное окно настроек для этого не нужны. - -## Правило для одного проекта - -В настройках откройте `Git Protection`, выберите любую рабочую копию репозитория, введите точное -имя ветки и нажмите `Preview Confirmation`. Для удаления обычной ветки на сервере требуется одно -подтверждение. Для `main`, `master`, основной ветки сервера и ветки из списка защиты потребуется -также ввести имя репозитория. Если основная ветка сервера неизвестна, пример объясняет это условие. -Её определяет исполнитель при обращении к выбранному серверу. Если сервер не сообщает основную -ветку, исполнитель останавливает удаление ветки, для которой ещё не действует правило защиты. -Так проверяется ветка без типа; тип ветки меняет уровень в пределах пола, см. [«Типы веток»](#типы-веток). - -`Require Repository Name` добавляет ветку в локальный список `mothership.protectedBranch`. -Связанные рабочие копии используют этот же список. Снятие правила запрашивает подтверждение и -удаляет только точное значение из основного файла настроек репозитория. Правило из подключённого -файла Git продолжает действовать. Предварительный просмотр и изменение настроек работают без -сетевого соединения. Для защиты команд нужен установленный обработчик Git. - -На Mac `AgentWatchGit` показывает отдельное окно Agent Watch. В нём указаны операция, репозиторий и -имя ветки. При отказе, закрытии окна или истечении времени операция останавливается. Агент -не может подтвердить её за человека. - -## Типы веток - -В `Settings… → Git Protection → Branch types` задаётся таблица типов, одна на все репозитории. -Тип — это имя, шаблоны имени ветки и уровень проверки. Уровень действует на принудительную отправку -(force push) и на удаление ветки на сервере. Остальные отправки проверяются как раньше. - -| Уровень в настройках | В файле | Что происходит | +## Общий переключатель + +`Protect Git commands` включён по умолчанию. Выключение требует подтверждения и останавливает проверки +команд во всех подключённых профилях со следующего вызова обработчика. Установленные обработчики и +правила сохраняются, повторное включение возвращает их в действие. Для работы переключателя и правил +можно закрыть окно приложения. Вызванная напрямую команда `AgentWatchGit push` по-прежнему проверяет +операцию и при необходимости показывает окно. + +## Правила веток + +В `Branch rules` сначала выберите действие: + +- `Push` показывает встроенные правила обычной отправки. Для `main` и `master` нужно подтверждение + и имя репозитория. Другие ветки по умолчанию проходят без окна. Если назначение нельзя точно + определить по команде, обработчик просит агента указать его явно. +- `Force Push` задаёт правила принудительной отправки. Ветка без совпадения требует подтверждения + и имени репозитория. +- `Delete Remote Branch` задаёт правила удаления ветки на сервере. Ветка без совпадения требует + одного подтверждения. + +| Действие агента | В файле | Что происходит | |---|---|---| -| `No Window` | `none` | Окна нет: обычная команда `git push` агента проходит. | -| `Click` | `click` | Одно окно; его кнопка выполняет операцию. | -| `Click + Name` | `name` | Подтверждение, затем ввод имени репозитория. | -| `Forbid` | `forbid` | Отказ без окна. Команду запускает человек в терминале. | - -Тип выбирается по первому совпавшему шаблону, сверху вниз. Порядок меняют стрелки в строке типа. -`*` совпадает с любыми символами, включая `/`: `release/*` подходит и для `release/2026/q1`. `?` — -один любой символ. Остальные символы сравниваются точно, с учётом регистра. Шаблоны разделяются -пробелом: в имени ветки пробела не бывает, а запятая бывает. - -Ветка без типа проверяется как раньше: удаление — одно подтверждение, принудительная отправка — -подтверждение и имя репозитория. Пока таблица пуста, ничего не меняется. - -**Пол.** `main`, `master`, основная ветка сервера, ветки из `mothership.protectedBranch` и метки -всегда требуют не меньше `Click + Name`. Тип может только поднять их до `Forbid`. Правило -`Require Repository Name` тоже только поднимает уровень. Агент работает от того же пользователя и -может изменить любой файл настроек, поэтому гарантию даёт только пол -([ADR-0025](adr/0025-a-branch-type-chooses-the-check-above-a-floor.md)). +| `Allow` | `none` | Действие разрешено без окна. | +| `Confirm` | `click` | Нужно одно подтверждение. | +| `Confirm + type repository name` | `name` | Нужно подтвердить действие и ввести имя репозитория. | +| `Block` | `forbid` | Агент получает отказ. Человек может выполнить команду в терминале. | + +В `All repositories` применяется первый совпавший шаблон выбранного действия. Кнопки `Move Earlier` +и `Move Later` в редакторе меняют порядок. `*` совпадает с любыми символами, включая `/`. Например, +`release/*` подходит и для `release/2026/q1`. `?` совпадает с одним символом. Регистр учитывается. +Несколько шаблонов в одном правиле разделяются пробелами. + +Выберите `One repository…`, если в конкретном репозитории нужна более строгая проверка. Первое +совпавшее правило репозитория может усилить итоговый уровень. Например, `Confirm` в репозитории +усиливает общее `Allow`. Все связанные рабочие копии используют одни правила. `main`, `master`, основная ветка сервера, ветки из `mothership.protectedBranch` и метки +при принудительной отправке или удалении требуют как минимум подтверждения и имени репозитория. +Код проверяет эту границу, даже если шаблон разрешает действие без окна. + +`Preview a Branch` показывает проверку для выбранного действия, репозитория и точного имени ветки. +Пример работает без сети. Если результат зависит от основной ветки сервера, пример объясняет условие. +При выполнении отправки исполнитель уточняет основную ветку у сервера. Правило из файла конфигурации +Git также видно в примере. Точное локальное правило можно убрать с подтверждением, правило из +подключённого файла Git продолжает действовать. -### Файл таблицы +Обработчик проверяет команду оболочки перед её запуском. Для рискованной отправки он возвращает +клиенту причину отказа и команду для однократного запуска `AgentWatchGit push`. Исполнитель проверяет +репозиторий и назначение, показывает отдельное окно macOS и останавливается при отказе, закрытии окна +или истечении времени. Агент не может подтвердить окно за человека. -Приложение записывает таблицу в `~/Library/Application Support/AgentWatch/git-branch-types.json`. -`AgentWatchGit` читает её при каждой проверке, через `HOME` того процесса, который его запустил: +### Файл правил -```json -{ - "types" : [ - { "level" : "none", "name" : "Agent drafts", "patterns" : [ "agent/*", "tmp/*" ] } - ], - "version" : 1 -} -``` +Приложение записывает переключатель и таблицы в +`~/Library/Application Support/AgentWatch/git-branch-types.json`. Версия 2 хранит общий переключатель, +отдельные таблицы `forcePush` и `delete` и правила репозиториев по их общей папке Git. Смена пути +репозитория меняет его ключ. При чтении файла версии 1 прежние правила используются для обеих +операций. Файл обновляется при первом сохранении из настроек. -Если файла нет, он не читается, у него другая версия или неизвестный уровень, `AgentWatchGit` -считает, что типов нет, и проверяет ветки как раньше. Страница настроек показывает такую ошибку. -Отладочная копия приложения с `AGENT_WATCH_SUPPORT_DIR` пишет таблицу в свою папку, а -`AgentWatchGit` ищет её только по `HOME`. +Установленный исполнитель использует домашнюю папку учётной записи macOS, даже если профиль агента +запущен с другим `HOME`. В отладочной сборке запускайте приложение и обработчик с одинаковым +`AGENT_WATCH_SUPPORT_DIR`, если используете эту переменную. Неупакованный исполнитель для испытаний +берёт путь из `HOME`. Отсутствующий, повреждённый или неизвестный файл включает встроенные проверки +без пользовательских правил. Страница настроек показывает ошибку чтения. ### Как уровень применяют обработчик и исполнитель @@ -139,14 +121,14 @@ Claude хранит команду в `settings.json` своего профил команде, отправка по настройкам Git) проверяются как раньше при любом уровне. Обработчик проверяет команды, которые он узнаёт, и не заменяет песочницу: отправку через псевдоним -Git, `=git` в zsh или `xcrun git` он не распознаёт, как и до типов веток. Путь без окна не добавляет +Git, `=git` в zsh или `xcrun git` он не распознаёт, как и до правил веток. Путь без окна не добавляет нового способа задеть пол, но против агента, который нарочно обходит проверку, гарантия — только исполнитель и сервер Git ([ADR-0025](adr/0025-a-branch-type-chooses-the-check-above-a-floor.md)). Обработчик видит окружение агента, а не оболочки, в которой выполнится команда. Если оболочка получает `GIT_DIR` или `GIT_CONFIG_PARAMETERS` из файлов запуска, обработчик этого не знает. Так -было и до типов веток; правка файлов запуска — тот же уровень доступа, что правка таблицы. +было и до правил веток; правка файлов запуска — тот же уровень доступа, что правка таблицы. ## Ручная проверка подтверждений @@ -226,8 +208,6 @@ macOS 26.6.2). Обычное переключение на соседнюю в ## Сквозная проверка в Codex -В этой проверке Mothership передавал запрос на подтверждение Agent Watch. - 19 ноября 2026 года в обычном чате Codex `push_once` вернул `completed` после того, как пользователь подтвердил удаление тестовой ветки в окне Agent Watch сборки `6ac27a52` (замер: Codex 0.169.0-alpha.11.1, macOS 27.2). Затем `git ls-remote` подтвердил, что тестовой diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 1182658..c206897 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -58,10 +58,11 @@ Agent Watch и агентов. [План установки, управлени Режим у камеры и управление сном отложены до проверки основных сценариев. -Типы веток с уровнями `none`, `click`, `name` и `forbid` и пол, который тип не опускает, -сделаны после 0.5.0 и ещё не вышли в релизе ([ADR-0025](adr/0025-a-branch-type-chooses-the-check-above-a-floor.md)). -Осталось проверить их владельцу на живой установке: окна `click` и `name`, отказ `forbid` и -отправку без окна при `none` в Claude и Codex. +Настройки защиты Git показывают состояние обработчика каждого профиля и общий переключатель. +У принудительной отправки и удаления веток отдельные списки правил. Репозиторий может усилить +проверку. Встроенная граница для защищённых веток действует, пока защита включена +([ADR-0028](adr/0028-git-protection-settings-are-shared-by-agent-profiles.md)). Остаётся проверка +окон `click` и `name`, отказа `forbid` и отправки без окна при `none` в обоих настольных клиентах. ## Наблюдение Skip в Codex diff --git a/docs/settings.md b/docs/settings.md index f5ad33f..21ce7b4 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -19,17 +19,9 @@ чтение транскриптов и обновления ([«Обновление»](distribution.md#обновление)). - **`Tooling`** — что приложение записало в агентов и IDE, кнопки установки и мастер подключения ([«Страница Tooling»](agent-install.md#страница-tooling)). -- **`Git Protection`** — подключить защиту к профилям Claude и Codex, выбрать папку репозитория - и ввести имя ветки, чтобы посмотреть пример подтверждения удаления на сервере. Для `main`, `master` и точного - совпадения с локальной настройкой `mothership.protectedBranch` потребуется имя репозитория. - В остальных случаях экран показывает оба варианта: результат зависит от основной ветки сервера. - Кнопка `Preview Confirmation` читает настройки заново. Сеть, установка защиты и удаление ветки - для просмотра не требуются. Кнопка `Require Repository Name` записывает точное имя ветки в - настройки репозитория. Кнопка `Remove Project Rule…` просит подтвердить снятие его правила. - Правила из подключённых файлов Git видны отдельно. Таблица `Branch types` задаёт для всех - репозиториев типы веток и уровень проверки принудительной отправки и удаления каждого типа; - пример подтверждения учитывает тип. Строки `main, master, the remote’s default branch, tags` и - `Branches without a type` серые: их тип не меняет. Таблица сохраняется при каждом изменении. +- **`Git Protection`** — общий переключатель защиты, состояние обработчика для каждого профиля + Claude Code и Codex, отдельные правила для принудительной отправки и удаления ветки на сервере. + Репозиторий выбирают для более строгого правила или для предварительного просмотра. [Подробнее о защите Git](git-protection.md). - **`Working Copies`** — выбрать репозиторий, посмотреть его рабочие копии и папки, занявшие место. Отчёт показывает происхождение каждой копии и предупреждения. [Рабочие копии и место на диске](worktree-disk.md). diff --git a/native/devtool/src/packaging/bundle.rs b/native/devtool/src/packaging/bundle.rs index 6b7d036..85eacfa 100644 --- a/native/devtool/src/packaging/bundle.rs +++ b/native/devtool/src/packaging/bundle.rs @@ -79,7 +79,7 @@ impl Settings { // Build next to the destination so failed compilation or signing preserves the previous copy. let stage = scratch(parent)?; let staged = stage.join(app.file_name().ok_or("missing bundle name")?); - self.assemble(root, &bin, &staged, name) + self.assemble(root, &bin, &staged, name, configuration) .map_err(|e| format!("{e}\nBuild files: {}", stage.display()))?; trash(&app)?; io(fs::rename(&staged, &app), &app)?; @@ -87,7 +87,14 @@ impl Settings { Ok(app) } - fn assemble(&self, root: &Path, bin: &Path, app: &Path, name: &str) -> Result { + fn assemble( + &self, + root: &Path, + bin: &Path, + app: &Path, + name: &str, + configuration: &str, + ) -> Result { let contents = app.join("Contents"); let executables = contents.join("MacOS"); let resources = contents.join("Resources"); @@ -182,8 +189,17 @@ impl Settings { let target = std::env::var_os("CARGO_TARGET_DIR") .filter(|s| !s.is_empty()) .map_or_else(|| root.join(".build/devtool"), |p| root.join(p)); + let support_folder = if self.dev { + "AgentWatch Dev" + } else { + "AgentWatch" + }; run_cmd( cmd("rustup") + .env( + "AGENT_WATCH_GIT_BUNDLE_POLICY", + format!("{support_folder}/{configuration}"), + ) .args([ "run", "1.98.1", diff --git a/native/git-protection/Cargo.toml b/native/git-protection/Cargo.toml index bcb473a..0db943c 100644 --- a/native/git-protection/Cargo.toml +++ b/native/git-protection/Cargo.toml @@ -18,7 +18,7 @@ required-features = ["mcp-fixture"] serde = { version = "1.0.228", features = ["derive"] } serde_json = "1.0.154" signal-hook = "0.4.6" -nix = { version = "0.31.2", default-features = false, features = ["fs", "poll", "process", "signal"] } +nix = { version = "0.31.2", default-features = false, features = ["fs", "poll", "process", "signal", "user"] } [target.'cfg(target_os = "macos")'.dependencies] muda = { version = "0.21.2", default-features = false } diff --git a/native/git-protection/src/git.rs b/native/git-protection/src/git.rs index 412fce0..f91682c 100644 --- a/native/git-protection/src/git.rs +++ b/native/git-protection/src/git.rs @@ -219,7 +219,16 @@ impl Git { let branch = destination .strip_prefix("refs/heads/") .unwrap_or(destination); - let (chosen, kind) = levels::chosen(&BranchTypes::load(), branch, delete); + let types = BranchTypes::load(); + let common = if types.has_repository_rules() { + Some(levels::canonical_directory( + Path::new(repo), + &self.read(repo, levels::COMMON_DIRECTORY_ARGS)?, + )?) + } else { + None + }; + let (chosen, kind) = levels::chosen(&types, branch, delete, common.as_deref()); let level = if chosen < Level::Name { levels::with_floor(chosen, self.protected_branch(repo, url, destination)?) } else { diff --git a/native/git-protection/src/hook/mod.rs b/native/git-protection/src/hook/mod.rs index 09b656e..3bb4fd5 100644 --- a/native/git-protection/src/hook/mod.rs +++ b/native/git-protection/src/hook/mod.rs @@ -3,6 +3,7 @@ mod commands; mod policy; mod shell; +use crate::levels::BranchTypes; use crate::process::{Cancellation, EXPIRED}; use nix::errno::Errno; use nix::poll::{PollFd, PollFlags, PollTimeout, poll}; @@ -20,6 +21,7 @@ const GUIDANCE: &str = "with repository (absolute working tree path), destinatio fn inspect( payload: &Value, binary: &Path, + rules: &BranchTypes, cancel: &Cancellation, deadline: Instant, ) -> Result, String> { @@ -60,6 +62,7 @@ fn inspect( policy::literal(command), &cwd, &home, + rules, cancel, deadline, )?; @@ -115,11 +118,15 @@ fn read_event(input: impl AsFd, cancel: &Cancellation, deadline: Instant) -> Res fn inspect_event() -> Result, String> { let deadline = Instant::now() + Duration::from_secs(6); + let rules = BranchTypes::load(); + if !rules.enabled() { + return Ok(None); + } let cancel = Cancellation::for_command()?; let event = read_event(std::io::stdin(), &cancel, deadline)?; let path = std::env::current_exe().map_err(|_| "The Agent Watch Git executable is unavailable.")?; - inspect(&event, &path, &cancel, deadline) + inspect(&event, &path, &rules, &cancel, deadline) } pub(super) fn run(args: &[String]) -> Result<(), String> { diff --git a/native/git-protection/src/hook/policy.rs b/native/git-protection/src/hook/policy.rs index a7e1cfd..34bd32f 100644 --- a/native/git-protection/src/hook/policy.rs +++ b/native/git-protection/src/hook/policy.rs @@ -3,7 +3,7 @@ use super::commands::{basename, command_index, git_subcommand}; use super::shell::Parsed; -use crate::levels::{BranchTypes, Level}; +use crate::levels::{self, BranchRules, BranchTypes, Level}; use crate::process::{self, Cancellation, Output}; use std::collections::HashSet; use std::path::{Path, PathBuf}; @@ -235,31 +235,25 @@ enum Outcome { /// Decides one destination. Git is asked only when a type would allow or forbid, so with no /// matching type a command is inspected exactly as before types existed. fn outcome( - types: &BranchTypes, + rules: BranchRules<'_>, allow: bool, candidate: Option<&str>, resolve: impl FnOnce() -> Result, String>, repo: &Repository, ) -> Result { - let interesting = |name: &str| { - types - .matching(name) - .is_some_and(|kind| matches!(kind.level, Level::None | Level::Forbid)) - }; - if !types.has_none_or_forbid() || candidate.is_some_and(|name| !interesting(name)) { + let interesting = |name: &str| matches!(rules.selected(name).0, Level::None | Level::Forbid); + if !rules.has_none_or_forbid() || candidate.is_some_and(|name| !interesting(name)) { return Ok(Outcome::Checked); } let Some((branch, remote)) = resolve()? else { return Ok(Outcome::Checked); }; - Ok(match types.matching(&branch) { - Some(kind) if kind.level == Level::Forbid => Outcome::Forbidden { + Ok(match rules.selected(&branch) { + (Level::Forbid, Some(rule)) => Outcome::Forbidden { branch, - kind: kind.name.clone(), + kind: rule.name.clone(), }, - Some(kind) if kind.level == Level::None && allow && repo.below_floor(&remote, &branch) => { - Outcome::Allowed - } + (Level::None, _) if allow && repo.below_floor(&remote, &branch) => Outcome::Allowed, _ => Outcome::Checked, }) } @@ -453,6 +447,23 @@ impl<'a> Push<'a> { } let remote = self.operands.first().copied().or(self.remote_option); let refspecs = self.operands.get(1..).unwrap_or_default(); + let uses_branch_rules = self.force + || self.delete + || refspecs + .iter() + .any(|reference| reference.len() > 1 && reference.starts_with(':')); + let common = if uses_branch_rules && types.has_repository_rules() { + let output = repo.query(levels::COMMON_DIRECTORY_ARGS)?; + if !output.status.success() { + return Err("Git could not identify the repository for the branch rules.".into()); + } + let directory = output.stdout.strip_suffix('\n').unwrap_or(&output.stdout); + Some(levels::canonical_directory(repo.path, directory)?) + } else { + None + }; + let force_rules = types.rules(false, common.as_deref()); + let delete_rules = types.rules(true, common.as_deref()); let implicit = refspecs.is_empty() && !self.tags_only && !self.all; if overrides { risks.push("command-local Git configuration may override push routing".into()); @@ -476,7 +487,7 @@ impl<'a> Push<'a> { let decided = if tag { Outcome::Checked } else { - deleted(repo, types, allow, remote, name)? + deleted(repo, delete_rules, allow, remote, name)? }; verdict.delete(decided, || deletion(repo, context, name, tag))?; } else if reference == ":" || reference.contains('*') { @@ -511,14 +522,14 @@ impl<'a> Push<'a> { Outcome::Checked } else { let local = !reference.contains(':'); - rewritten(repo, types, allow, remote, local, destination)? + rewritten(repo, force_rules, allow, remote, local, destination)? }); } } tag = false; } if implicit { - self.current_branch(repo, context, types, allow, &mut verdict, &mut forced)?; + self.current_branch(repo, context, force_rules, allow, &mut verdict, &mut forced)?; } if self.force { verdict.force(forced, usize::from(self.prune)); @@ -533,7 +544,7 @@ impl Push<'_> { &self, repo: &Repository, context: &Context, - types: &BranchTypes, + rules: BranchRules<'_>, allow: bool, verdict: &mut Verdict, forced: &mut Vec, @@ -547,7 +558,7 @@ impl Push<'_> { if self.force && !self.delete { let remote = self.operands.first().copied().or(self.remote_option); forced.push(outcome( - types, + rules, allow, Some(&branch), || { @@ -570,13 +581,13 @@ impl Push<'_> { /// How a deletion of `name` is decided. fn deleted( repo: &Repository, - types: &BranchTypes, + rules: BranchRules<'_>, allow: bool, remote: Option<&str>, name: &str, ) -> Result { outcome( - types, + rules, allow, Some(name.strip_prefix("refs/heads/").unwrap_or(name)), || { @@ -591,7 +602,7 @@ fn deleted( /// How a force push of `source` to `destination` is decided. fn rewritten( repo: &Repository, - types: &BranchTypes, + rules: BranchRules<'_>, allow: bool, remote: Option<&str>, local: bool, @@ -603,7 +614,7 @@ fn rewritten( .unwrap_or(destination) }); outcome( - types, + rules, allow, candidate, || { @@ -639,7 +650,7 @@ impl Verdict { match decided { Outcome::Allowed => {} Outcome::Forbidden { branch, kind } => self.forbidden.push(format!( - "deleting branch '{branch}' is forbidden by branch type '{kind}'" + "deleting branch '{branch}' is forbidden by branch rule '{kind}'" )), Outcome::Checked => self.risks.push(risk()?), } @@ -653,7 +664,7 @@ impl Verdict { match decided { Outcome::Allowed => {} Outcome::Forbidden { branch, kind } => self.forbidden.push(format!( - "force push to '{branch}' is forbidden by branch type '{kind}'" + "force push to '{branch}' is forbidden by branch rule '{kind}'" )), Outcome::Checked => checked = true, } @@ -743,13 +754,13 @@ pub(super) fn check( literal: bool, cwd: &Path, home: &Path, + types: &BranchTypes, cancel: &Cancellation, deadline: Instant, ) -> Result { let mut folders = vec![None; parsed.parents.len()]; folders[0] = Some(cwd.to_owned()); let mut context = Context::default(); - let mut types = None; let mut verdict = Verdict::default(); let mut seen = HashSet::new(); let alone = literal && parsed.total == 1 && parsed.commands.len() == 1; @@ -809,7 +820,7 @@ pub(super) fn check( }, &context, overrides, - types.get_or_insert_with(BranchTypes::load), + types, alone && i == 0 && pos == 0 && command.words[0] == "git", )?; for risk in found.risks { diff --git a/native/git-protection/src/levels.rs b/native/git-protection/src/levels.rs index 87dcd33..375fc09 100644 --- a/native/git-protection/src/levels.rs +++ b/native/git-protection/src/levels.rs @@ -5,6 +5,7 @@ //! default branch, branches listed in `mothership.protectedBranch` and tags. See ADR-0025. use serde::Deserialize; +use std::collections::HashMap; use std::path::{Path, PathBuf}; /// How a force push or a remote deletion of a branch is checked, weakest first. @@ -21,9 +22,37 @@ pub enum Level { Forbid, } -/// Where the app keeps the table, relative to the home folder. -pub const TABLE_PATH: &str = "Library/Application Support/AgentWatch/git-branch-types.json"; -const TABLE_VERSION: u32 = 1; +const TABLE_FILE: &str = "git-branch-types.json"; + +fn settings_path() -> Option { + #[cfg(target_os = "macos")] + if let Some((folder, configuration)) = + option_env!("AGENT_WATCH_GIT_BUNDLE_POLICY").and_then(|value| value.split_once('/')) + { + // A profile can use a different HOME. A packaged helper follows the same account + // Application Support folder as the app, even when the app is closed. + let support = if let Some(path) = (configuration == "debug") + .then(|| std::env::var_os("AGENT_WATCH_SUPPORT_DIR").filter(|value| !value.is_empty())) + .flatten() + { + PathBuf::from(path) + } else { + nix::unistd::User::from_uid(nix::unistd::getuid()) + .ok()?? + .dir + .join("Library/Application Support") + }; + return Some(support.join(folder).join(TABLE_FILE)); + } + + std::env::var_os("HOME") + .filter(|home| !home.is_empty()) + .map(|home| { + PathBuf::from(home) + .join("Library/Application Support/AgentWatch") + .join(TABLE_FILE) + }) +} const MAX_TABLE_BYTES: u64 = 1024 * 1024; // Unknown fields are ignored, as the app's decoder ignores them, so both sides read one @@ -36,22 +65,81 @@ pub struct BranchType { } #[derive(Deserialize)] -struct Table { - version: u32, +struct LegacyTable { types: Vec, } -#[derive(Clone, Debug, Default)] -pub struct BranchTypes(Vec); +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +struct OperationRules { + force_push: Vec, + delete: Vec, +} + +impl OperationRules { + fn for_operation(&self, delete: bool) -> &[BranchType] { + if delete { + &self.delete + } else { + &self.force_push + } + } +} + +#[derive(Clone, Debug, Deserialize)] +pub struct BranchTypes { + enabled: bool, + global: OperationRules, + repositories: HashMap, +} + +impl Default for BranchTypes { + fn default() -> Self { + Self { + enabled: true, + global: OperationRules::default(), + repositories: HashMap::new(), + } + } +} + +#[derive(Clone, Copy)] +pub struct BranchRules<'a> { + global: &'a [BranchType], + local: &'a [BranchType], + default: Level, +} + +impl<'a> BranchRules<'a> { + pub fn has_none_or_forbid(self) -> bool { + self.global + .iter() + .chain(self.local) + .any(|rule| matches!(rule.level, Level::None | Level::Forbid)) + } + + pub fn selected(self, branch: &str) -> (Level, Option<&'a BranchType>) { + let matching = |rules: &'a [BranchType]| { + rules.iter().find(|rule| { + rule.patterns + .iter() + .any(|pattern| pattern_matches(pattern, branch)) + }) + }; + let global = matching(self.global); + let level = global.map_or(self.default, |rule| rule.level); + if let Some(local) = matching(self.local) + && local.level > level + { + return (local.level, Some(local)); + } + (level, global) + } +} impl BranchTypes { - /// The table of the home the agent runs with. Agents follow `HOME`, so a scratch home - /// gets no types, which is today's behaviour. pub fn load() -> Self { - std::env::var_os("HOME") - .filter(|home| !home.is_empty()) - .map(|home| Self::load_from(&PathBuf::from(home).join(TABLE_PATH))) - .unwrap_or_default() + settings_path().map_or_else(Self::default, |path| Self::load_from(&path)) } /// A missing or unreadable file means no types. Never a lower level: with no types every @@ -74,25 +162,43 @@ impl BranchTypes { } pub fn parse(text: &str) -> Option { - let table: Table = serde_json::from_str(text).ok()?; - (table.version == TABLE_VERSION).then_some(Self(table.types)) + #[derive(Deserialize)] + struct Version { + version: u32, + } + + match serde_json::from_str::(text).ok()?.version { + 1 => { + let old: LegacyTable = serde_json::from_str(text).ok()?; + Some(Self { + global: OperationRules { + force_push: old.types.clone(), + delete: old.types, + }, + ..Self::default() + }) + } + 2 => serde_json::from_str(text).ok(), + _ => None, + } } - /// Whether any type can let a push through or refuse it without a window. Without one, - /// the hook has nothing to look up. - pub fn has_none_or_forbid(&self) -> bool { - self.0 - .iter() - .any(|kind| matches!(kind.level, Level::None | Level::Forbid)) + pub fn enabled(&self) -> bool { + self.enabled } - /// The first type with a pattern that matches the short branch name. - pub fn matching(&self, branch: &str) -> Option<&BranchType> { - self.0.iter().find(|kind| { - kind.patterns - .iter() - .any(|pattern| pattern_matches(pattern, branch)) - }) + pub fn has_repository_rules(&self) -> bool { + !self.repositories.is_empty() + } + + pub fn rules(&self, delete: bool, repository: Option<&str>) -> BranchRules<'_> { + BranchRules { + global: self.global.for_operation(delete), + local: repository + .and_then(|key| self.repositories.get(key)) + .map_or(&[], |rules| rules.for_operation(delete)), + default: if delete { Level::Click } else { Level::Name }, + } } } @@ -121,16 +227,31 @@ pub fn pattern_matches(pattern: &str, name: &str) -> bool { pattern[p..].iter().all(|&c| c == '*') } -/// The level of a force push or deletion of a branch, before the floor. -/// -/// A branch no type matches keeps the behaviour it had before types existed: one click for a -/// deletion, a confirmation plus the repository name for a force push. -pub fn chosen(types: &BranchTypes, branch: &str, delete: bool) -> (Level, Option) { - match types.matching(branch) { - Some(kind) => (kind.level, Some(kind.name.clone())), - None if delete => (Level::Click, None), - None => (Level::Name, None), +/// The level of a force push or deletion, before protected-branch checks. +pub fn chosen( + types: &BranchTypes, + branch: &str, + delete: bool, + repo: Option<&str>, +) -> (Level, Option) { + let (level, rule) = types.rules(delete, repo).selected(branch); + (level, rule.map(|rule| rule.name.clone())) +} + +pub const COMMON_DIRECTORY_ARGS: &[&str] = &["rev-parse", "--git-common-dir"]; + +pub fn canonical_directory(folder: &Path, path: &str) -> Result { + if path.is_empty() { + return Err("Git did not return the repository’s common directory.".into()); } + let resolved = folder + .join(path) + .canonicalize() + .map_err(|_| "Git could not resolve the repository’s common directory.")?; + resolved + .into_os_string() + .into_string() + .map_err(|_| "The repository's directory is not valid UTF-8.".into()) } /// The floor raises a protected branch to `name`; nothing lowers it. @@ -174,12 +295,25 @@ mod tests { let types = BranchTypes::parse(include_str!("../tests/fixtures/branch-types.json")).unwrap(); assert_eq!( - chosen(&types, "fix/typo", true), + chosen(&types, "fix/typo", true, None), (Level::Click, Some("Features".into())) ); - assert_eq!(chosen(&types, "hotfix/1", false).0, Level::Name); - assert_eq!(chosen(&types, "tmp/x", false).0, Level::None); - assert_eq!(chosen(&types, "archive/2025", true).0, Level::Forbid); + assert_eq!(chosen(&types, "hotfix/1", false, None).0, Level::Name); + assert_eq!(chosen(&types, "tmp/x", false, None).0, Level::None); + assert_eq!(chosen(&types, "archive/2025", true, None).0, Level::Forbid); + } + + #[test] + fn operations_are_independent_and_repositories_can_only_strengthen_them() { + let types = + BranchTypes::parse(include_str!("../tests/fixtures/branch-rules-v2.json")).unwrap(); + let repo = Some("/work/agent-watch/.git"); + assert!(types.enabled()); + assert_eq!(chosen(&types, "release/1", false, repo).0, Level::Forbid); + assert_eq!(chosen(&types, "release/1", true, repo).0, Level::Name); + assert_eq!(chosen(&types, "agent/kept", false, repo).0, Level::Name); + assert_eq!(chosen(&types, "agent/kept", true, repo).0, Level::Forbid); + assert_eq!(chosen(&types, "agent/kept", true, None).0, Level::None); } #[test] @@ -189,10 +323,21 @@ mod tests { {"name":"Everything","patterns":["*"],"level":"forbid"}, {"name":"Late","patterns":["agent/x"],"level":"name"}]"#, ); - assert_eq!(types.matching("agent/x").unwrap().name, "Drafts"); - assert_eq!(types.matching("feature/y").unwrap().name, "Everything"); assert_eq!( - chosen(&types, "agent/x", true), + types.rules(true, None).selected("agent/x").1.unwrap().name, + "Drafts" + ); + assert_eq!( + types + .rules(true, None) + .selected("feature/y") + .1 + .unwrap() + .name, + "Everything" + ); + assert_eq!( + chosen(&types, "agent/x", true, None), (Level::None, Some("Drafts".into())) ); } @@ -207,7 +352,7 @@ mod tests { ); let levels: Vec<_> = ["a", "b", "c", "d"] .iter() - .map(|branch| chosen(&types, branch, false).0) + .map(|branch| chosen(&types, branch, false, None).0) .collect(); assert_eq!( levels, @@ -220,8 +365,14 @@ mod tests { #[test] fn a_branch_without_a_type_keeps_todays_behaviour() { for types in [BranchTypes::default(), table("[]")] { - assert_eq!(chosen(&types, "feature/x", true), (Level::Click, None)); - assert_eq!(chosen(&types, "feature/x", false), (Level::Name, None)); + assert_eq!( + chosen(&types, "feature/x", true, None), + (Level::Click, None) + ); + assert_eq!( + chosen(&types, "feature/x", false, None), + (Level::Name, None) + ); } } @@ -249,8 +400,11 @@ mod tests { let newer = BranchTypes::parse( r#"{"version":1,"types":[{"name":"A","patterns":["a"],"level":"none","colour":"red"}]}"#, ); - assert_eq!(newer.unwrap().matching("a").unwrap().level, Level::None); + assert_eq!( + newer.unwrap().rules(true, None).selected("a").0, + Level::None + ); let missing = BranchTypes::load_from(Path::new("/nonexistent/agent-watch/types.json")); - assert!(missing.matching("anything").is_none()); + assert!(missing.rules(true, None).selected("anything").1.is_none()); } } diff --git a/native/git-protection/src/push.rs b/native/git-protection/src/push.rs index cf99689..49295a3 100644 --- a/native/git-protection/src/push.rs +++ b/native/git-protection/src/push.rs @@ -20,7 +20,7 @@ pub fn execute( } let confirmed = || -> Result<(), String> { cancel.check(deadline)?; - // At `none` the person chose no window for this branch type, so nothing is asked. + // At `none` the person chose no window for this branch rule, so nothing is asked. let risks = if plan.level == Level::None { &[][..] } else { @@ -91,6 +91,6 @@ fn forbidden(plan: &Plan) -> String { .unwrap_or(&plan.destination); let kind = plan.branch_type.as_deref().unwrap_or_default(); format!( - "Agent Watch settings forbid the {operation} of branch '{branch}' (branch type '{kind}'). Nothing was pushed and no window was shown. Do not call AgentWatchGit for it again." + "Agent Watch settings forbid the {operation} of branch '{branch}' (branch rule '{kind}'). Nothing was pushed and no window was shown. Do not call AgentWatchGit for it again." ) } diff --git a/native/git-protection/tests/fixtures/branch-rules-v2.json b/native/git-protection/tests/fixtures/branch-rules-v2.json new file mode 100644 index 0000000..211361b --- /dev/null +++ b/native/git-protection/tests/fixtures/branch-rules-v2.json @@ -0,0 +1,25 @@ +{ + "enabled": true, + "global": { + "forcePush": [ + { "name": "Release", "patterns": ["release/*"], "level": "forbid" }, + { "name": "Draft", "patterns": ["agent/*"], "level": "none" } + ], + "delete": [ + { "name": "Release", "patterns": ["release/*"], "level": "name" }, + { "name": "Draft", "patterns": ["agent/*"], "level": "none" } + ] + }, + "repositories": { + "/work/agent-watch/.git": { + "forcePush": [ + { "name": "Keep draft", "patterns": ["agent/kept"], "level": "name" } + ], + "delete": [ + { "name": "Keep draft", "patterns": ["agent/kept"], "level": "forbid" }, + { "name": "Weaker release", "patterns": ["release/*"], "level": "click" } + ] + } + }, + "version": 2 +} diff --git a/native/git-protection/tests/git_guard.rs b/native/git-protection/tests/git_guard.rs index 57327df..35b0612 100644 --- a/native/git-protection/tests/git_guard.rs +++ b/native/git-protection/tests/git_guard.rs @@ -594,7 +594,7 @@ fn branch_types_decide_force_pushes_and_deletions_in_the_hook() { let reason = denial(&check(command)); assert!(reason.contains(refusal), "{reason}"); assert!( - reason.contains("forbidden by branch type 'Locked'"), + reason.contains("forbidden by branch rule 'Locked'"), "{reason}" ); assert!(reason.contains("run it in a terminal"), "{reason}"); @@ -605,7 +605,7 @@ fn branch_types_decide_force_pushes_and_deletions_in_the_hook() { let both = denial(&check( "git push -f origin HEAD:refs/heads/locked/x HEAD:refs/heads/feature/y", )); - assert!(both.contains("forbidden by branch type 'Locked'"), "{both}"); + assert!(both.contains("forbidden by branch rule 'Locked'"), "{both}"); assert!( both.contains("force push. For one intended reference"), "{both}" @@ -661,3 +661,67 @@ fn without_a_readable_table_the_hook_checks_as_before() { } } } + +#[test] +fn disabling_and_enabling_applies_to_both_clients_without_reinstalling() { + let bundle = Bundle::new(); + let repo = bundle.repo("switch"); + let payload = json!({ + "cwd": repo, + "tool_input": { "command": "git push origin --delete refs/heads/main" }, + }) + .to_string(); + let mut rules: Value = + serde_json::from_str(include_str!("fixtures/branch-rules-v2.json")).unwrap(); + for (enabled, has_denial) in [(true, true), (false, false), (true, true)] { + rules["enabled"] = json!(enabled); + bundle.branch_types(&rules.to_string()); + for host in ["claude", "codex"] { + assert_eq!(!bundle.invoke(host, &payload).is_empty(), has_denial); + } + } + // An invalid file carrying a false flag cannot silently turn protection off. + rules["enabled"] = json!(false); + rules["global"]["delete"][0]["level"] = json!("unknown"); + bundle.branch_types(&rules.to_string()); + for host in ["claude", "codex"] { + denial(&bundle.invoke(host, &payload)); + } +} + +#[test] +fn linked_worktrees_share_the_repository_rule_for_the_selected_operation() { + let bundle = Bundle::new(); + let repo = bundle.repo_with_remote(); + let linked = bundle.root.path().join("linked"); + bundle.git( + &repo, + &["worktree", "add", "--detach", linked.to_str().unwrap()], + ); + let common = repo.join(".git").canonicalize().unwrap(); + let mut rules: Value = + serde_json::from_str(include_str!("fixtures/branch-rules-v2.json")).unwrap(); + let entries = rules["repositories"]["/work/agent-watch/.git"].take(); + rules["repositories"] = json!({common.to_str().unwrap(): entries}); + bundle.branch_types(&rules.to_string()); + + for host in ["claude", "codex"] { + for folder in [&repo, &linked] { + let check = |command| { + bundle.invoke( + host, + &json!({"cwd": folder, "tool_input": {"command": command}}).to_string(), + ) + }; + let blocked = denial(&check("git push origin --delete refs/heads/agent/kept")); + assert!( + blocked.contains("forbidden by branch rule 'Keep draft'"), + "{blocked}" + ); + let confirmed = denial(&check("git push -f origin HEAD:refs/heads/agent/kept")); + assert!(confirmed.contains("push ''"), "{confirmed}"); + assert!(!confirmed.contains("forbidden"), "{confirmed}"); + assert!(check("git push origin --delete refs/heads/agent/x").is_empty()); + } + } +} diff --git a/native/git-protection/tests/push.rs b/native/git-protection/tests/push.rs index 4345c44..4c2af7a 100644 --- a/native/git-protection/tests/push.rs +++ b/native/git-protection/tests/push.rs @@ -1550,7 +1550,7 @@ fn each_level_asks_for_its_own_windows() { assert_eq!(result["status"], "not_pushed", "{result}"); assert_eq!(prompts, 0); let message = result["message"].as_str().unwrap(); - assert!(message.contains("branch type 'Locked'"), "{message}"); + assert!(message.contains("branch rule 'Locked'"), "{message}"); assert!(message.contains("no window was shown"), "{message}"); assert!(result["manual_command"].is_string()); } @@ -1705,3 +1705,37 @@ fn a_level_raised_during_the_window_stops_the_push() { ); assert!(fixture.remote_refs().contains(branch)); } + +#[test] +fn the_direct_executor_keeps_repository_rules_when_hooks_are_off() { + let fixture = Fixture::new(false); + let branch = "agent/kept"; + let reference = format!("refs/heads/{branch}"); + fixture.seed(&reference); + let before = fixture.remote_refs(); + let common = fixture.repo.join(".git").canonicalize().unwrap(); + let mut rules: Value = + serde_json::from_str(include_str!("fixtures/branch-rules-v2.json")).unwrap(); + let entries = rules["repositories"]["/work/agent-watch/.git"].take(); + rules["repositories"] = json!({common.to_str().unwrap(): entries}); + rules["enabled"] = json!(false); + fixture.branch_types(&rules.to_string()); + let request = json!({"repository":fixture.repo,"destination":reference,"delete":true}); + let output = Command::new(env!("CARGO_BIN_EXE_agent-watch-git")) + .args(["push", &request.to_string()]) + .env("HOME", &fixture.home) + .output() + .unwrap(); + assert!(!output.status.success()); + let result: Value = serde_json::from_slice(&output.stdout) + .unwrap_or_else(|error| panic!("{error}: {}", String::from_utf8_lossy(&output.stderr))); + assert_eq!(result["status"], "not_pushed", "{result}"); + assert!( + result["message"] + .as_str() + .unwrap() + .contains("branch rule 'Keep draft'"), + "{result}" + ); + assert_eq!(fixture.remote_refs(), before); +}