diff --git a/README.md b/README.md index a1f91c0..800dd2a 100644 --- a/README.md +++ b/README.md @@ -232,8 +232,9 @@ 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. +**Force Push**, or **Delete Remote Branch**. In **All repositories**, edit **Default** or +**Protected branches**, then confirm the change. A repository can require a stricter check. +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 diff --git a/Sources/AgentWatchApp/GitProtectionPane.swift b/Sources/AgentWatchApp/GitProtectionPane.swift index fbe0459..28de0b8 100644 --- a/Sources/AgentWatchApp/GitProtectionPane.swift +++ b/Sources/AgentWatchApp/GitProtectionPane.swift @@ -21,6 +21,12 @@ struct GitProtectionPane: View { let index: Int? let count: Int } + private struct DefaultSelection: Identifiable { + let rule: GitProtectionRules.DefaultRule + let operation: GitBranchOperation + let level: GitCheckLevel + var id: GitProtectionRules.DefaultRule { rule } + } @State private var rules: GitProtectionRules? @State private var settingsError: String? @@ -39,6 +45,7 @@ struct GitProtectionPane: View { @State private var readingPreview = false @State private var confirmsLegacyRemoval = false @State private var editor: EditorSelection? + @State private var defaultEditor: DefaultSelection? private var enabled: Bool { rules?.enabled ?? true } private var activeRepository: GitProtectionRepository? { scope == .repository ? rulesRepository : nil } @@ -50,7 +57,7 @@ struct GitProtectionPane: View { return rules?.global[operation] ?? [] } private var canAddRule: Bool { - rules != nil && operation != .push && (scope == .all || activeRepository != nil) + rules != nil && (scope == .all || activeRepository != nil) } private var previewRequest: PreviewRequest { PreviewRequest(repository: previewRepository, branch: branch) } @@ -66,7 +73,6 @@ struct GitProtectionPane: View { } .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( @@ -78,6 +84,16 @@ struct GitProtectionPane: View { change: { try edit(selection, change: $0) } ) } + .sheet(item: $defaultEditor) { selection in + GitProtectionDefaultEditor( + rule: selection.rule, operation: selection.operation, currentLevel: selection.level + ) { + level in + guard var updated = rules else { throw SettingsError.missingDirectory } + updated.setDefaultLevel(level, for: selection.rule, operation: selection.operation) + try save(updated) + } + } .alert("Turn off Git Protection?", isPresented: $confirmsDisable) { Button("Cancel", role: .cancel) {}.keyboardShortcut(.defaultAction) Button("Turn Off Protection", role: .destructive) { setEnabled(false) } @@ -90,7 +106,7 @@ struct GitProtectionPane: View { 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.") + Text("Other rules and the remote’s default branch can still require a check.") } } @@ -132,31 +148,18 @@ struct GitProtectionPane: View { .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) } - } + Picker("Rule scope", selection: $scope) { + Text("All repositories").tag(Scope.all) + Text("One repository…").tag(Scope.repository) } - LabeledContent { - Text(operation.defaultLevel.title) - } label: { - Heading(title: scope == .all ? "Default" : "Inherited default", hint: "Branches with no matching rule") + if scope == .repository { + LabeledContent("Repository") { + repositoryButton(rulesRepository, use: .rules) + } + if let folderError, folderUse == .rules { errorText(folderError) } } - 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(GitProtectionRules.DefaultRule.allCases) { rule in + defaultRow(rule) } ForEach(currentRules) { rule in let patterns = rule.patterns.joined(separator: " ") @@ -174,14 +177,12 @@ struct GitProtectionPane: View { .disabled(rules == nil) } } - if operation != .push { - Button { - openEditor() - } label: { - Label("Add \(operation.ruleTitle)…", systemImage: "plus") - } - .disabled(!canAddRule) + Button { + openEditor() + } label: { + Label("Add \(operation.ruleTitle)…", systemImage: "plus") } + .disabled(!canAddRule) } header: { HStack { Text("Branch rules") @@ -192,15 +193,37 @@ struct GitProtectionPane: View { } } footer: { Footnote( - 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." + scope == .all + ? "The first matching pattern applies. Its check can strengthen the Protected branches rule." + : "The first matching repository rule can make the global check stricter. Linked working copies use the same rules." ) } } + private func defaultRow(_ rule: GitProtectionRules.DefaultRule) -> some View { + let level = rules?.defaultLevel(rule, for: operation) ?? rule.factoryLevel(for: operation) + return LabeledContent { + HStack { + Text(level.title) + if scope == .all { + Button("Edit…") { + defaultEditor = DefaultSelection(rule: rule, operation: operation, level: level) + } + .accessibilityLabel("Edit \(rule.title) for \(operation.title)") + .disabled(rules == nil) + } + } + } label: { + Heading( + title: rule == .unmatched && scope == .repository ? "Inherited default" : rule.title, + hint: rule == .unmatched + ? "Other branches with no matching rule" + : operation == .push + ? "main and master" + : "main, master, the remote’s default branch, and branches protected in Git") + } + } + private var branchPreview: some View { Section("Preview a branch") { LabeledContent("Repository") { @@ -228,21 +251,19 @@ struct GitProtectionPane: View { } private func previewResult(_ evidence: GitDeletionPreview) -> (level: GitCheckLevel, reason: String) { - let choice = (rules ?? GitProtectionRules()).level( - for: operation, branch: branch, repository: previewRepository?.key) + let settings = rules ?? GitProtectionRules() 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 + let key = previewRepository?.key + let choice = settings.level(for: operation, branch: branch, repository: key, protected: protected) + var reason = + choice.source.map { "Matches rule “\($0)”." } + ?? (protected ? "Uses the Protected branches rule." : "Uses the default for \(operation.title).") + if operation != .push && evidence == .dependsOnRemote { + let remoteLevel = settings.level(for: operation, branch: branch, repository: key, protected: true).level + if remoteLevel != choice.level { + reason += " If this is the remote’s default branch: \(remoteLevel.title)." } } - 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) } @@ -374,7 +395,7 @@ struct GitProtectionPane: View { } scoped[selection.operation] = list if let key { - updated.repositories[key] = scoped.forcePush.isEmpty && scoped.delete.isEmpty ? nil : scoped + updated.repositories[key] = scoped.isEmpty ? nil : scoped } else { updated.global = scoped } diff --git a/Sources/AgentWatchApp/GitProtectionRuleEditor.swift b/Sources/AgentWatchApp/GitProtectionRuleEditor.swift index abf4ec0..1f6d585 100644 --- a/Sources/AgentWatchApp/GitProtectionRuleEditor.swift +++ b/Sources/AgentWatchApp/GitProtectionRuleEditor.swift @@ -94,6 +94,79 @@ struct GitProtectionRuleEditor: View { } } +struct GitProtectionDefaultEditor: View { + let rule: GitProtectionRules.DefaultRule + let operation: GitBranchOperation + let currentLevel: GitCheckLevel + let save: (GitCheckLevel) throws -> Void + @Environment(\.dismiss) private var dismiss + @State private var level = GitCheckLevel.name + @State private var confirmsChange = false + @State private var errorMessage: String? + + var body: some View { + VStack(alignment: .leading, spacing: 14) { + VStack(alignment: .leading, spacing: 4) { + Text("Edit \(rule.title)").font(.headline) + Text("All repositories · \(operation.title)").foregroundStyle(.secondary) + } + Picker("Agent action", selection: $level) { + ForEach(GitCheckLevel.allCases, id: \.self) { level in + Text(level.title).tag(level) + } + } + if let errorMessage { Text(errorMessage).font(.caption).foregroundStyle(.red) } + HStack { + Button("Use Original Default") { level = rule.factoryLevel(for: operation) } + .disabled(level == rule.factoryLevel(for: operation)) + Spacer() + Button("Cancel", role: .cancel) { dismiss() }.keyboardShortcut(.cancelAction) + Button("Save Rule…") { confirmsChange = true } + .keyboardShortcut(.defaultAction) + .disabled(level == currentLevel) + } + } + .padding(20) + .frame(width: 460) + .onAppear { level = currentLevel } + .alert("Change \(rule.title) for \(operation.title)?", isPresented: $confirmsChange) { + Button("Cancel", role: .cancel) {}.keyboardShortcut(.defaultAction) + Button("Change Rule", role: level < currentLevel ? .destructive : nil) { + do { + try save(level) + dismiss() + } catch { + errorMessage = "Could not save the rule. \(error.localizedDescription)" + } + } + } message: { + Text( + "This changes Git Protection for all repositories and connected agent profiles. \(currentLevel.title) → \(level.title). \(consequence)" + ) + } + } + + private var consequence: String { + if level < currentLevel { + switch operation { + case .push: return "Agents may send changes to shared branches with fewer checks." + case .forcePush: return "Agents may overwrite shared branch history with fewer checks." + case .delete: return "Agents may delete remote branches with fewer checks." + } + } + return "Future matching commands may require an extra confirmation or be blocked." + } +} + +extension GitProtectionRules.DefaultRule { + var title: String { + switch self { + case .unmatched: "Default" + case .protected: "Protected branches" + } + } +} + extension GitBranchOperation { var title: String { switch self { diff --git a/Sources/AgentWatchGit/GitProtectionRules.swift b/Sources/AgentWatchGit/GitProtectionRules.swift index c11ad7e..2d2e5dc 100644 --- a/Sources/AgentWatchGit/GitProtectionRules.swift +++ b/Sources/AgentWatchGit/GitProtectionRules.swift @@ -17,22 +17,25 @@ public enum GitBranchOperation: String, CaseIterable, Identifiable, Sendable { /// Shared with AgentWatchGit. Version 1 applied each type to both editable operations. public struct GitProtectionRules: Codable, Equatable, Sendable { public struct Rules: Codable, Equatable, Sendable { + private var push: [GitBranchType]? public var forcePush: [GitBranchType] = [] public var delete: [GitBranchType] = [] public init() {} + public var isEmpty: Bool { [GitBranchOperation.push, .forcePush, .delete].allSatisfy { self[$0].isEmpty } } + public subscript(operation: GitBranchOperation) -> [GitBranchType] { get { switch operation { - case .push: [] + case .push: push ?? [] case .forcePush: forcePush case .delete: delete } } set { switch operation { - case .push: break + case .push: push = newValue.isEmpty ? nil : newValue case .forcePush: forcePush = newValue case .delete: delete = newValue } @@ -46,6 +49,8 @@ public struct GitProtectionRules: Codable, Equatable, Sendable { public var enabled: Bool public var global: Rules public var repositories: [String: Rules] + private var defaults: LevelOverrides? + private var protectedBranches: LevelOverrides? public init() { version = 2 @@ -54,6 +59,35 @@ public struct GitProtectionRules: Codable, Equatable, Sendable { repositories = [:] } + public enum DefaultRule: CaseIterable, Identifiable, Sendable { + case unmatched, protected + + public var id: Self { self } + + public func factoryLevel(for operation: GitBranchOperation) -> GitCheckLevel { + self == .protected ? .name : operation.defaultLevel + } + } + + public func defaultLevel(_ rule: DefaultRule, for operation: GitBranchOperation) -> GitCheckLevel { + let levels = rule == .protected ? protectedBranches : defaults + return levels?[operation] ?? rule.factoryLevel(for: operation) + } + + public mutating func setDefaultLevel(_ level: GitCheckLevel, for rule: DefaultRule, operation: GitBranchOperation) { + let override = level == rule.factoryLevel(for: operation) ? nil : level + switch rule { + case .unmatched: + var levels = defaults ?? LevelOverrides() + levels[operation] = override + defaults = levels.isEmpty ? nil : levels + case .protected: + var levels = protectedBranches ?? LevelOverrides() + levels[operation] = override + protectedBranches = levels.isEmpty ? nil : levels + } + } + public static func load(from url: URL) throws -> Self { let file: FileHandle do { @@ -90,21 +124,48 @@ public struct GitProtectionRules: Codable, Equatable, Sendable { } public func level( - for operation: GitBranchOperation, branch: String, repository: String? + for operation: GitBranchOperation, branch: String, repository: String?, protected: Bool = false ) -> (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 + let fallback = defaultLevel(protected ? .protected : .unmatched, for: operation) + let level = globalRule?.level ?? fallback if let repository, let rules = repositories[repository], let local = match(rules[operation]), - local.level > level + local.level > (protected ? max(level, fallback) : level) { return (local.level, local.name) } + if protected && level < fallback { return (fallback, nil) } return (level, globalRule?.name) } + private struct LevelOverrides: Codable, Equatable, Sendable { + var push: GitCheckLevel? + var forcePush: GitCheckLevel? + var delete: GitCheckLevel? + + var isEmpty: Bool { push == nil && forcePush == nil && delete == nil } + + subscript(operation: GitBranchOperation) -> GitCheckLevel? { + get { + switch operation { + case .push: push + case .forcePush: forcePush + case .delete: delete + } + } + set { + switch operation { + case .push: push = newValue + case .forcePush: forcePush = newValue + case .delete: delete = newValue + } + } + } + } + private struct Version: Decodable { let version: Int } private enum Failure: LocalizedError { diff --git a/Tests/AgentWatchGitTests/GitBranchTypesTests.swift b/Tests/AgentWatchGitTests/GitBranchTypesTests.swift index ccd789f..764dde6 100644 --- a/Tests/AgentWatchGitTests/GitBranchTypesTests.swift +++ b/Tests/AgentWatchGitTests/GitBranchTypesTests.swift @@ -132,4 +132,35 @@ final class GitBranchTypesTests: XCTestCase { XCTAssertEqual(plain.level, .click) XCTAssertNil(plain.type) } + + func testEditedDefaultsRoundTripAndOnlyChangeTheirOwnOperations() throws { + let url = try scratch().appendingPathComponent(GitProtectionRules.fileName) + var config = GitProtectionRules() + config.setDefaultLevel(.click, for: .unmatched, operation: .push) + config.setDefaultLevel(.forbid, for: .unmatched, operation: .forcePush) + config.setDefaultLevel(.name, for: .unmatched, operation: .delete) + config.setDefaultLevel(.none, for: .protected, operation: .push) + config.setDefaultLevel(.click, for: .protected, operation: .forcePush) + config.setDefaultLevel(.forbid, for: .protected, operation: .delete) + config.global[.push] = [GitBranchType(name: "Sandbox", patterns: ["sandbox/*"], level: .none)] + try config.save(to: url) + + let expected = try JSONSerialization.jsonObject(with: fixture("branch-rules-defaults.json")) as? NSDictionary + let written = try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? NSDictionary + XCTAssertEqual(written, expected) + + config = try GitProtectionRules.load(from: url) + XCTAssertEqual(config.level(for: .push, branch: "main", repository: nil, protected: true).level, .none) + XCTAssertEqual(config.level(for: .forcePush, branch: "main", repository: nil, protected: true).level, .click) + XCTAssertEqual(config.level(for: .delete, branch: "main", repository: nil, protected: true).level, .forbid) + XCTAssertEqual(config.level(for: .forcePush, branch: "feature/x", repository: nil).level, .forbid) + XCTAssertEqual(config.level(for: .push, branch: "sandbox/x", repository: nil).level, .none) + + config.setDefaultLevel(.name, for: .protected, operation: .push) + try config.save(to: url) + config = try GitProtectionRules.load(from: url) + XCTAssertEqual(config.level(for: .push, branch: "main", repository: nil, protected: true).level, .name) + XCTAssertEqual(config.level(for: .push, branch: "feature/x", repository: nil).level, .click) + XCTAssertEqual(config.level(for: .delete, branch: "main", repository: nil, protected: true).level, .forbid) + } } 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 05a5310..078e3f6 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 @@ -1,6 +1,6 @@ # Тип ветки выбирает проверку, но не ниже пола -**Статус:** принято 2026-11-23. +**Статус:** частично заменено [ADR-0029](0029-branch-defaults-are-editable.md) — уровень защищённых веток можно менять. Общий переключатель и отдельные правила операций описаны в [ADR-0028](0028-git-protection-settings-are-shared-by-agent-profiles.md). 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 index 6245b06..6d9137b 100644 --- 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 @@ -1,6 +1,6 @@ # Защита Git использует общие настройки профилей агента -**Статус:** принято 2026-11-26. +**Статус:** частично заменено [ADR-0029](0029-branch-defaults-are-editable.md) — общие уровни по умолчанию настраиваются. [ADR-0025](0025-a-branch-type-chooses-the-check-above-a-floor.md) задаёт нижнюю границу проверки защищённых веток. В интерфейсе одна строка меняла два разных действия, а правило репозитория diff --git a/docs/adr/0029-branch-defaults-are-editable.md b/docs/adr/0029-branch-defaults-are-editable.md new file mode 100644 index 0000000..91719bf --- /dev/null +++ b/docs/adr/0029-branch-defaults-are-editable.md @@ -0,0 +1,20 @@ +# Общие уровни защиты веток можно менять + +**Статус:** принято 2026-11-28. + +Здесь решение о редактировании общих уровней и его границе безопасности. Порядок действий +в интерфейсе описан в [правилах веток](../git-protection.md#правила-веток). + +У обычной отправки, принудительной отправки и удаления свой уровень для защищённых веток +и свой уровень для остальных веток без совпавшего шаблона. Общий шаблон выбирает уровень +для обычной ветки и может усилить уровень защищённой. Подключённый репозиторий может +усилить итоговое правило. Исходные значения совпадают с поведением [ADR-0025](0025-a-branch-type-chooses-the-check-above-a-floor.md) +и [ADR-0028](0028-git-protection-settings-are-shared-by-agent-profiles.md). + +Оба общих уровня можно как усилить, так и ослабить. Каждое изменение сохраняется после +отдельного подтверждения с текущим и новым уровнем. Выбор состава защищённых веток остаётся +частью проверки Git. Правила меток остаются отдельными. + +Теперь проверка защищённой ветки зависит от пользовательского файла. Диалог защищает от +случайного изменения из интерфейса. Файл доступен агенту с правами пользователя, поэтому +обязательные ограничения для всех клиентов задаются на сервере Git. diff --git a/docs/git-protection.md b/docs/git-protection.md index 84c48ab..f3fa161 100644 --- a/docs/git-protection.md +++ b/docs/git-protection.md @@ -29,13 +29,17 @@ Claude хранит команду в `settings.json` своего профил В `Branch rules` сначала выберите действие: -- `Push` показывает встроенные правила обычной отправки. Для `main` и `master` нужно подтверждение - и имя репозитория. Другие ветки по умолчанию проходят без окна. Если назначение нельзя точно - определить по команде, обработчик просит агента указать его явно. -- `Force Push` задаёт правила принудительной отправки. Ветка без совпадения требует подтверждения - и имени репозитория. -- `Delete Remote Branch` задаёт правила удаления ветки на сервере. Ветка без совпадения требует - одного подтверждения. +- `Push` — обычная отправка. Исходное правило для остальных веток разрешает её без окна. +- `Force Push` — принудительная отправка. Исходное правило для остальных веток требует + подтверждения и имени репозитория. +- `Delete Remote Branch` — удаление ветки на сервере. Исходное правило для остальных веток + требует одного подтверждения. + +Для каждого действия в `All repositories` можно изменить `Default` для веток без совпавшего +шаблона и `Protected branches` для защищённых веток. Изначально защищённые ветки требуют +подтверждения и имени репозитория. После выбора нового уровня отдельное окно показывает, +что изменится для всех репозиториев и профилей. `Cancel` оставляет сохранённое правило. +`Use Original Default` возвращает исходный уровень после подтверждения. | Действие агента | В файле | Что происходит | |---|---|---| @@ -51,9 +55,10 @@ Claude хранит команду в `settings.json` своего профил Выберите `One repository…`, если в конкретном репозитории нужна более строгая проверка. Первое совпавшее правило репозитория может усилить итоговый уровень. Например, `Confirm` в репозитории -усиливает общее `Allow`. Все связанные рабочие копии используют одни правила. `main`, `master`, основная ветка сервера, ветки из `mothership.protectedBranch` и метки -при принудительной отправке или удалении требуют как минимум подтверждения и имени репозитория. -Код проверяет эту границу, даже если шаблон разрешает действие без окна. +усиливает общее `Allow`. Все связанные рабочие копии используют одни правила. +Для `Push` защищены `main` и `master`. При принудительной отправке и удалении к ним добавляются +основная ветка сервера и ветки из `mothership.protectedBranch`. На таких ветках действует +уровень `Protected branches`, который совпавший шаблон может усилить. Метки проверяются отдельно. `Preview a Branch` показывает проверку для выбранного действия, репозитория и точного имени ветки. Пример работает без сети. Если результат зависит от основной ветки сервера, пример объясняет условие. @@ -70,9 +75,10 @@ Git также видно в примере. Точное локальное п Приложение записывает переключатель и таблицы в `~/Library/Application Support/AgentWatch/git-branch-types.json`. Версия 2 хранит общий переключатель, -отдельные таблицы `forcePush` и `delete` и правила репозиториев по их общей папке Git. Смена пути -репозитория меняет его ключ. При чтении файла версии 1 прежние правила используются для обеих -операций. Файл обновляется при первом сохранении из настроек. +таблицы `push`, `forcePush` и `delete`, правила репозиториев по их общей папке Git и изменённые +уровни в `defaults` и `protectedBranches`. Для отсутствующих полей действуют исходные настройки. +Смена пути репозитория меняет его ключ. При чтении файла версии 1 прежние правила используются +для принудительной отправки и удаления. Файл обновляется при первом сохранении из настроек. Установленный исполнитель использует домашнюю папку учётной записи macOS, даже если профиль агента запущен с другим `HOME`. В отладочной сборке запускайте приложение и обработчик с одинаковым @@ -85,9 +91,11 @@ Git также видно в примере. Точное локальное п Исполнитель `AgentWatchGit push` знает точное назначение и применяет уровень всегда. При `none` он выполняет операцию без окна, при `forbid` отказывает без окна и возвращает команду для терминала. Если таблица изменилась, пока окно было открыто, и уровень вырос, операция останавливается. +Явный вызов исполнителя для обычной ветки без правила сохраняет ввод имени репозитория, +пока для `Push` действует исходное значение `Default`. -Обработчик пропускает принудительную отправку или удаление при `none` только тогда, когда то, что -он прочитал, совпадает с тем, что увидит `git push`: +Обработчик применяет изменённые правила к обычной отправке, принудительной отправке и удалению. +Для `none` он пропускает команду, если может подтвердить, что `git push` увидит то же назначение: - **Команда одна.** Во вводе нет ничего, кроме `git push`: ни `cd`, ни `|`, ни `;`, ни присвоения переменной перед `git`, ни `git -C` или `git -c`. Иначе соседняя команда может переключить @@ -108,8 +116,9 @@ Git также видно в примере. Точное локальное п сопоставляет и полное имя по окончанию, и `refs/tags/refs/heads/x` забрал бы отправку. - **Подмодули не отправляются.** При `submodule.recurse` или `push.recurseSubmodules` в конфигурации окно остаётся: подмодуль уходит на сервер, который проверка не спрашивает. -- **Пол проверен у сервера.** Основную ветку обработчик спрашивает у сервера так же, как - исполнитель, и читает `mothership.protectedBranch` тем же запросом. Сервер должен быть описан в +- **Защищённость ветки определена.** Если уровень принудительной отправки или удаления зависит от + статуса ветки, обработчик спрашивает основную ветку у сервера и читает + `mothership.protectedBranch`, как и исполнитель. Сервер должен быть описан в конфигурации Git (`remote.<имя>.url`): сервер из старых файлов `.git/branches` и `.git/remotes` приносит свои правила отправки, которых проверка не видит. Это правило действует и для `AgentWatchGit push`. @@ -121,10 +130,10 @@ Git также видно в примере. Точное локальное п команде, отправка по настройкам Git) проверяются как раньше при любом уровне. Обработчик проверяет команды, которые он узнаёт, и не заменяет песочницу: отправку через псевдоним -Git, `=git` в zsh или `xcrun git` он не распознаёт, как и до правил веток. Путь без окна не добавляет -нового способа задеть пол, но против агента, который нарочно обходит проверку, гарантия — только -исполнитель и сервер Git -([ADR-0025](adr/0025-a-branch-type-chooses-the-check-above-a-floor.md)). +Git, `=git` в zsh или `xcrun git` он не распознаёт. Агент также работает с правами пользователя, +которому доступен файл правил. Для ограничений, обязательных для всех клиентов, используйте +защиту веток на сервере Git +([ADR-0029](adr/0029-branch-defaults-are-editable.md)). Обработчик видит окружение агента, а не оболочки, в которой выполнится команда. Если оболочка получает `GIT_DIR` или `GIT_CONFIG_PARAMETERS` из файлов запуска, обработчик этого не знает. Так diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index c206897..c03fae4 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -59,9 +59,9 @@ Agent Watch и агентов. [План установки, управлени Режим у камеры и управление сном отложены до проверки основных сценариев. Настройки защиты Git показывают состояние обработчика каждого профиля и общий переключатель. -У принудительной отправки и удаления веток отдельные списки правил. Репозиторий может усилить -проверку. Встроенная граница для защищённых веток действует, пока защита включена -([ADR-0028](adr/0028-git-protection-settings-are-shared-by-agent-profiles.md)). Остаётся проверка +У обычной и принудительной отправки и удаления веток отдельные правила и уровни по умолчанию. +Общие уровни, включая уровень защищённых веток, меняются с подтверждением. Репозиторий может +усилить проверку ([ADR-0029](adr/0029-branch-defaults-are-editable.md)). Остаётся проверка окон `click` и `name`, отказа `forbid` и отправки без окна при `none` в обоих настольных клиентах. ## Наблюдение Skip в Codex diff --git a/native/git-protection/src/confirmation.rs b/native/git-protection/src/confirmation.rs index e1445ec..a6d6b2f 100644 --- a/native/git-protection/src/confirmation.rs +++ b/native/git-protection/src/confirmation.rs @@ -1,4 +1,5 @@ use crate::domain::{Plan, Risk}; +use crate::levels::Operation; use serde_json::{Value, json}; pub struct Form { @@ -53,10 +54,11 @@ fn context(plan: &Plan) -> String { fn risk_heading(plan: &Plan, risk: Risk) -> &'static str { match risk { + Risk::PushBranch => "Отправка в ветку", Risk::ProtectedBranch => "Основная ветка", Risk::ForceUpdate if plan.destination.starts_with("refs/tags/") => "Замена версии метки", Risk::ForceUpdate => "Принудительная отправка", - Risk::DeleteBranch => "Удаление обычной ветки", + Risk::DeleteBranch => "Удаление ветки", Risk::DeleteProtectedBranch => "Удаление защищённой ветки", Risk::DeleteTag => "Удаление метки", } @@ -66,6 +68,10 @@ pub fn risk_form(plan: &Plan, risk: Risk, index: usize, titled_choices: bool) -> let name = reference_name(plan); let heading = risk_heading(plan, risk); let (consequence, permission) = match risk { + Risk::PushBranch => ( + format!("Изменения будут отправлены в ветку «{name}» на сервере."), + "Отправить изменения", + ), Risk::ProtectedBranch => ( format!("Изменение основной ветки «{name}» может затронуть работу других участников."), "Разрешить изменение основной ветки", @@ -120,9 +126,10 @@ pub fn risk_form(plan: &Plan, risk: Risk, index: usize, titled_choices: bool) -> } else { "На этом шаге ничего не меняется. Далее: отдельное подтверждение следующего риска.".into() }; - let title = match (single_click, plan.delete) { - (true, true) => "Удалить ветку?", - (true, false) => "Перезаписать историю ветки?", + let title = match (single_click, plan.operation) { + (true, Operation::Delete) => "Удалить ветку?", + (true, Operation::ForcePush) => "Перезаписать историю ветки?", + (true, Operation::Push) => "Отправить изменения?", (false, _) => "Можно продолжить?", }; let mut decision = json!({"type":"string","title":title}); diff --git a/native/git-protection/src/domain.rs b/native/git-protection/src/domain.rs index 947c076..fe74448 100644 --- a/native/git-protection/src/domain.rs +++ b/native/git-protection/src/domain.rs @@ -1,4 +1,4 @@ -use crate::levels::Level; +use crate::levels::{Level, Operation}; use serde::Deserialize; use serde_json::{Value, json}; use std::path::Path; @@ -132,6 +132,7 @@ pub fn repository_name(url: &str) -> Result { #[derive(Clone, Copy, PartialEq, Eq)] pub enum Risk { + PushBranch, ProtectedBranch, ForceUpdate, DeleteBranch, @@ -150,6 +151,7 @@ pub struct Plan { pub new: String, pub old: String, pub delete: bool, + pub operation: Operation, pub risks: Vec, /// How many windows the operation needs. `Level::Name` for every operation the branch /// types do not govern, which is what those operations always asked for. @@ -174,12 +176,6 @@ pub fn quote(text: &str) -> String { } impl Plan { - /// Branch types decide the level of a force push or deletion of a branch, nothing else. - pub fn governed(&self) -> bool { - self.destination.starts_with("refs/heads/") - && (self.delete || self.risks.contains(&Risk::ForceUpdate)) - } - /// One window whose button runs the operation; there is no step with the repository name. pub fn single_click(&self) -> bool { self.level == Level::Click diff --git a/native/git-protection/src/git.rs b/native/git-protection/src/git.rs index f91682c..a42840a 100644 --- a/native/git-protection/src/git.rs +++ b/native/git-protection/src/git.rs @@ -1,5 +1,5 @@ use crate::domain::{Arguments, Plan, Risk, repository_name, valid_oid, valid_text}; -use crate::levels::{self, BranchTypes, Level}; +use crate::levels::{self, BranchTypes, Level, Operation}; use crate::process::{self, Cancellation, Output}; use std::ffi::OsString; use std::path::{Path, PathBuf}; @@ -206,16 +206,14 @@ impl Git { } } - /// The level of a force push or deletion of a branch. The remote is asked for its - /// default branch only when the chosen level is below the floor, so an operation the - /// branch types leave alone asks exactly what it asked before they existed. + /// Ask the remote for its default branch only when it changes the outcome. fn level( &self, repo: &str, url: &str, destination: &str, - delete: bool, - ) -> Result<(Level, Option), String> { + operation: Operation, + ) -> Result<(Level, Option, bool), String> { let branch = destination .strip_prefix("refs/heads/") .unwrap_or(destination); @@ -228,38 +226,46 @@ impl Git { } 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 { - chosen - }; - Ok((level, kind)) + let mut rules = types.rules(operation, common.as_deref()); + if operation == Operation::Push { + rules = rules.for_direct_push(); + } + let protected = main_branch(destination) + || (operation != Operation::Push + && rules.depends_on_protection(branch) + && self.protected_branch(repo, url, destination)?); + let (level, rule) = rules.selected(branch, protected); + Ok((level, rule.map(|rule| rule.name.clone()), protected)) } - /// The floor for the hook: whether `main`, `master`, the remote's default branch or a - /// project rule protects the branch, asked through the same checked remote as a push. - /// /// Git matches even a full `refs/heads/x` against the remote's refs by suffix, so a remote - /// ref such as `refs/tags/refs/heads/x` would take the push: any listed ref other than the - /// branch itself counts as protected, as it stops a push. - pub fn protected(&self, repo: &str, remote: &str, branch: &str) -> Result { + /// ref such as `refs/tags/refs/heads/x` makes the destination ambiguous. + pub fn push_destination( + &self, + repo: &str, + remote: &str, + destination: &str, + check_remote_head: bool, + ) -> Result, String> { let (root, _, url) = self.identity(repo, remote)?; - let destination = format!("refs/heads/{branch}"); - if self.protected_branch(&root, &url, &destination)? { - return Ok(true); - } - let listing = self.read(&root, &["ls-remote", "--refs", "--", &url, &destination])?; - Ok(listing + let listing = self.read(&root, &["ls-remote", "--refs", "--", &url, destination])?; + if listing .lines() - .any(|line| line.split_once('\t').map(|(_, name)| name) != Some(destination.as_str()))) + .any(|line| line.split_once('\t').map(|(_, name)| name) != Some(destination)) + { + return Ok(None); + } + Ok(Some( + main_branch(destination) + || (check_remote_head && self.protected_branch(&root, &url, destination)?), + )) } - fn risks(args: &Arguments, level: Level) -> Vec { + fn risks(args: &Arguments, level: Level, protected: bool) -> Vec { if args.delete { let risk = if !args.destination.starts_with("refs/heads/") { Risk::DeleteTag - } else if level >= Level::Name { + } else if protected { Risk::DeleteProtectedBranch } else { Risk::DeleteBranch @@ -267,12 +273,15 @@ impl Git { return vec![risk]; } let mut risks = Vec::new(); - if main_branch(&args.destination) { + if main_branch(&args.destination) && !(args.force && level == Level::Click) { risks.push(Risk::ProtectedBranch); } if args.force { risks.push(Risk::ForceUpdate); } + if risks.is_empty() && level == Level::Click { + risks.push(Risk::PushBranch); + } risks } @@ -399,13 +408,19 @@ impl Git { return Err("A normal push must preserve existing history. Fetch the remote ref first; if rewriting it is intended, request force=true.".into()); } } - let (level, branch_type) = - if args.destination.starts_with("refs/heads/") && (args.delete || args.force) { - self.level(&root, &url, &args.destination, args.delete)? - } else { - (Level::Name, None) - }; - let risks = Self::risks(args, level); + let operation = if args.delete { + Operation::Delete + } else if args.force { + Operation::ForcePush + } else { + Operation::Push + }; + let (level, branch_type, protected) = if args.destination.starts_with("refs/heads/") { + self.level(&root, &url, &args.destination, operation)? + } else { + (Level::Name, None, false) + }; + let risks = Self::risks(args, level, protected); let options = self.pin_remote(&root, &args.remote, &url)?; let mut command = vec![self.binary.clone(), "-C".into(), root.clone()]; command.extend(options.clone()); @@ -430,6 +445,7 @@ impl Git { new, old, delete: args.delete, + operation, risks, level, branch_type, @@ -449,11 +465,14 @@ impl Git { return Ok(false); } - // The table can change while a window is open, and below the floor the remote can - // start calling the branch its default. A level that rose stops the push. - if plan.governed() { - let (level, _) = - self.level(&plan.repository, &plan.url, &plan.destination, plan.delete)?; + // The rules or the remote's default branch can change while a window is open. + if plan.destination.starts_with("refs/heads/") { + let (level, _, _) = self.level( + &plan.repository, + &plan.url, + &plan.destination, + plan.operation, + )?; // The remote HEAD lookup can block. Revalidate the destination after it. if level > plan.level || (level < Level::Name diff --git a/native/git-protection/src/hook/policy.rs b/native/git-protection/src/hook/policy.rs index 34bd32f..f44c061 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::{self, BranchRules, BranchTypes, Level}; +use crate::levels::{self, BranchRules, BranchTypes, Level, Operation}; use crate::process::{self, Cancellation, Output}; use std::collections::HashSet; use std::path::{Path, PathBuf}; @@ -117,11 +117,9 @@ impl Repository<'_> { Ok("origin".into()) } - /// The branch a push of a local name updates. Without `:` Git updates the source's - /// own full ref, so the name must resolve to exactly `refs/heads/`: `heads/trunk` - /// resolving to `refs/heads/trunk` is refused, because the floor would be asked about - /// another branch than the one pushed. - fn local_branch(&self, name: &str) -> Result, String> { + /// Without `:` Git updates the source's own full ref. Resolve only an exact + /// branch or tag name, or HEAD when it is unambiguous. + fn local_ref(&self, name: &str, namespace: &str) -> Result, String> { // `rev-parse` reads `@` as HEAD, while `git push` first looks for a ref named `@`. if name == "@" || (name != "HEAD" && !plain(name)) { return Ok(None); @@ -143,30 +141,64 @@ impl Repository<'_> { } let output = self.query(&["rev-parse", "--symbolic-full-name", name])?; let full = output.stdout.trim(); - let Some(branch) = full.strip_prefix("refs/heads/") else { + let Some(reference) = full.strip_prefix(namespace) else { return Ok(None); }; - let exact = name == "HEAD" || name == full || name == branch; - Ok((output.status.success() && exact && plain(branch)).then(|| branch.to_owned())) + let exact = name == "HEAD" || name == full || name == reference; + Ok((output.status.success() && exact && plain(reference)).then(|| reference.to_owned())) } - /// Whether the floor leaves the branch alone, asked of the remote the way a push asks. - /// Any doubt keeps the floor. - fn below_floor(&self, remote: &str, branch: &str) -> bool { - let Some(path) = self.path.to_str() else { - return false; - }; + fn can_push_without_window(&self) -> bool { // A submodule push goes to remotes this check never asks. let recursing = self.query(&[ "config", "--get-regexp", r"^(push\.recursesubmodules|submodule\.recurse)$", ]); - plain(remote) - && recursing.is_ok_and(|output| output.status.code() == Some(1)) - && crate::git::Git::new(self.cancel.clone(), self.deadline) - .and_then(|git| git.protected(path, remote, branch)) - == Ok(false) + recursing.is_ok_and(|output| output.status.code() == Some(1)) + } + + fn push_destination( + &self, + remote: &str, + destination: &str, + check_remote_head: bool, + ) -> Option { + let path = self.path.to_str()?; + if !plain(remote) { + return None; + } + crate::git::Git::new(self.cancel.clone(), self.deadline) + .and_then(|git| git.push_destination(path, remote, destination, check_remote_head)) + .ok() + .flatten() + } + + fn tag_destination( + &self, + remote: Option<&str>, + name: &str, + tag_operand: bool, + local: bool, + ) -> Result { + let Some(remote) = remote else { + return Ok(false); + }; + let tag = if tag_operand { + plain(name).then(|| name.to_owned()) + } else if local { + self.local_ref(name, "refs/tags/")? + } else { + name.strip_prefix("refs/tags/") + .filter(|name| plain(name)) + .map(str::to_owned) + }; + Ok(tag.is_some_and(|tag| { + self.can_push_without_window() + && self + .push_destination(remote, &format!("refs/tags/{tag}"), false) + .is_some() + })) } fn known_branch(&self, name: &str) -> Result { @@ -220,40 +252,68 @@ fn explicit_branch(name: &str) -> Option { .map(str::to_owned) } -/// What a branch type says about one force push or deletion. +/// What the rule for one branch says. enum Outcome { - /// The type is `none`, the destination is a branch and the floor leaves it alone. Allowed, Forbidden { branch: String, - kind: String, + kind: Option, }, /// Everything else goes to the confirmation, as before types existed. Checked, } -/// 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. +/// Decides one destination. Only an exact branch can use Allow or Block directly. fn outcome( rules: BranchRules<'_>, allow: bool, candidate: Option<&str>, resolve: impl FnOnce() -> Result, String>, repo: &Repository, + operation: Operation, ) -> Result { - let interesting = |name: &str| matches!(rules.selected(name).0, Level::None | Level::Forbid); + let interesting = |name: &str| { + [false, true].into_iter().any(|protected| { + matches!( + rules.selected(name, protected).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 rules.selected(&branch) { - (Level::Forbid, Some(rule)) => Outcome::Forbidden { + let exact_main = matches!(branch.as_str(), "main" | "master"); + let depends_on_remote = + operation != Operation::Push && !exact_main && rules.depends_on_protection(&branch); + let destination = format!("refs/heads/{branch}"); + let protected = if depends_on_remote { + let Some(protected) = repo.push_destination(&remote, &destination, true) else { + return Ok(Outcome::Checked); + }; + protected + } else { + exact_main + }; + let (level, rule) = rules.selected(&branch, protected); + Ok(match level { + Level::Forbid => Outcome::Forbidden { branch, - kind: rule.name.clone(), + kind: rule.map(|rule| rule.name.clone()), }, - (Level::None, _) if allow && repo.below_floor(&remote, &branch) => Outcome::Allowed, + Level::None + if allow + && repo.can_push_without_window() + && (depends_on_remote + || repo + .push_destination(&remote, &destination, false) + .is_some()) => + { + Outcome::Allowed + } _ => Outcome::Checked, }) } @@ -294,6 +354,7 @@ impl Context { struct Push<'a> { dry: bool, force: bool, + leases: Vec<&'a str>, all: bool, delete: bool, tags_only: bool, @@ -337,44 +398,42 @@ fn abbreviated(arg: &str, names: &[&str]) -> bool { } impl<'a> Push<'a> { - fn operand(&mut self, arg: &'a str) { - let reference = if let Some(reference) = arg.strip_prefix('+') { - self.force = true; - reference - } else { - arg - }; - self.operands.push(reference); - } - fn parse(arguments: &'a [String]) -> Self { let mut push = Self { unusual: arguments.iter().any(|arg| unusual(arg)), ..Self::default() }; + let mut all_leases = false; + let mut mirror = false; let mut args = arguments.iter(); while let Some(arg) = args.next() { let arg = arg.as_str(); if arg == "--" { - for operand in args { - push.operand(operand); - } + push.operands.extend(args.map(String::as_str)); break; } if arg == "-n" || (arg.starts_with("--dr") && "--dry-run".starts_with(arg)) { push.dry = true; } else if arg.starts_with("--no-dr") && "--no-dry-run".starts_with(arg) { push.dry = false; - } else if abbreviated( - arg, - &[ - "--force", - "--force-if-includes", - "--force-with-lease", - "--mirror", - ], - ) { + } else if abbreviated(arg, &["--force"]) { push.force = true; + } else if arg == "--no-force" { + push.force = false; + } else if abbreviated(arg, &["--force-with-lease"]) { + // --force-if-includes only modifies how Git checks leases. + if let Some((_, value)) = arg.split_once('=') { + push.leases.push(value.split(':').next().unwrap_or(value)); + } else { + all_leases = true; + } + } else if abbreviated(arg, &["--no-force-with-lease"]) { + push.leases.clear(); + all_leases = false; + } else if abbreviated(arg, &["--mirror"]) { + mirror = true; + } else if abbreviated(arg, &["--no-mirror"]) { + mirror = false; } else if abbreviated(arg, &["--all", "--branches"]) { push.all = true; } else if matches!(arg, "--prune" | "--prun" | "--pru") { @@ -417,12 +476,21 @@ impl<'a> Push<'a> { } } } else { - push.operand(arg); + push.operands.push(arg); } } + push.force |= all_leases || mirror; push } + fn lease_matches(&self, reference: &str) -> bool { + self.leases.iter().any(|name| { + ["", "refs/", "refs/heads/", "refs/tags/", "refs/remotes/"] + .iter() + .any(|prefix| reference.strip_prefix(prefix) == Some(name)) + }) + } + fn risks( &self, repo: &Repository, @@ -447,11 +515,14 @@ 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 + let customizable_push = types.has_push_rules(); + let uses_branch_rules = customizable_push + || self.force + || !self.leases.is_empty() || self.delete || refspecs .iter() - .any(|reference| reference.len() > 1 && reference.starts_with(':')); + .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() { @@ -462,8 +533,9 @@ impl<'a> Push<'a> { } else { None }; - let force_rules = types.rules(false, common.as_deref()); - let delete_rules = types.rules(true, common.as_deref()); + let push_rules = types.rules(Operation::Push, common.as_deref()); + let force_rules = types.rules(Operation::ForcePush, common.as_deref()); + let delete_rules = types.rules(Operation::Delete, 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()); @@ -474,6 +546,9 @@ impl<'a> Push<'a> { let mut forced = Vec::new(); let mut tag = false; for &reference in refspecs { + let forced_ref = reference.strip_prefix('+'); + let mut force = self.force || forced_ref.is_some(); + let reference = forced_ref.unwrap_or(reference); if reference == "tag" { tag = true; continue; @@ -494,7 +569,9 @@ impl<'a> Push<'a> { verdict .risks .push("pushes matching branches, main/master included".into()); - forced.push(Outcome::Checked); + if force { + forced.push(Outcome::Checked); + } } else { let destination = reference .split_once(':') @@ -504,7 +581,63 @@ impl<'a> Push<'a> { if dest.is_empty() { source } else { dest } }, ); - if protected(destination) { + let local = !reference.contains(':'); + if !force && !self.leases.is_empty() { + let full = if !allow { + None + } else if tag && plain(destination) { + Some(format!("refs/tags/{destination}")) + } else if destination.starts_with("refs/") && plain(destination) && !local { + Some(destination.to_owned()) + } else if local { + if let Some(branch) = repo.local_ref(destination, "refs/heads/")? { + Some(format!("refs/heads/{branch}")) + } else { + repo.local_ref(destination, "refs/tags/")? + .map(|tag| format!("refs/tags/{tag}")) + } + } else { + None + }; + let Some(full) = full else { + forced.push(Outcome::Checked); + tag = false; + continue; + }; + force = self.lease_matches(&full); + } + if force && !self.delete { + forced.push(if tag { + Outcome::Checked + } else { + rewritten( + repo, + force_rules, + allow, + remote, + local, + destination, + Operation::ForcePush, + )? + }); + } else if push_rules.customized() { + if !(allow && repo.tag_destination(remote, destination, tag, local)?) { + let decided = if tag { + Outcome::Checked + } else { + rewritten( + repo, + push_rules, + allow, + remote, + local, + destination, + Operation::Push, + )? + }; + verdict.push(decided); + } + } else if protected(destination) { verdict.risks.push("push targets main/master".into()); } else if matches!(destination, "HEAD" | "@") || destination.contains("$(") @@ -517,21 +650,21 @@ impl<'a> Push<'a> { .push(format!("pushes the current branch '{branch}' (protected)")); } } - if self.force && !self.delete { - forced.push(if tag { - Outcome::Checked - } else { - let local = !reference.contains(':'); - rewritten(repo, force_rules, allow, remote, local, destination)? - }); - } } tag = false; } - if implicit { - self.current_branch(repo, context, force_rules, allow, &mut verdict, &mut forced)?; + if implicit && !self.leases.is_empty() && !allow { + forced.push(Outcome::Checked); + } else if implicit { + let branch = repo.branch(context)?; + let force = self.force || self.lease_matches(&format!("refs/heads/{branch}")); + let rules = if force { force_rules } else { push_rules }; + let decided = self.current_branch(repo, branch, force, rules, allow, &mut verdict)?; + if let Some(decided) = decided { + forced.push(decided); + } } - if self.force { + if self.force || (self.tags_only && !self.leases.is_empty()) || !forced.is_empty() { verdict.force(forced, usize::from(self.prune)); } Ok(verdict) @@ -543,38 +676,51 @@ impl Push<'_> { fn current_branch( &self, repo: &Repository, - context: &Context, + branch: String, + force: bool, rules: BranchRules<'_>, allow: bool, verdict: &mut Verdict, - forced: &mut Vec, - ) -> Result<(), String> { - let branch = repo.branch(context)?; - if matches!(branch.as_str(), "main" | "master") { - verdict - .risks - .push(format!("current branch is '{branch}' (protected)")); - } - if self.force && !self.delete { - let remote = self.operands.first().copied().or(self.remote_option); - forced.push(outcome( - rules, - allow, - Some(&branch), - || { - let Some(branch) = repo.local_branch("HEAD")? else { - return Ok(None); - }; - let remote = match remote { - Some(remote) => remote.to_owned(), - None => repo.implicit_remote(&branch)?, - }; - Ok(Some((branch, remote))) - }, - repo, - )?); + ) -> Result, String> { + if !force && !rules.customized() { + if matches!(branch.as_str(), "main" | "master") { + verdict + .risks + .push(format!("current branch is '{branch}' (protected)")); + } + return Ok(None); } - Ok(()) + if self.delete { + return Ok(None); + } + let operation = if force { + Operation::ForcePush + } else { + Operation::Push + }; + let remote = self.operands.first().copied().or(self.remote_option); + let decided = outcome( + rules, + allow, + Some(&branch), + || { + let Some(branch) = repo.local_ref("HEAD", "refs/heads/")? else { + return Ok(None); + }; + let remote = match remote { + Some(remote) => remote.to_owned(), + None => repo.implicit_remote(&branch)?, + }; + Ok(Some((branch, remote))) + }, + repo, + operation, + )?; + if force { + return Ok(Some(decided)); + } + verdict.push(decided); + Ok(None) } } @@ -596,6 +742,7 @@ fn deleted( .map(|(remote, branch)| (branch, remote.to_owned()))) }, repo, + Operation::Delete, ) } @@ -607,6 +754,7 @@ fn rewritten( remote: Option<&str>, local: bool, destination: &str, + operation: Operation, ) -> Result { let candidate = (!matches!(destination, "HEAD" | "@")).then(|| { destination @@ -623,13 +771,14 @@ fn rewritten( }; // `name:name` is not a local push: its `` is matched on the remote. let branch = if local { - repo.local_branch(destination)? + repo.local_ref(destination, "refs/heads/")? } else { explicit_branch(destination) }; Ok(branch.map(|branch| (branch, remote.to_owned()))) }, repo, + operation, ) } @@ -642,6 +791,20 @@ pub(super) struct Verdict { } impl Verdict { + fn forbid(&mut self, action: &str, branch: &str, kind: Option) { + let rule = kind.map_or(String::new(), |kind| format!(" by branch rule '{kind}'")); + self.forbidden + .push(format!("{action} '{branch}' is forbidden{rule}")); + } + + fn push(&mut self, decided: Outcome) { + match decided { + Outcome::Allowed => {} + Outcome::Forbidden { branch, kind } => self.forbid("push to", &branch, kind), + Outcome::Checked => self.risks.push("push requires a branch check".into()), + } + } + fn delete( &mut self, decided: Outcome, @@ -649,9 +812,7 @@ impl Verdict { ) -> Result<(), String> { match decided { Outcome::Allowed => {} - Outcome::Forbidden { branch, kind } => self.forbidden.push(format!( - "deleting branch '{branch}' is forbidden by branch rule '{kind}'" - )), + Outcome::Forbidden { branch, kind } => self.forbid("deleting branch", &branch, kind), Outcome::Checked => self.risks.push(risk()?), } Ok(()) @@ -663,9 +824,7 @@ impl Verdict { for decided in forced { match decided { Outcome::Allowed => {} - Outcome::Forbidden { branch, kind } => self.forbidden.push(format!( - "force push to '{branch}' is forbidden by branch rule '{kind}'" - )), + Outcome::Forbidden { branch, kind } => self.forbid("force push to", &branch, kind), Outcome::Checked => checked = true, } } diff --git a/native/git-protection/src/levels.rs b/native/git-protection/src/levels.rs index 375fc09..32bbad6 100644 --- a/native/git-protection/src/levels.rs +++ b/native/git-protection/src/levels.rs @@ -1,14 +1,13 @@ //! Branch types from Agent Watch settings and the check level each one asks for. //! -//! The app writes the table; this side only reads it. An agent runs as the same user and can -//! edit the file, so nothing read here may lower the floor: `main`, `master`, the remote's -//! default branch, branches listed in `mothership.protectedBranch` and tags. See ADR-0025. +//! The app writes the table; this side only reads it. Branch defaults are configurable, +//! including the minimum for protected branches. Tags use their own confirmation. 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. +/// How a Git operation is checked, weakest first. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Level { @@ -55,6 +54,23 @@ fn settings_path() -> Option { } const MAX_TABLE_BYTES: u64 = 1024 * 1024; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Operation { + Push, + ForcePush, + Delete, +} + +impl Operation { + fn default_level(self) -> Level { + match self { + Self::Push => Level::None, + Self::ForcePush => Level::Name, + Self::Delete => Level::Click, + } + } +} + // Unknown fields are ignored, as the app's decoder ignores them, so both sides read one // file the same way. #[derive(Clone, Debug, Deserialize)] @@ -72,25 +88,47 @@ struct LegacyTable { #[derive(Clone, Debug, Default, Deserialize)] #[serde(rename_all = "camelCase")] struct OperationRules { + push: Option>, force_push: Vec, delete: Vec, } impl OperationRules { - fn for_operation(&self, delete: bool) -> &[BranchType] { - if delete { - &self.delete - } else { - &self.force_push + fn for_operation(&self, operation: Operation) -> &[BranchType] { + match operation { + Operation::Push => self.push.as_deref().unwrap_or_default(), + Operation::ForcePush => &self.force_push, + Operation::Delete => &self.delete, } } } #[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct LevelOverrides { + push: Option, + force_push: Option, + delete: Option, +} + +impl LevelOverrides { + fn get(&self, operation: Operation) -> Option { + match operation { + Operation::Push => self.push, + Operation::ForcePush => self.force_push, + Operation::Delete => self.delete, + } + } +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct BranchTypes { enabled: bool, global: OperationRules, repositories: HashMap, + defaults: Option, + protected_branches: Option, } impl Default for BranchTypes { @@ -99,6 +137,8 @@ impl Default for BranchTypes { enabled: true, global: OperationRules::default(), repositories: HashMap::new(), + defaults: None, + protected_branches: None, } } } @@ -108,17 +148,36 @@ pub struct BranchRules<'a> { global: &'a [BranchType], local: &'a [BranchType], default: Level, + protected: Level, + has_default_override: bool, } 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)) + matches!(self.default, Level::None | Level::Forbid) + || matches!(self.protected, Level::None | Level::Forbid) + || 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>) { + pub fn customized(self) -> bool { + self.has_default_override + || self.protected != Level::Name + || !self.global.is_empty() + || !self.local.is_empty() + } + + pub fn for_direct_push(mut self) -> Self { + if !self.has_default_override { + self.default = Level::Name; + } + self + } + + pub fn selected(self, branch: &str, protected: bool) -> (Level, Option<&'a BranchType>) { let matching = |rules: &'a [BranchType]| { rules.iter().find(|rule| { rule.patterns @@ -127,13 +186,27 @@ impl<'a> BranchRules<'a> { }) }; let global = matching(self.global); - let level = global.map_or(self.default, |rule| rule.level); + let fallback = if protected { + self.protected + } else { + self.default + }; + let level = global.map_or(fallback, |rule| rule.level); + let effective = if protected { + level.max(fallback) + } else { + level + }; if let Some(local) = matching(self.local) - && local.level > level + && local.level > effective { return (local.level, Some(local)); } - (level, global) + (effective, global.filter(|_| effective == level)) + } + + pub fn depends_on_protection(self, branch: &str) -> bool { + self.selected(branch, false).0 != self.selected(branch, true).0 } } @@ -174,6 +247,7 @@ impl BranchTypes { global: OperationRules { force_push: old.types.clone(), delete: old.types, + ..OperationRules::default() }, ..Self::default() }) @@ -191,13 +265,31 @@ impl BranchTypes { !self.repositories.is_empty() } - pub fn rules(&self, delete: bool, repository: Option<&str>) -> BranchRules<'_> { + pub fn has_push_rules(&self) -> bool { + self.rules(Operation::Push, None).customized() + || self + .repositories + .values() + .any(|rules| !rules.for_operation(Operation::Push).is_empty()) + } + + pub fn rules(&self, operation: Operation, repository: Option<&str>) -> BranchRules<'_> { + let default = self + .defaults + .as_ref() + .and_then(|levels| levels.get(operation)); BranchRules { - global: self.global.for_operation(delete), + global: self.global.for_operation(operation), local: repository .and_then(|key| self.repositories.get(key)) - .map_or(&[], |rules| rules.for_operation(delete)), - default: if delete { Level::Click } else { Level::Name }, + .map_or(&[], |rules| rules.for_operation(operation)), + default: default.unwrap_or(operation.default_level()), + protected: self + .protected_branches + .as_ref() + .and_then(|levels| levels.get(operation)) + .unwrap_or(Level::Name), + has_default_override: default.is_some(), } } } @@ -227,14 +319,19 @@ pub fn pattern_matches(pattern: &str, name: &str) -> bool { pattern[p..].iter().all(|&c| c == '*') } -/// The level of a force push or deletion, before protected-branch checks. -pub fn chosen( +#[cfg(test)] +fn chosen( types: &BranchTypes, branch: &str, delete: bool, repo: Option<&str>, ) -> (Level, Option) { - let (level, rule) = types.rules(delete, repo).selected(branch); + let operation = if delete { + Operation::Delete + } else { + Operation::ForcePush + }; + let (level, rule) = types.rules(operation, repo).selected(branch, false); (level, rule.map(|rule| rule.name.clone())) } @@ -254,15 +351,6 @@ pub fn canonical_directory(folder: &Path, path: &str) -> Result .map_err(|_| "The repository's directory is not valid UTF-8.".into()) } -/// The floor raises a protected branch to `name`; nothing lowers it. -pub fn with_floor(level: Level, protected: bool) -> Level { - if protected { - level.max(Level::Name) - } else { - level - } -} - #[cfg(test)] mod tests { use super::*; @@ -324,13 +412,18 @@ mod tests { {"name":"Late","patterns":["agent/x"],"level":"name"}]"#, ); assert_eq!( - types.rules(true, None).selected("agent/x").1.unwrap().name, + types + .rules(Operation::Delete, None) + .selected("agent/x", false) + .1 + .unwrap() + .name, "Drafts" ); assert_eq!( types - .rules(true, None) - .selected("feature/y") + .rules(Operation::Delete, None) + .selected("feature/y", false) .1 .unwrap() .name, @@ -378,11 +471,14 @@ mod tests { #[test] fn the_floor_never_goes_below_name() { - for level in [Level::None, Level::Click, Level::Name] { - assert_eq!(with_floor(level, true), Level::Name); - } - assert_eq!(with_floor(Level::Forbid, true), Level::Forbid); - assert_eq!(with_floor(Level::None, false), Level::None); + let types = table( + r#"[{"name":"Allow","patterns":["main"],"level":"none"}, + {"name":"Block","patterns":["master"],"level":"forbid"}]"#, + ); + let rules = types.rules(Operation::ForcePush, None); + assert_eq!(rules.selected("main", true).0, Level::Name); + assert_eq!(rules.selected("master", true).0, Level::Forbid); + assert_eq!(rules.selected("main", false).0, Level::None); } #[test] @@ -401,10 +497,20 @@ mod tests { r#"{"version":1,"types":[{"name":"A","patterns":["a"],"level":"none","colour":"red"}]}"#, ); assert_eq!( - newer.unwrap().rules(true, None).selected("a").0, + newer + .unwrap() + .rules(Operation::Delete, None) + .selected("a", false) + .0, Level::None ); let missing = BranchTypes::load_from(Path::new("/nonexistent/agent-watch/types.json")); - assert!(missing.rules(true, None).selected("anything").1.is_none()); + assert!( + missing + .rules(Operation::Delete, None) + .selected("anything", false) + .1 + .is_none() + ); } } diff --git a/native/git-protection/src/push.rs b/native/git-protection/src/push.rs index 49295a3..5fd47d0 100644 --- a/native/git-protection/src/push.rs +++ b/native/git-protection/src/push.rs @@ -1,7 +1,7 @@ use crate::confirmation::{self, Form}; use crate::domain::{Arguments, Plan}; use crate::git::Git; -use crate::levels::Level; +use crate::levels::{Level, Operation}; use crate::process::{self, Cancellation}; use serde_json::{Value, json}; use std::time::{Duration, Instant}; @@ -80,17 +80,20 @@ pub fn execute( } fn forbidden(plan: &Plan) -> String { - let operation = if plan.delete { - "deletion" - } else { - "force push" + let operation = match plan.operation { + Operation::Push => "push", + Operation::ForcePush => "force push", + Operation::Delete => "deletion", }; let branch = plan .destination .strip_prefix("refs/heads/") .unwrap_or(&plan.destination); - let kind = plan.branch_type.as_deref().unwrap_or_default(); + let rule = plan + .branch_type + .as_ref() + .map_or(String::new(), |kind| format!(" (branch rule '{kind}')")); format!( - "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." + "Agent Watch settings forbid the {operation} of branch '{branch}'{rule}. 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-defaults.json b/native/git-protection/tests/fixtures/branch-rules-defaults.json new file mode 100644 index 0000000..f079b63 --- /dev/null +++ b/native/git-protection/tests/fixtures/branch-rules-defaults.json @@ -0,0 +1,12 @@ +{ + "defaults": { "push": "click", "forcePush": "forbid", "delete": "name" }, + "enabled": true, + "global": { + "push": [{ "name": "Sandbox", "patterns": ["sandbox/*"], "level": "none" }], + "forcePush": [], + "delete": [] + }, + "protectedBranches": { "push": "none", "forcePush": "click", "delete": "forbid" }, + "repositories": {}, + "version": 2 +} diff --git a/native/git-protection/tests/git_guard.rs b/native/git-protection/tests/git_guard.rs index 35b0612..04ba8c7 100644 --- a/native/git-protection/tests/git_guard.rs +++ b/native/git-protection/tests/git_guard.rs @@ -689,6 +689,67 @@ fn disabling_and_enabling_applies_to_both_clients_without_reinstalling() { } } +#[test] +fn edited_defaults_apply_independently_in_both_hosts() { + let bundle = Bundle::new(); + let repo = bundle.repo_with_remote(); + bundle.branch_types(include_str!("fixtures/branch-rules-defaults.json")); + bundle.git(&repo, &["tag", "local-tag"]); + + for host in ["claude", "codex"] { + let check = |command| { + bundle.invoke( + host, + &json!({"cwd": repo, "tool_input": {"command": command}}).to_string(), + ) + }; + assert!(check("git push origin HEAD:refs/heads/main").is_empty()); + assert!(check("git push origin HEAD:refs/heads/sandbox/x").is_empty()); + assert!(check("git push --force-if-includes origin HEAD:refs/heads/main").is_empty()); + assert!(check("git push origin local-tag").is_empty()); + assert!( + denial(&check("true && git push origin local-tag")) + .contains("push requires a branch check") + ); + assert!( + denial(&check("git push legacy local-tag")).contains("push requires a branch check") + ); + let ordinary = denial(&check("git push origin HEAD:refs/heads/agent/x")); + assert!( + ordinary.contains("push requires a branch check"), + "{ordinary}" + ); + let force = denial(&check("git push origin +HEAD:refs/heads/main")); + assert!( + force.contains("force push. For one intended reference"), + "{force}" + ); + let force_unmatched = denial(&check("git push -f origin HEAD:refs/heads/agent/x")); + assert!( + force_unmatched.contains("'agent/x' is forbidden"), + "{force_unmatched}" + ); + let deletion = denial(&check("git push origin --delete refs/heads/trunk")); + assert!(deletion.contains("'trunk' is forbidden"), "{deletion}"); + let deletion = denial(&check("git push origin --delete refs/heads/agent/kept")); + assert!(deletion.contains("'agent/kept' is forbidden"), "{deletion}"); + let mixed = denial(&check( + "git push origin +HEAD:refs/heads/agent/x HEAD:refs/heads/agent/y", + )); + assert!(mixed.contains("'agent/x' is forbidden"), "{mixed}"); + assert!(mixed.contains("push requires a branch check"), "{mixed}"); + let scoped = denial(&check( + "git push --force-with-lease=main origin HEAD:refs/heads/main HEAD:refs/heads/agent/y", + )); + assert!( + scoped.contains("force push") && scoped.contains("push requires a branch check"), + "{scoped}" + ); + assert!(!scoped.contains("forbidden"), "{scoped}"); + assert!(check("git push origin HEAD:refs/tags/test").is_empty()); + } +} + #[test] fn linked_worktrees_share_the_repository_rule_for_the_selected_operation() { let bundle = Bundle::new(); diff --git a/native/git-protection/tests/push.rs b/native/git-protection/tests/push.rs index 4c2af7a..f55a680 100644 --- a/native/git-protection/tests/push.rs +++ b/native/git-protection/tests/push.rs @@ -676,7 +676,7 @@ fn feature_delete_needs_one_explicit_click() { assert_eq!(fixture.prompts.len(), 1); let params = &fixture.prompts[0]["params"]; let message = params["message"].as_str().unwrap(); - assert!(message.starts_with("Шаг 1 из 1: Удаление обычной ветки")); + assert!(message.starts_with("Шаг 1 из 1: Удаление ветки")); assert!(message.contains("Кнопка «Удалить ветку» выполнит операцию")); assert!(message.contains(fixture.remote.to_str().unwrap())); let properties = ¶ms["requestedSchema"]["properties"]; @@ -1558,6 +1558,55 @@ fn each_level_asks_for_its_own_windows() { assert!(fixture.remote_refs().contains("refs/heads/locked/x")); } +#[test] +fn edited_defaults_change_windows_and_protect_only_the_selected_operation() { + let mut fixture = Fixture::new(true); + fixture.branch_types(include_str!("fixtures/branch-rules-defaults.json")); + + for (branch, windows) in [("main", 0), ("feature/new", 1)] { + let destination = format!("refs/heads/{branch}"); + fixture.arguments = json!({"repository":fixture.repo,"destination":destination}); + let result = fixture.push_accept(); + assert_eq!(result["status"], "completed", "{result}"); + assert_eq!(fixture.prompts.len(), windows); + assert!(fixture.remote_refs().contains(&destination)); + if windows == 1 { + assert_eq!( + fixture.prompts[0]["params"]["requestedSchema"]["properties"]["decision"]["title"], + "Отправить изменения?" + ); + } + } + + let (result, prompts) = run_level(&mut fixture, "main", false); + assert_eq!(result["status"], "completed", "{result}"); + assert_eq!(prompts, 1); + let (result, prompts) = run_level(&mut fixture, "feature/new", false); + assert_eq!(result["status"], "not_pushed", "{result}"); + assert_eq!(prompts, 0); + let (result, prompts) = run_level(&mut fixture, "main", true); + assert_eq!(result["status"], "not_pushed", "{result}"); + assert_eq!(prompts, 0); + assert!(fixture.remote_refs().contains("refs/heads/main")); + let (result, prompts) = run_level(&mut fixture, "feature/new", true); + assert_eq!(result["status"], "completed", "{result}"); + assert_eq!(prompts, 2); + + let mut rules: Value = + serde_json::from_str(include_str!("fixtures/branch-rules-defaults.json")).unwrap(); + rules["protectedBranches"]["delete"] = json!("click"); + fixture.branch_types(&rules.to_string()); + let (result, prompts) = run_level(&mut fixture, "main", true); + assert_eq!(result["status"], "completed", "{result}"); + assert_eq!(prompts, 1); + assert!( + fixture.prompts[0]["params"]["message"] + .as_str() + .unwrap() + .starts_with("Шаг 1 из 1: Удаление защищённой ветки") + ); +} + #[test] fn a_click_level_force_push_runs_from_its_only_window() { let mut fixture = Fixture::new(true);