diff --git a/.agents/notes/implemented/feature/2026-09-13-macos-git-graph-intellij-layout.md b/.agents/notes/implemented/feature/2026-09-13-macos-git-graph-intellij-layout.md index 388419f4b2..b851369ab5 100644 --- a/.agents/notes/implemented/feature/2026-09-13-macos-git-graph-intellij-layout.md +++ b/.agents/notes/implemented/feature/2026-09-13-macos-git-graph-intellij-layout.md @@ -618,3 +618,7 @@ Lithe 在工作台视图中持有 `WorkbenchToolContentStore`,本次用于 Git - `macos/Tests/LitheGitModuleTests/Fixtures/GitGraphIDEA/` - `macos/Tests/LitheTests/Fixtures/GitGraph/` - `macos/Resources/GitGraph/` + +## 后续:布局下沉到 Rust Core(#1662 GIT-18/19) + +本文描述的 DFS、head 排序、定色、过滤后的虚线拓扑和 missing parents 算法已搬进 `rust/lithe-core/src/git/graph.rs`,由 `git.graphProjection` 统一提供,规则以 `shared/fixtures/git/graph-projection-v1.json` 为准。文中提到的 Swift/TS 实现文件已删除;两端只保留绘制、像素和颜色 ID 到主题色的映射。 diff --git a/.agents/notes/implemented/feature/2026-09-25-windows-git-graph-branch-colors.md b/.agents/notes/implemented/feature/2026-09-25-windows-git-graph-branch-colors.md index d8111b57b8..2d0d36d47d 100644 --- a/.agents/notes/implemented/feature/2026-09-25-windows-git-graph-branch-colors.md +++ b/.agents/notes/implemented/feature/2026-09-25-windows-git-graph-branch-colors.md @@ -307,3 +307,7 @@ ResizeObserver(浏览器按帧合并的尺寸观察器)服务已挂载行, - `macos/Sources/LitheGitModule/Services/GitGraphHeadOrdering.swift` - `macos/Sources/LitheGitModule/Services/GitGraphProjection.swift` - `macos/Tests/LitheGitModuleTests/Fixtures/GitGraphIDEA/` + +## 后续:布局下沉到 Rust Core(#1662 GIT-18/19) + +本文描述的 DFS、head 排序、定色、过滤后的虚线拓扑和 missing parents 算法已搬进 `rust/lithe-core/src/git/graph.rs`,由 `git.graphProjection` 统一提供,规则以 `shared/fixtures/git/graph-projection-v1.json` 为准。文中提到的 Swift/TS 实现文件已删除;两端只保留绘制、像素和颜色 ID 到主题色的映射。 diff --git a/Package.swift b/Package.swift index 2e8d847332..edb090d12a 100644 --- a/Package.swift +++ b/Package.swift @@ -24,7 +24,6 @@ let package = Package( .library(name: "LitheWorkspaceModule", targets: ["LitheWorkspaceModule"]), .library(name: "LithePluginPackageSigning", targets: ["LithePluginPackageSigning"]), .executable(name: "LitheCoreVerifier", targets: ["LitheCoreVerifier"]), - .executable(name: "LitheGitGraphVerifier", targets: ["LitheGitGraphVerifier"]), .executable(name: "LitheGitPerformanceVerifier", targets: ["LitheGitPerformanceVerifier"]), .executable(name: "LitheOfficialPluginVerifier", targets: ["LitheOfficialPluginVerifier"]), .executable(name: "LithePluginPackageSigner", targets: ["LithePluginPackageSigner"]) @@ -147,7 +146,7 @@ let package = Package( ), .target( name: "LitheGitTestSupport", - dependencies: ["LitheGitModule"], + dependencies: ["LitheGitModule", "LitheRustCore"], path: "macos/Tests/LitheGitTestSupport", swiftSettings: [.swiftLanguageMode(.v6)] ), @@ -198,7 +197,6 @@ let package = Package( name: "LitheGitModuleTests", dependencies: ["LitheGitTestSupport", "LitheGitModule", "LitheApplicationKernel", "LitheRustCore", .product(name: "Testing", package: "swift-testing")], path: "macos/Tests/LitheGitModuleTests", - resources: [.copy("Fixtures")], swiftSettings: [.swiftLanguageMode(.v6)] ), .target( @@ -214,6 +212,7 @@ let package = Package( "Lithe", "LitheGitModule", "LitheGitPerformanceSupport", + "LitheGitTestSupport", .product(name: "Testing", package: "swift-testing") ], path: "macos/Tests/LitheGitPerformanceTests", @@ -249,15 +248,9 @@ let package = Package( path: "macos/Tests/LitheCoreVerifier", swiftSettings: [.swiftLanguageMode(.v6)] ), - .executableTarget( - name: "LitheGitGraphVerifier", - dependencies: ["LitheGitModule"], - path: "macos/Tests/LitheGitGraphVerifier", - swiftSettings: [.swiftLanguageMode(.v6)] - ), .executableTarget( name: "LitheGitPerformanceVerifier", - dependencies: ["LitheGitModule", "LitheGitPerformanceSupport"], + dependencies: ["LitheGitModule", "LitheGitPerformanceSupport", "LitheGitTestSupport"], path: "macos/Tests/LitheGitPerformanceVerifier", swiftSettings: [.swiftLanguageMode(.v6)] ), diff --git a/macos/Sources/Lithe/Views/Git/GitGraphReferenceGroup.swift b/macos/Sources/Lithe/Views/Git/GitGraphReferenceGroup.swift index f00db61e64..fd5ffb9d1f 100644 --- a/macos/Sources/Lithe/Views/Git/GitGraphReferenceGroup.swift +++ b/macos/Sources/Lithe/Views/Git/GitGraphReferenceGroup.swift @@ -2,6 +2,7 @@ // Copyright 2000-2024 JetBrains s.r.o. and contributors. Apache-2.0. // See Resources/GitGraph/NOTICE.txt. import AppKit +import LitheCoreContracts import LitheGitModule /// IDEA's default compact reference display. The original names remain intact @@ -40,7 +41,7 @@ struct GitGraphReferenceGroup: Equatable, Sendable { } let sorted = labels.sorted { rank($0) == rank($1) - ? GitGraphHeadOrdering.naturalCompare(Array($0.title.utf16), Array($1.title.utf16)) < 0 + ? NaturalNameOrder.compare(Array($0.title.utf16), Array($1.title.utf16)) < 0 : rank($0) < rank($1) } let locals = sorted.filter { $0.kind == .branch } diff --git a/macos/Sources/Lithe/Views/Git/GitLogView.swift b/macos/Sources/Lithe/Views/Git/GitLogView.swift index 6fc4076e73..caec5b2429 100644 --- a/macos/Sources/Lithe/Views/Git/GitLogView.swift +++ b/macos/Sources/Lithe/Views/Git/GitLogView.swift @@ -165,9 +165,16 @@ struct GitLogView: View { let visibleHashes = visibleCommitHashes let options: GitGraphDisplayOptions = showLongGraphEdges ? .expanded : .compact let highlightsCurrentBranch = graphProjectionIdentity.highlightsCurrentBranch - let task = UserActionContext.detached(priority: .userInitiated) { - let layout = GitGraphLayoutService.layout(commits: commits, references: references, - repositoryCommits: repositoryCommits, visibleHashes: visibleHashes, options: options) + let currentBranch = highlightsCurrentBranch + ? references.first(where: { $0.kind == .local && $0.isCurrent })?.shortName : nil + let projector = feature.graphProjector + // One Core call projects the whole loaded window; layout runs off the main actor. + let task = UserActionContext.detached(priority: .userInitiated) { () -> GitGraphPresentation? in + guard let layout = await GitGraphLayoutService.layout( + commits: commits, references: references, repositoryCommits: repositoryCommits, + visibleHashes: visibleHashes, options: options, currentBranch: currentBranch, + project: projector + ) else { return nil } let referenceIndex = GitGraphReferenceGroup.ReferenceIndex(references) return GitGraphPresentation(rows: layout.rows, routingSnapshot: GitGraphLayoutService.routingSnapshot(for: layout), @@ -175,14 +182,14 @@ struct GitLogView: View { referenceGroups: Dictionary(uniqueKeysWithValues: layout.rows.map { ($0.commit.hash, GitGraphReferenceGroup(labels: $0.labels, index: referenceIndex)) }), - currentBranchHashes: highlightsCurrentBranch - ? GitGraphLayoutService.currentBranchHashes(commits: commits, repositoryCommits: repositoryCommits, references: references) : []) + currentBranchHashes: layout.currentBranchHashes) } - let presentation = await withTaskCancellationHandler { + let result = await withTaskCancellationHandler { await task.value } onCancel: { task.cancel() } + guard let presentation = result else { return } guard !Task.isCancelled, graphProjectionIdentity == identity else { return } presentationCache.store(presentation, for: identity) graphPresentation = presentation diff --git a/macos/Sources/LitheCoreContracts/Execution/BuildSystemContracts.swift b/macos/Sources/LitheCoreContracts/Execution/BuildSystemContracts.swift index 183195a1de..153b9a8235 100644 --- a/macos/Sources/LitheCoreContracts/Execution/BuildSystemContracts.swift +++ b/macos/Sources/LitheCoreContracts/Execution/BuildSystemContracts.swift @@ -1027,6 +1027,20 @@ package struct BuildTestResults: Equatable, Sendable, Decodable { package let suite: String? package let testCase: String? private enum CodingKeys: String, CodingKey { case project, suite; case testCase = "case" } + + /// The contract forbids a case without its suite (Core rejects it too), + /// so a scope that names one is malformed rather than guessed at. + package init(from decoder: Decoder) throws { + let values = try decoder.container(keyedBy: CodingKeys.self) + project = try values.decode(String.self, forKey: .project) + suite = try values.decodeIfPresent(String.self, forKey: .suite) + testCase = try values.decodeIfPresent(String.self, forKey: .testCase) + if testCase != nil, suite == nil { + throw DecodingError.dataCorruptedError( + forKey: .testCase, in: values, + debugDescription: "A coverage case requires its suite.") + } + } } package let coverage: [Coverage]? package struct TestCase: Equatable, Identifiable, Sendable, Codable { diff --git a/macos/Sources/LitheCoreContracts/Execution/TestRunOutcomeContracts.swift b/macos/Sources/LitheCoreContracts/Execution/TestRunOutcomeContracts.swift index e710167159..8a9a61a042 100644 --- a/macos/Sources/LitheCoreContracts/Execution/TestRunOutcomeContracts.swift +++ b/macos/Sources/LitheCoreContracts/Execution/TestRunOutcomeContracts.swift @@ -46,8 +46,35 @@ public struct TestRunVerdict: Codable, Equatable, Sendable { public let exitCode: Int32? } +/// What a run replaces in the stored test history: exact result ids and id +/// prefixes. The provider adapter builds it; Core only compares strings. +public struct TestOutcomeMergeScope: Codable, Equatable, Sendable { + public var ids: [String] + public var prefixes: [String] + + public init(ids: [String] = [], prefixes: [String] = []) { + self.ids = ids + self.prefixes = prefixes + } +} + +/// One merged result: its position in the `previous` or `incoming` input. +public struct TestOutcomeMergeEntry: Codable, Equatable, Sendable { + public enum Source: String, Codable, Sendable { case previous, incoming } + public let source: Source + public let index: Int +} + /// Reduces a finished test run to the verdict both platforms show. public protocol TestRunOutcomeResolving: Sendable { + /// `build.mergeTestOutcomes`: which stored and which reported results + /// make up the new history, in display order. + func mergeTestOutcomes( + previous: [String], + incoming: [String], + scope: TestOutcomeMergeScope + ) throws -> [TestOutcomeMergeEntry] + func resolveTestRunOutcome( termination: TestRunTermination, scope: TestRunScopeKind, @@ -83,6 +110,30 @@ public extension TestRunOutcomeCoreCommandExecuting { } } +public extension TestRunOutcomeCoreCommandExecuting { + func mergeTestOutcomes( + previous: [String], + incoming: [String], + scope: TestOutcomeMergeScope + ) throws -> [TestOutcomeMergeEntry] { + let response: MergeTestOutcomesResponse = try executeTestRunOutcomeCommand( + "build.mergeTestOutcomes", + payload: MergeTestOutcomesPayload(previous: previous, incoming: incoming, scope: scope) + ) + return response.entries + } +} + +private struct MergeTestOutcomesPayload: Encodable { + let previous: [String] + let incoming: [String] + let scope: TestOutcomeMergeScope +} + +private struct MergeTestOutcomesResponse: Decodable { + let entries: [TestOutcomeMergeEntry] +} + private struct ResolveTestRunOutcomeTermination: Encodable { let kind: String let exitCode: Int32? diff --git a/macos/Sources/LitheExecutionModule/Services/LanguageTestService.swift b/macos/Sources/LitheExecutionModule/Services/LanguageTestService.swift index 129de0ec48..f9d1c52a04 100644 --- a/macos/Sources/LitheExecutionModule/Services/LanguageTestService.swift +++ b/macos/Sources/LitheExecutionModule/Services/LanguageTestService.swift @@ -302,18 +302,20 @@ package final class LanguageTestService: ObservableObject { resultsWorkspaceURL = workspaceURL.standardizedFileURL // Only the backend can say that a whole suite/project completed. // Legacy reports without coverage replace their exact returned cases. - let keys = Set(result.reports.flatMap(\.tests).map(BuildTestCaseKey.init)) + // Core merges by id; this adapter only names the ids and prefixes. + let previous = testOutcomesByProviderID[providerID] ?? [] let coverage = result.reports.flatMap { $0.coverage ?? [] } - var outcomes = testOutcomesByProviderID[providerID] ?? [] - outcomes.removeAll { outcome in - keys.contains(BuildTestCaseKey(outcome)) - || coverage.contains { scope in - scope.project == outcome.project - && (scope.suite == nil || scope.suite == outcome.suite) - && (scope.testCase == nil || scope.testCase == outcome.name) - } + let merged = try outcomeResolver.mergeTestOutcomes( + previous: previous.map(\.id), + incoming: report.tests.map(\.id), + scope: TestOutcomeMergeScope( + ids: report.tests.map(\.id), + prefixes: coverage.map(Self.coveragePrefix) + ) + ) + testOutcomesByProviderID[providerID] = merged.map { + $0.source == .previous ? previous[$0.index] : report.tests[$0.index] } - testOutcomesByProviderID[providerID] = outcomes + report.tests applyVerdict( termination: .exited(result.exitCode), scope: scope, @@ -330,6 +332,16 @@ package final class LanguageTestService: ObservableObject { } } + /// A coverage scope is a prefix of the ids it completed: a project, one of + /// its suites, or (with a case name) exactly one test. `TestCase.id` is + /// length-prefixed per part, so a shorter scope never matches another name. + private static func coveragePrefix(_ scope: BuildTestResults.Coverage) -> String { + // Decoding rejects a case without its suite, so levels are contiguous. + [scope.project, scope.suite, scope.testCase] + .compactMap { $0.map { "\($0.utf8.count):" + $0 } } + .joined() + } + package func sourceURL(for test: BuildTestResults.TestCase) -> URL? { guard let root = resultsWorkspaceURL, let path = test.path, !path.hasPrefix("/"), !path.contains("\\"), diff --git a/macos/Sources/LitheGitModule/Models/GitCorePlans.swift b/macos/Sources/LitheGitModule/Models/GitCorePlans.swift index 782579a095..a87366e124 100644 --- a/macos/Sources/LitheGitModule/Models/GitCorePlans.swift +++ b/macos/Sources/LitheGitModule/Models/GitCorePlans.swift @@ -7,6 +7,7 @@ package enum GitCorePlanCommand: String, Sendable { case rebasePlanPreview = "git.rebasePlanPreview" case updatePlan = "git.updatePlan" case historyWindow = "git.historyWindow" + case graphProjection = "git.graphProjection" } // MARK: - git.normalizeChangeTargets diff --git a/macos/Sources/LitheGitModule/Models/GitGraphModels.swift b/macos/Sources/LitheGitModule/Models/GitGraphModels.swift index 0c4cd32a4e..bb61fbbac7 100644 --- a/macos/Sources/LitheGitModule/Models/GitGraphModels.swift +++ b/macos/Sources/LitheGitModule/Models/GitGraphModels.swift @@ -1,12 +1,12 @@ import Foundation +/// How much of a long edge the graph draws. Core owns the thresholds +/// (`git.graphProjection` `displayMode`); the host only picks the mode. package struct GitGraphDisplayOptions: Hashable, Sendable { - package static let compact = Self(longEdgeSize: 30, visiblePartSize: 1, edgeWithArrowSize: Int.max) - package static let expanded = Self(longEdgeSize: 1_000, visiblePartSize: 250, edgeWithArrowSize: 30) + package static let compact = Self(mode: "compact") + package static let expanded = Self(mode: "expanded") - let longEdgeSize: Int - let visiblePartSize: Int - let edgeWithArrowSize: Int + let mode: String } package enum GitGraphReferenceKind: String, Hashable, Sendable { @@ -74,12 +74,18 @@ package struct GitGraphLayout: Sendable { package let laneCount: Int package let hasMissingParents: Bool package let recommendedLaneCount: Int + /// Ancestry of the requested current branch, for the row background highlight. + package let currentBranchHashes: Set - package init(rows: [GitGraphRow], laneCount: Int, hasMissingParents: Bool, recommendedLaneCount: Int = 0) { + package init( + rows: [GitGraphRow], laneCount: Int, hasMissingParents: Bool, recommendedLaneCount: Int = 0, + currentBranchHashes: Set = [] + ) { self.rows = rows self.laneCount = laneCount self.hasMissingParents = hasMissingParents self.recommendedLaneCount = recommendedLaneCount + self.currentBranchHashes = currentBranchHashes } } diff --git a/macos/Sources/LitheGitModule/Models/GitGraphProjectionModels.swift b/macos/Sources/LitheGitModule/Models/GitGraphProjectionModels.swift new file mode 100644 index 0000000000..16f7aa7c24 --- /dev/null +++ b/macos/Sources/LitheGitModule/Models/GitGraphProjectionModels.swift @@ -0,0 +1,86 @@ +import Foundation + +// Wire types for Core's `git.graphProjection`. Core owns lanes, colors, routes, and +// labels (`shared/fixtures/git/graph-projection-v1.json`); the host builds the request +// and turns the response into its drawing models. + +package struct GitGraphProjectionRequest: Encodable, Sendable, Equatable { + package struct Commit: Encodable, Sendable, Equatable { + package let hash: String + package let parentHashes: [String] + package let decorations: String + + package init(hash: String, parentHashes: [String], decorations: String) { + self.hash = hash + self.parentHashes = parentHashes + self.decorations = decorations + } + } + + package let commits: [Commit] + package let remoteNames: [String] + package let repositoryCommits: [Commit] + package let visibleHashes: [String]? + package let displayMode: String + package let currentBranch: String? + + package init( + commits: [Commit], remoteNames: [String] = [], repositoryCommits: [Commit] = [], + visibleHashes: [String]? = nil, displayMode: String = "compact", currentBranch: String? = nil + ) { + self.commits = commits + self.remoteNames = remoteNames + self.repositoryCommits = repositoryCommits + self.visibleHashes = visibleHashes + self.displayMode = displayMode + self.currentBranch = currentBranch + } +} + +package struct GitGraphProjectionResponse: Decodable, Sendable { + package struct Label: Decodable, Sendable { + package let title: String + package let kind: String + } + + package struct ParentEdge: Decodable, Sendable { + package let id: String + package let parentHash: String + package let targetLane: Int? + package let colorId: Int + package let isMissing: Bool + } + + package struct PrintElement: Decodable, Sendable { + package let id: String + package let position: Int + package let adjacentPosition: Int + package let direction: String + package let colorId: Int + package let isDotted: Bool + package let hasArrow: Bool + package let isTerminal: Bool + package let targetHash: String? + } + + package struct Row: Decodable, Sendable { + package let commitHash: String + package let lane: Int + package let laneCount: Int + package let colorId: Int + package let layoutIndex: Int + package let incomingLaneColors: [Int] + package let parentEdges: [ParentEdge] + package let labels: [Label] + package let printElements: [PrintElement] + } + + package let rows: [Row] + package let laneCount: Int + package let recommendedLaneCount: Int + package let hasMissingParents: Bool + package let currentBranchHashes: [String] +} + +/// Runs one `git.graphProjection` call; `nil` means Core rejected the request. +package typealias GitGraphProjector = @Sendable (GitGraphProjectionRequest) async -> GitGraphProjectionResponse? diff --git a/macos/Sources/LitheGitModule/Services/GitGraphHeadOrdering.swift b/macos/Sources/LitheGitModule/Services/GitGraphHeadOrdering.swift deleted file mode 100644 index a83eadcb20..0000000000 --- a/macos/Sources/LitheGitModule/Services/GitGraphHeadOrdering.swift +++ /dev/null @@ -1,57 +0,0 @@ -// Adapted from IntelliJ GitRefManager, HeadCommitsComparator and NaturalComparator. -// Copyright 2000-2024 JetBrains s.r.o. and contributors. Apache-2.0. -// Swift adaptation: Lithe contributors. See macos/Resources/GitGraph/NOTICE.txt. -import Foundation -import LitheCoreContracts - -package enum GitGraphHeadOrdering { - static func sortedHeads(labels: [[GitGraphLabel]], children: [[Int]]) -> [Int] { - let best = labels.map(bestReference) - // A referenced branch may already have children. It still seeds DFS - // before less important graph tips; tags alone do not create a head. - return labels.indices.filter { - children[$0].isEmpty || labels[$0].contains { $0.kind != .tag } - }.sorted { left, right in - switch (best[left], best[right]) { - case let (a?, b?): - if a == b { return left < right } - return precedes(a, b) - case (_?, nil): return true - case (nil, _?): return false - case (nil, nil): return left < right - } - } - } - - static func bestReference(_ labels: [GitGraphLabel]) -> GitGraphLabel? { - labels.min(by: precedes) - } - - /// Java String.hashCode, used by IDEA's GraphColorManagerImpl for the - /// principal fragment of a referenced head. Unreferenced heads use zero. - static func colorID(for labels: [GitGraphLabel]) -> Int { - guard let ref = bestReference(labels) else { return 0 } - let hash = ref.title.utf16.reduce(Int32(0)) { ($0 &* 31) &+ Int32($1) } - return Int(hash) - } - - private static func precedes(_ left: GitGraphLabel, _ right: GitGraphLabel) -> Bool { - let a = priority(left), b = priority(right) - return a == b ? naturalCompare(Array(left.title.utf16), Array(right.title.utf16)) < 0 : a < b - } - - private static func priority(_ ref: GitGraphLabel) -> Int { - switch ref.kind { - case .remote: return ["origin/main", "origin/master"].contains(ref.title) ? 0 : 1 - case .branch: return ["main", "master"].contains(ref.title) ? 2 : 3 - case .tag: return 4 - case .head: return 6 - } - } - - /// IntelliJ `NaturalComparator` order for ref names. The algorithm is shared - /// with the Project tree through `NaturalNameOrder` in LitheCoreContracts. - package static func naturalCompare(_ a: [UInt16], _ b: [UInt16], ignoreCase: Bool = true) -> Int { - NaturalNameOrder.compare(a, b, ignoreCase: ignoreCase) - } -} diff --git a/macos/Sources/LitheGitModule/Services/GitGraphLayoutService.swift b/macos/Sources/LitheGitModule/Services/GitGraphLayoutService.swift index 7e1954ecda..9464d6bc65 100644 --- a/macos/Sources/LitheGitModule/Services/GitGraphLayoutService.swift +++ b/macos/Sources/LitheGitModule/Services/GitGraphLayoutService.swift @@ -1,60 +1,86 @@ import Foundation +/// Turns a loaded history window into the native graph models. The layout itself — +/// permanent layout, head ordering, colors, filtered topology, lanes, print elements — +/// is Core's `git.graphProjection`; this service builds the request and maps the answer. package enum GitGraphLayoutService { - /// CurrentBranchHighlighter colors ancestry, including every merge parent. - /// ponytail: only the loaded graph can prove membership; a missing parent - /// ends this walk. A complete repository graph can extend it without I/O in drawing. - package static func currentBranchHashes( - commits: [GitCommit], repositoryCommits: [GitCommit], references: [GitReference] - ) -> Set { - guard let branch = references.first(where: { $0.kind == .local && $0.isCurrent }) else { return [] } - let byHash = Dictionary((commits + repositoryCommits).map { ($0.hash, $0) }, - uniquingKeysWith: { first, _ in first }) - guard let head = (commits + repositoryCommits).first(where: { - labels(from: $0.decorations, remoteNames: []).contains { $0.kind == .branch && $0.title == branch.shortName } - }) else { return [] } - var pending = [head.hash] - var result = Set() - while let hash = pending.popLast() { - guard result.insert(hash).inserted else { continue } - pending.append(contentsOf: byHash[hash]?.parentHashes ?? []) + /// The Core request for one loaded window; the whole window is projected in one call. + package static func request( + commits: [GitCommit], + references: [GitReference] = [], + repositoryCommits: [GitCommit] = [], + visibleHashes: Set? = nil, + options: GitGraphDisplayOptions = .compact, + currentBranch: String? = nil + ) -> GitGraphProjectionRequest { + func identities(_ values: [GitCommit]) -> [GitGraphProjectionRequest.Commit] { + values.map { .init(hash: $0.hash, parentHashes: $0.parentHashes, decorations: $0.decorations) } } - return result + return GitGraphProjectionRequest( + commits: identities(commits), + remoteNames: references.filter { $0.kind == .remote }.map(\.shortName), + repositoryCommits: identities(repositoryCommits), + visibleHashes: visibleHashes.map { Array($0) }, + displayMode: options.mode, + currentBranch: currentBranch + ) } - /// Uses IntelliJ's permanent-layout, visible-graph and print-element rules. - /// Input stays in Git's child-before-parent order; filtering never mutates it. + /// Projects one loaded window through Core. `nil` means Core rejected the request. package static func layout( commits: [GitCommit], references: [GitReference] = [], repositoryCommits: [GitCommit] = [], visibleHashes: Set? = nil, - options: GitGraphDisplayOptions = .compact - ) -> GitGraphLayout { - guard !Task.isCancelled else { return GitGraphLayout(rows: [], laneCount: 0, hasMissingParents: false) } - let remoteNames = Set(references.filter { $0.kind == .remote }.map(\.shortName)) - func commitLabels(_ values: [GitCommit]) -> [[GitGraphLabel]] { - values.map { labels(from: $0.decorations, remoteNames: remoteNames) } - } - var orderedCommits = commits - var permanentGraph: GitGraphProjection? - let scopedHashes = Set(commits.map(\.hash)) - let repositoryHashes = Set(repositoryCommits.map(\.hash)) - // IDEA builds the permanent graph before applying the branch scope. - // Otherwise an older release ref can steal the main branch's layout - // when main's tip is outside the selected branch's first history page. - // Use only a complete, unique context; bounded-history misses fall back - // to the scoped graph instead of dropping commits or mixing indices. - if !repositoryCommits.isEmpty, repositoryHashes.count == repositoryCommits.count, - scopedHashes.isSubset(of: repositoryHashes) { - permanentGraph = GitGraphProjection(commits: repositoryCommits, labels: commitLabels(repositoryCommits), visibleHashes: nil) - let scopedByHash = Dictionary(commits.map { ($0.hash, $0) }, uniquingKeysWith: { first, _ in first }) - orderedCommits = repositoryCommits.compactMap { scopedByHash[$0.hash] } + options: GitGraphDisplayOptions = .compact, + currentBranch: String? = nil, + project: GitGraphProjector + ) async -> GitGraphLayout? { + guard !commits.isEmpty else { return GitGraphLayout(rows: [], laneCount: 0, hasMissingParents: false) } + let request = request( + commits: commits, references: references, repositoryCommits: repositoryCommits, + visibleHashes: visibleHashes, options: options, currentBranch: currentBranch + ) + guard let response = await project(request), !Task.isCancelled else { return nil } + return layout(commits: commits, response: response) + } + + /// Attaches the caller's commits to Core's rows; the first commit of a hash wins. + package static func layout(commits: [GitCommit], response: GitGraphProjectionResponse) -> GitGraphLayout? { + var byHash: [String: GitCommit] = [:] + for commit in commits where byHash[commit.hash] == nil { byHash[commit.hash] = commit } + var rows: [GitGraphRow] = [] + rows.reserveCapacity(response.rows.count) + for row in response.rows { + guard let commit = byHash[row.commitHash] else { return nil } + rows.append(GitGraphRow( + commit: commit, lane: row.lane, laneCount: row.laneCount, + incomingLaneColors: row.incomingLaneColors.map { Optional($0) }, + parentEdges: row.parentEdges.map { + GitGraphEdge(id: $0.id, parentHash: $0.parentHash, targetLane: $0.targetLane, + colorIndex: $0.colorId, isMissing: $0.isMissing) + }, + labels: row.labels.compactMap { label in + GitGraphReferenceKind(rawValue: label.kind).map { GitGraphLabel(title: label.title, kind: $0) } + }, + layoutIndex: row.layoutIndex, nodeColorIndex: row.colorId, + printElements: row.printElements.map { element in + // `:`; both halves of an edge share the edge ID. + let edgeID = element.id.lastIndex(of: ":").map { String(element.id[..<$0]) } ?? element.id + return GitGraphPrintElement( + edgeID: edgeID, position: element.position, adjacentPosition: element.adjacentPosition, + direction: element.direction == "down" ? .down : .up, colorIndex: element.colorId, + isDotted: element.isDotted, hasArrow: element.hasArrow, isTerminal: element.isTerminal, + targetHash: element.targetHash + ) + } + )) } - let graph = GitGraphProjection(commits: orderedCommits, labels: commitLabels(orderedCommits), - visibleHashes: visibleHashes, permanentGraph: permanentGraph) - guard !Task.isCancelled else { return GitGraphLayout(rows: [], laneCount: 0, hasMissingParents: false) } - return graph.layout(options: options) + return GitGraphLayout( + rows: rows, laneCount: response.laneCount, hasMissingParents: response.hasMissingParents, + recommendedLaneCount: response.recommendedLaneCount, + currentBranchHashes: Set(response.currentBranchHashes) + ) } package static func routingSnapshot(for layout: GitGraphLayout) -> GitGraphRoutingSnapshot { @@ -78,41 +104,12 @@ package enum GitGraphLayoutService { recommendedLaneCount: layout.recommendedLaneCount ) } +} - private static func labels(from decorations: String, remoteNames: Set) -> [GitGraphLabel] { - decorations - .split(separator: ",") - .flatMap { rawValue -> [GitGraphLabel] in - let raw = rawValue.trimmingCharacters(in: .whitespacesAndNewlines) - guard !raw.isEmpty else { return [] } - - if raw == "HEAD" { - return [GitGraphLabel(title: "HEAD", kind: .head)] - } - if raw.hasPrefix("HEAD -> ") { - let branch = localName(String(raw.dropFirst("HEAD -> ".count))) - return [ - GitGraphLabel(title: "HEAD", kind: .head), - GitGraphLabel(title: branch, kind: .branch) - ] - } - if raw.hasPrefix("tag: ") { - return [GitGraphLabel(title: String(raw.dropFirst("tag: ".count)), kind: .tag)] - } - if raw.hasPrefix("refs/tags/") { - return [GitGraphLabel(title: String(raw.dropFirst("refs/tags/".count)), kind: .tag)] - } - if remoteNames.contains(raw) || raw.hasPrefix("origin/") || raw.hasPrefix("refs/remotes/") { - let title = raw.hasPrefix("refs/remotes/") - ? String(raw.dropFirst("refs/remotes/".count)) - : raw - return [GitGraphLabel(title: title, kind: .remote)] - } - return [GitGraphLabel(title: localName(raw), kind: .branch)] - } - } - - private static func localName(_ name: String) -> String { - name.hasPrefix("refs/heads/") ? String(name.dropFirst("refs/heads/".count)) : name +extension GitFeatureModel { + /// Projects the loaded history window through Core off the main actor. + package var graphProjector: GitGraphProjector { + let service = service + return { request in await service.corePlan(.graphProjection, request) } } } diff --git a/macos/Sources/LitheGitModule/Services/GitGraphMissingParents.swift b/macos/Sources/LitheGitModule/Services/GitGraphMissingParents.swift deleted file mode 100644 index f8c447002e..0000000000 --- a/macos/Sources/LitheGitModule/Services/GitGraphMissingParents.swift +++ /dev/null @@ -1,67 +0,0 @@ -import Foundation - -/// Projects unloaded ancestors through hidden commits without storing a full -/// reachable-hash set at every hidden node. All input rows are topological. -enum GitGraphMissingParents { - /// Shared boundary DAG: local unloaded hashes and links to older groups. - /// Equal groups share an ID; single-parent paths with no local boundary - /// reuse their parent's ID instead of creating another traversal step. - private struct Group: Hashable { - let hashes: [String] - let parents: [Int] - } - - static func project( - commits: [GitCommit], byHash: [String: Int], parents: [[Int]], visible: [Int], - add: (Int, String) -> Void - ) { - guard !visible.isEmpty, !Task.isCancelled else { return } - let visibleRows = Set(visible) - var groupForRow = [Int?](repeating: nil, count: commits.count) - var groups: [Group] = [] - var groupIDs: [Group: Int] = [:] - for row in commits.indices.reversed() { - guard !Task.isCancelled else { return } - // A visible ancestor owns its own continuation. Duplicate page - // entries and unrelated hidden roots cannot introduce fake edges. - guard !visibleRows.contains(row), byHash[commits[row].hash] == row else { continue } - let hashes = Set(commits[row].parentHashes.filter { byHash[$0] == nil }).sorted() - let inherited = Set(parents[row].compactMap { groupForRow[$0] }).sorted() - if hashes.isEmpty, inherited.count <= 1 { - groupForRow[row] = inherited.first - } else { - let group = Group(hashes: hashes, parents: inherited) - if let id = groupIDs[group] { - groupForRow[row] = id - } else { - let id = groups.count - groups.append(group) - groupIDs[group] = id - groupForRow[row] = id - } - } - } - guard !groups.isEmpty else { return } - - // A traversal stamp avoids clearing an O(history-size) visited array - // for each visible commit. Only that commit's output hashes accumulate. - var visited = [Int](repeating: -1, count: groups.count) - for row in visible { - guard !Task.isCancelled else { return } - var pending = parents[row].compactMap { groupForRow[$0] } - var missing = Set() - while let id = pending.popLast() { - guard !Task.isCancelled else { return } - guard visited[id] != row else { continue } - visited[id] = row - missing.formUnion(groups[id].hashes) - pending.append(contentsOf: groups[id].parents) - } - let direct = Set(commits[row].parentHashes) - for hash in missing.sorted() where !direct.contains(hash) { - guard !Task.isCancelled else { return } - add(row, hash) - } - } - } -} diff --git a/macos/Sources/LitheGitModule/Services/GitGraphProjection.swift b/macos/Sources/LitheGitModule/Services/GitGraphProjection.swift deleted file mode 100644 index be7177496a..0000000000 --- a/macos/Sources/LitheGitModule/Services/GitGraphProjection.swift +++ /dev/null @@ -1,325 +0,0 @@ -// Portions adapted from JetBrains IntelliJ Community, Copyright 2000-2024 -// JetBrains s.r.o. and contributors, under the Apache License, Version 2.0. -// Swift adaptation: Lithe contributors. See -// .agents/notes/implemented/feature/2026-09-13-macos-git-graph-intellij-layout.md -// and macos/Resources/GitGraph/NOTICE.txt for the pinned sources and license. -import Foundation - -/// Permanent layout indices are deliberately independent of compact screen -/// columns. This is the macOS projection; it performs no I/O or native drawing. -struct GitGraphProjection { - private struct Edge { - let up: Int - let down: Int? - let parentHash: String - let dotted: Bool - var id: String { "\(up):\(down.map(String.init) ?? parentHash):\(dotted)" } - } - - private enum Element { - case node(Int) - case edge(Int) - } - - private let commits: [GitCommit] - private let labels: [[GitGraphLabel]] - private let visible: [Int] - private let indices: [Int] - private let colors: [Int] - private let edges: [Edge] - - init(commits: [GitCommit], labels: [[GitGraphLabel]], visibleHashes: Set?, permanentGraph: GitGraphProjection? = nil) { - self.commits = commits - self.labels = labels - // History normally has unique IDs. First occurrence wins for defensive - // handling of overlapping pages without making Dictionary trap. - var byHash: [String: Int] = [:] - for (row, commit) in commits.enumerated() where byHash[commit.hash] == nil { - byHash[commit.hash] = row - } - var parents = [[Int]](repeating: [], count: commits.count) - var children = parents - for (row, commit) in commits.enumerated() { - var seen = Set() - for hash in commit.parentHashes { - if let parent = byHash[hash], parent > row, seen.insert(parent).inserted { - parents[row].append(parent) - children[parent].append(row) - } - } - } - if let permanentGraph { - let permanentRows = Dictionary(uniqueKeysWithValues: permanentGraph.commits.enumerated().map { ($1.hash, $0) }) - indices = commits.map { permanentGraph.indices[permanentRows[$0.hash]!] } - colors = commits.map { permanentGraph.colors[permanentRows[$0.hash]!] } - } else { - let heads = GitGraphHeadOrdering.sortedHeads(labels: labels, children: children) - (indices, colors) = Self.permanentLayout(labels: labels, parents: parents, heads: heads) - } - visible = commits.indices.filter { byHash[commits[$0].hash] == $0 && (visibleHashes?.contains(commits[$0].hash) ?? true) } - let visibleRows = Dictionary(uniqueKeysWithValues: visible.enumerated().map { ($1, $0) }) - var result: [Edge] = [] - var pairs = Set() - func add(_ up: Int, _ down: Int, dotted: Bool) { - guard let u = visibleRows[up], let d = visibleRows[down], u < d, - pairs.insert("\(u):\(d)").inserted else { return } - result.append(Edge(up: u, down: d, parentHash: commits[down].hash, dotted: dotted)) - } - for row in visible { - for parent in parents[row] where visibleRows[parent] != nil { add(row, parent, dotted: false) } - var seen = Set() - for hash in commits[row].parentHashes where byHash[hash] == nil && seen.insert(hash).inserted { - result.append(Edge(up: visibleRows[row]!, down: nil, parentHash: hash, dotted: false)) - } - } - if visibleHashes != nil { - Self.dottedEdges(parents: parents, children: children, visible: Set(visible), add: { add($0, $1, dotted: true) }) - GitGraphMissingParents.project(commits: commits, byHash: byHash, parents: parents, visible: visible) { row, hash in - result.append(Edge(up: visibleRows[row]!, down: nil, parentHash: hash, dotted: true)) - } - } - edges = result.sorted { - if $0.up != $1.up { return $0.up < $1.up } - if $0.down != $1.down { return ($0.down ?? Int.max) < ($1.down ?? Int.max) } - return $0.parentHash < $1.parentHash - } - } - - private static func permanentLayout(labels: [[GitGraphLabel]], parents: [[Int]], heads: [Int]) -> ([Int], [Int]) { - var indices = [Int](repeating: 0, count: parents.count) - var colors = indices - var nextParent = indices - var layoutIndex = 1 - for head in heads { - guard indices[head] == 0 else { continue } - var stack = [head] - let headIndex = layoutIndex - let headColor = GitGraphHeadOrdering.colorID(for: labels[head]) - while let node = stack.last { - let firstVisit = indices[node] == 0 - if firstVisit { - indices[node] = layoutIndex - // GraphColorGetterByHead + GraphColorManagerImpl: the head - // fragment uses its reference name; side fragments use LI. - colors[node] = layoutIndex == headIndex ? headColor : layoutIndex - } - while nextParent[node] < parents[node].count && indices[parents[node][nextParent[node]]] != 0 { - nextParent[node] += 1 - } - if nextParent[node] < parents[node].count { - stack.append(parents[node][nextParent[node]]) - } else { - if firstVisit { layoutIndex += 1 } - stack.removeLast() - } - } - } - return (indices, colors) - } - - /// IntelliJ DottedFilterEdgesGenerator's two directional number walks. - /// Nearest-visible propagation avoids an exponential ancestor path search. - private static func dottedEdges(parents: [[Int]], children: [[Int]], visible: Set, add: (Int, Int) -> Void) { - var numbers = [Int](repeating: Int.min, count: parents.count) - for node in parents.indices { - if visible.contains(node) { - var nearest = Int.min - var adjacent = Int.min - for child in children[node] { - if visible.contains(child) { adjacent = max(adjacent, numbers[child]) } - else { nearest = max(nearest, numbers[child]) } - } - if nearest == adjacent || nearest == Int.min { numbers[node] = adjacent } - else { add(nearest, node); numbers[node] = nearest } - } else { - numbers[node] = children[node].reduce(Int.min) { - max($0, visible.contains($1) ? $1 : numbers[$1]) - } - } - } - numbers = [Int](repeating: Int.max, count: parents.count) - for node in parents.indices.reversed() { - if visible.contains(node) { - var nearest = Int.max - var adjacent = Int.max - for parent in parents[node] { - if visible.contains(parent) { adjacent = min(adjacent, numbers[parent]) } - else { nearest = min(nearest, numbers[parent]) } - } - if nearest == adjacent || nearest == Int.max { numbers[node] = adjacent } - else { add(node, nearest); numbers[node] = nearest } - } else { - numbers[node] = parents[node].reduce(Int.max) { - min($0, visible.contains($1) ? $1 : numbers[$1]) - } - } - } - } - - func layout(options: GitGraphDisplayOptions) -> GitGraphLayout { - guard !visible.isEmpty else { return GitGraphLayout(rows: [], laneCount: 0, hasMissingParents: false) } - // Values from the pinned PrintElementGeneratorImpl. Even expanded mode - // caps extreme edges while retaining direction arrows for ordinary long edges. - let longEdgeSize = options.longEdgeSize - let visiblePartSize = options.visiblePartSize - var elements = visible.indices.map { [Element.node($0)] } - var adjacent = [[Int]](repeating: [], count: visible.count) - for (id, edge) in edges.enumerated() { - adjacent[edge.up].append(id) - if let down = edge.down { - adjacent[down].append(id) - guard down > edge.up + 1 else { continue } - if down - edge.up < longEdgeSize { - for row in (edge.up + 1)..= longEdgeSize && offset == visiblePartSize) - || (span >= options.edgeWithArrowSize && offset == 1) - } else { - // IDEA places unloaded-parent arrows on the next - // row, never stacked on the last visible node. - arrow = direction == .down && row == edge.up + 1 - } - guard nextPosition != nil || arrow else { continue } - // Nodes never draw a terminal for a normal edge without - // a neighbour; only long-edge intermediate elements do. - prints.append(GitGraphPrintElement( - edgeID: edge.id, position: position, adjacentPosition: nextPosition ?? position, - direction: direction, colorIndex: edgeColor(edge), isDotted: edge.dotted, - hasArrow: arrow, isTerminal: nextPosition == nil, - targetHash: edge.down.map { commits[visible[direction == .down ? $0 : edge.up]].hash } - )) - } - } - } - let node = visible[row] - rows.append(GitGraphRow( - commit: commits[node], lane: nodePositions[row], laneCount: elements[row].count, - incomingLaneColors: elements[row].map { element in - if case .edge(let id) = element { return edgeColor(edges[id]) } - return colors[node] - }, - parentEdges: adjacent[row].compactMap { id in - let edge = edges[id] - guard edge.up == row else { return nil } - return GitGraphEdge(id: edge.id, parentHash: edge.parentHash, - targetLane: row + 1 < visible.count ? positions[row + 1][id] : nil, - colorIndex: edgeColor(edge), isMissing: edge.down == nil) - }, - labels: labels[node], layoutIndex: indices[node], - nodeColorIndex: colors[node], printElements: prints - )) - } - return GitGraphLayout(rows: rows, laneCount: elements.map(\.count).max() ?? 0, - hasMissingParents: edges.contains { $0.down == nil }, - recommendedLaneCount: recommendedWidth(options: options)) - } - - /// IntelliJ's weighted mean plus deviation. Difference intervals produce - /// the same per-row edge counts without scanning every live edge per row. - private func recommendedWidth(options: GitGraphDisplayOptions) -> Int { - let count = min(20_000, visible.count) - guard count > 1 else { return count } - var changes = [Int](repeating: 0, count: visible.count + 1) - var missing = [Int](repeating: 0, count: visible.count) - func add(_ lower: Int, _ upper: Int) { - changes[lower] += 1 - changes[upper] -= 1 - } - for edge in edges { - guard let down = edge.down else { missing[edge.up] += 1; continue } - if down - edge.up < options.longEdgeSize { - add(edge.up, down) - } else { - add(edge.up, edge.up + options.visiblePartSize + 1) - add(down - options.visiblePartSize, down) - } - } - let weightRatio = 0.1 - var current = 0, previous = 0 - var sum = 0.0, squares = 0.0 - for row in 0.. Int { - let up = visible[edge.up] - guard let down = edge.down.map({ visible[$0] }) else { return colors[up] } - return colors[indices[up] > indices[down] ? up : down] - } - - private func stableElementKey(_ element: Element) -> Int { - switch element { case .node: -1; case .edge(let id): id } - } - - /// Direct translation of GraphElementComparatorByLayoutIndex. These rules - /// also order crossing edges without keeping unrelated empty lane slots. - private func compare(_ lhs: Element, _ rhs: Element) -> Int { - switch (lhs, rhs) { - case (.node, .node): return 0 - case (.edge(let e), .node(let n)): return compare(edge: edges[e], node: n) - case (.node(let n), .edge(let e)): return -compare(edge: edges[e], node: n) - case (.edge(let a), .edge(let b)): - let first = edges[a], second = edges[b] - guard let firstDown = first.down else { return -compare(edge: second, node: first.up) } - guard let secondDown = second.down else { return compare(edge: first, node: second.up) } - if first.up == second.up { - return firstDown < secondDown ? -compare(edge: second, node: firstDown) : compare(edge: first, node: secondDown) - } - return first.up < second.up ? compare(edge: first, node: second.up) : -compare(edge: second, node: first.up) - } - } - - private func compare(edge: Edge, node: Int) -> Int { - let nodeIndex = indices[visible[node]] - guard let down = edge.down else { return indices[visible[edge.up]] - nodeIndex } - let edgeIndex = max(indices[visible[edge.up]], indices[visible[down]]) - return edgeIndex != nodeIndex ? edgeIndex - nodeIndex : edge.up - node - } -} diff --git a/macos/Tests/LitheCoreVerifier/CoreVerification.swift b/macos/Tests/LitheCoreVerifier/CoreVerification.swift index e9307ca847..ce14e23b2b 100644 --- a/macos/Tests/LitheCoreVerifier/CoreVerification.swift +++ b/macos/Tests/LitheCoreVerifier/CoreVerification.swift @@ -10,7 +10,6 @@ struct CoreVerification { verifySharedContractFixtures() verifyDiffParser() verifyVisibilityRules() - verifyGitGraph() verifyWhitespaceModes() verifySearchOptions() print("Core verification passed: shared fixtures, diff, visibility, graph, search options, and whitespace modes") @@ -70,26 +69,6 @@ struct CoreVerification { let operationError: OperationError? } - private struct GitFixture: Decodable { - struct Commit: Decodable { - let hash: String - let parents: [String] - let subject: String - let decorations: String - } - - struct Expected: Decodable { - let rowCount: Int - let mergeRow: Int - let mergeParentCount: Int - let hasMissingParents: Bool - let headLabel: String - } - - let commits: [Commit] - let expected: Expected - } - private static func verifySharedContractFixtures() { let searchURL = URL(fileURLWithPath: "shared/fixtures/search/basic.json") guard let searchData = try? Data(contentsOf: searchURL), @@ -141,31 +120,6 @@ struct CoreVerification { require(actual == fixtureCase.expected, "search fixture case failed: \(fixtureCase.name)") } - let gitURL = URL(fileURLWithPath: "shared/fixtures/git/graph.json") - guard let gitData = try? Data(contentsOf: gitURL), - let gitFixture = try? JSONDecoder().decode(GitFixture.self, from: gitData) else { - require(false, "Git contract fixture could not be decoded") - return - } - let commits = gitFixture.commits.map { commit in - GitCommit( - hash: commit.hash, - shortHash: commit.hash, - parentHashes: commit.parents, - authorName: "Fixture", - authorEmail: "fixture@example.com", - date: "2026/08/02 10:00", - subject: commit.subject, - decorations: commit.decorations - ) - } - let layout = GitGraphLayoutService.layout(commits: commits) - let mergeRow = layout.rows[gitFixture.expected.mergeRow] - require(layout.rows.count == gitFixture.expected.rowCount, "Git fixture row count changed") - require(mergeRow.parentEdges.count == gitFixture.expected.mergeParentCount, "Git fixture merge edge count changed") - require(layout.hasMissingParents == gitFixture.expected.hasMissingParents, "Git fixture missing-parent state changed") - require(mergeRow.labels.contains { $0.title == gitFixture.expected.headLabel }, "Git fixture HEAD label changed") - let commandURL = URL(fileURLWithPath: "shared/fixtures/git/command-response-v1.json") guard let commandData = try? Data(contentsOf: commandURL), let commandFixture = try? JSONDecoder().decode(GitCommandFixture.self, from: commandData) else { @@ -258,23 +212,6 @@ struct CoreVerification { ) } - private static func verifyGitGraph() { - let root = commit(hash: "root", parents: [], subject: "root", decorations: "") - let side = commit(hash: "side", parents: ["root"], subject: "side", decorations: "feature/orders") - let main = commit( - hash: "main", - parents: ["side", "root"], - subject: "merge", - decorations: "HEAD -> main" - ) - let layout = GitGraphLayoutService.layout(commits: [main, side, root]) - require(layout.rows.count == 3, "expected three graph rows") - require(layout.rows[0].isMerge, "expected merge commit") - require(layout.rows[0].parentEdges.count == 2, "expected two merge parent edges") - require(layout.rows[0].parentEdges.allSatisfy { !$0.isMissing }, "merge parents should be present") - require(layout.rows[0].labels.contains { $0.kind == .head }, "HEAD label should be parsed") - } - private static func verifyWhitespaceModes() { require(GitDiffWhitespaceMode.allCases.count == 2, "expected two whitespace modes") require(GitDiffWhitespaceMode.doNotIgnore.title == "Do not ignore", "default whitespace label changed") @@ -301,24 +238,6 @@ struct CoreVerification { require(regularExpression.matches("UserService42", query: "UserService\\d+"), "regex search should match a pattern") } - private static func commit( - hash: String, - parents: [String], - subject: String, - decorations: String - ) -> GitCommit { - GitCommit( - hash: hash, - shortHash: hash, - parentHashes: parents, - authorName: "Test", - authorEmail: "test@example.com", - date: "2026/08/02 10:00", - subject: subject, - decorations: decorations - ) - } - private static func require(_ condition: @autoclosure () -> Bool, _ message: String) { guard condition() else { fputs("Core verification failed: \(message)\n", stderr) diff --git a/macos/Tests/LitheExecutionModuleTests/ExecutionModuleTests.swift b/macos/Tests/LitheExecutionModuleTests/ExecutionModuleTests.swift index 9ea249e931..53cbedb730 100644 --- a/macos/Tests/LitheExecutionModuleTests/ExecutionModuleTests.swift +++ b/macos/Tests/LitheExecutionModuleTests/ExecutionModuleTests.swift @@ -448,6 +448,15 @@ struct ExecutionModuleTests { #expect(service.testOutcomes(for: "java").map(\.project) == ["b"]) } + @Test + func coverageNamingACaseWithoutItsSuiteIsRejectedAndNeverWidenedToTheProject() throws { + let json = try JSONSerialization.data(withJSONObject: [ + "tests": [], "summary": ["total": 0, "passed": 0, "failed": 0, "errors": 0, "skipped": 0], + "success": true, "coverage": [["project": "a", "case": "kept"]], + ] as [String: Any]) + #expect(throws: DecodingError.self) { try JSONDecoder().decode(BuildTestResults.self, from: json) } + } + @Test func backendTestsIgnoreCancelledRequestsThatReturnAfterReplacement() async throws { let service = LanguageTestService(outcomeResolver: LinkedCoreTestRunOutcome(), executableResolver: TestExecutableResolver(), processFactory: { TestStreamingProcess() }) diff --git a/macos/Tests/LitheGitGraphVerifier/GitGraphVerification.swift b/macos/Tests/LitheGitGraphVerifier/GitGraphVerification.swift deleted file mode 100644 index d34a212f6e..0000000000 --- a/macos/Tests/LitheGitGraphVerifier/GitGraphVerification.swift +++ /dev/null @@ -1,100 +0,0 @@ -import Foundation -import LitheGitModule - -@main -struct GitGraphVerification { - static func main() { - verifyLinearHistory() - verifyMergeHistory() - verifyMissingParent() - verifyDecorationLabels() - verifyLaneContinuity() - print("GitGraph verification passed: linear, merge, truncated parent, labels, and lane continuity") - } - - /// Compact columns may move; every nonterminal half-edge must meet the - /// corresponding half in the next row, with its identity and color intact. - private static func verifyLaneContinuity() { - let layout = GitGraphLayoutService.layout(commits: [ - commit("H", parents: ["G", "E"]), commit("G", parents: ["F"]), - commit("F", parents: ["D"]), commit("E", parents: ["D"]), - commit("D", parents: ["C"]), commit("C", parents: ["B"]), - commit("B", parents: ["A"]), commit("A", parents: []) - ]) - for (index, row) in layout.rows.enumerated() { - for edge in row.printElements where edge.direction == .down && !edge.isTerminal { - expect(index + 1 < layout.rows.count, "a continuing edge needs a next row") - expect(layout.rows[index + 1].printElements.contains { - $0.edgeID == edge.edgeID && $0.direction == .up - && $0.position == edge.adjacentPosition && $0.adjacentPosition == edge.position - && $0.colorIndex == edge.colorIndex - }, "a compacted edge must join its adjacent half") - } - } - } - - private static func verifyLinearHistory() { - let layout = GitGraphLayoutService.layout(commits: [ - commit("C", parents: ["B"]), - commit("B", parents: ["A"]), - commit("A", parents: []) - ]) - expect(layout.laneCount == 1, "linear history should use one lane") - expect(layout.rows.map { $0.lane } == [0, 0, 0], "linear history lane positions") - expect(!layout.hasMissingParents, "linear history should not report missing parents") - } - - private static func verifyMergeHistory() { - let layout = GitGraphLayoutService.layout(commits: [ - commit("M", parents: ["D", "C"]), - commit("D", parents: ["B"]), - commit("C", parents: ["B"]), - commit("B", parents: []) - ]) - expect(layout.laneCount == 2, "merge history should use two lanes") - expect(layout.rows[0].parentEdges.map { $0.targetLane } == [0, 1], "merge parents should fork") - expect(layout.rows[1].lane == 0 && layout.rows[2].lane == 1, "branch commits should stay on separate lanes") - expect(layout.rows[2].parentEdges.first?.targetLane == 0, "branch should converge into first-parent lane") - } - - private static func verifyMissingParent() { - let layout = GitGraphLayoutService.layout(commits: [ - commit("HEAD", parents: ["OLDER-COMMIT"]) - ]) - expect(layout.hasMissingParents, "truncated history should report missing parent") - expect(layout.rows[0].parentEdges.first?.targetLane == nil, "missing parent should terminate at the row edge") - expect(layout.rows[0].parentEdges.first?.isMissing == true, "missing parent edge should be marked") - } - - private static func verifyDecorationLabels() { - let layout = GitGraphLayoutService.layout(commits: [ - commit("A", parents: [], decorations: "HEAD -> main, origin/main, tag: v1.0") - ]) - let expectedIDs = ["head:HEAD", "branch:main", "remote:origin/main", "tag:v1.0"] - expect(layout.rows[0].labels.map(\.id) == expectedIDs, "decorations should become typed labels") - } - - private static func commit( - _ hash: String, - parents: [String], - decorations: String = "" - ) -> GitCommit { - GitCommit( - hash: hash, - shortHash: String(hash.prefix(7)), - parentHashes: parents, - authorName: "lick", - authorEmail: "lick@example.com", - date: "2026/08/01 12:00", - subject: hash, - decorations: decorations - ) - } - - private static func expect(_ condition: @autoclosure () -> Bool, _ message: String) { - guard condition() else { - fputs("GitGraph verification failed: \(message)\n", stderr) - exit(1) - } - } -} diff --git a/macos/Tests/LitheGitModuleTests/GitGraphLayoutTests.swift b/macos/Tests/LitheGitModuleTests/GitGraphLayoutTests.swift index eed23b4774..7709997b66 100644 --- a/macos/Tests/LitheGitModuleTests/GitGraphLayoutTests.swift +++ b/macos/Tests/LitheGitModuleTests/GitGraphLayoutTests.swift @@ -1,340 +1,122 @@ import Foundation +import LitheGitTestSupport @testable import LitheGitModule import Testing -@Suite("IntelliJ Git graph parity") +/// Layout rules belong to Rust Core (`git.graphProjection`); its tests and +/// `shared/fixtures/git/graph-projection-v1.json` define them. These tests run the real linked +/// Core and assert how the macOS models carry its answer. +@Suite("Git graph through Core") struct GitGraphLayoutTests { - @Test("Current branch background follows every merge parent, not lane or row adjacency") - func currentBranchMembership() { - let refs = [GitReference(fullName: "refs/heads/main", shortName: "main", kind: .local, - peelsToCommit: true, - isCurrent: true, upstreamShortName: nil)] - let commits = [commit("head", ["left", "merged"], "HEAD -> main"), - commit("other", ["base"], "other"), commit("left", ["base"])] - let repository = [commit("merged", ["base"]), commit("base", ["missing"])] - let hashes = GitGraphLayoutService.currentBranchHashes(commits: commits, repositoryCommits: repository, references: refs) - #expect(hashes == ["head", "left", "merged", "base", "missing"]) - #expect(!hashes.contains("other")) - #expect(GitGraphLayoutService.currentBranchHashes(commits: commits, repositoryCommits: repository, references: []).isEmpty) - #expect(GitGraphLayoutService.currentBranchHashes(commits: [commit("detached", [], "HEAD")], - repositoryCommits: [], references: refs).isEmpty) - } - - @Test("DFS indices match pinned IntelliJ fixtures", arguments: ["manyNodes", "oneNode", "notFullGraph", "oneNodeNotFullGraph"]) - func upstreamLayout(_ name: String) throws { - let input = try fixture("layoutBuilder", name, "in") - let expected = try fixture("layoutBuilder", name, "out").split(separator: "\n").map { - Int($0.components(separatedBy: "|-")[0])! - } - let commits = input.split(separator: "\n").map { line in - let parts = line.components(separatedBy: "|-") - return commit(parts[0], parts[1].split(separator: " ").map(String.init)) - } - #expect(GitGraphLayoutService.layout(commits: commits).rows.map(\.layoutIndex) == expected) - } - - @Test("Compact positions and half-edge routing match IntelliJ golden outputs", - arguments: ["oneNode", "manyNodes", "longEdges", "oneUpOneDown1", "oneUpOneDown2"]) - func upstreamPrinting(_ name: String) throws { - let input = try fixture("elementGenerator", name, "in") - var commits: [GitCommit] = [] - var visible = Set() - for line in input.split(separator: "\n") { - let parts = line.components(separatedBy: "|-") - let id = String(parts[0].split(separator: "_")[0]) - visible.insert(id) - var hidden: [GitCommit] = [] - let parents = parts[1].split(separator: " ").map { token -> String in - let fields = token.split(separator: "_") - let target = String(fields[0]) - // Git commits only carry direct edges. A hidden intermediate - // commit recreates the upstream fixture's DOTTED edge naturally. - if fields[1] == "D" { - let hash = "hidden-\(id)-\(target)" - hidden.append(commit(hash, [target])) - return hash - } - return target - } - commits.append(commit(id, parents)) - commits.append(contentsOf: hidden) - } - let options = GitGraphDisplayOptions( - longEdgeSize: name == "oneUpOneDown2" ? 10 : 7, - visiblePartSize: name.hasPrefix("oneUpOneDown") ? 1 : 2, - edgeWithArrowSize: 10 - ) - let layout = GitGraphLayoutService.layout(commits: commits, visibleHashes: visible, options: options) - let expected = try fixture("elementGenerator", name, "out").split(separator: "\n").map { line -> String in - let parts = line.trimmingCharacters(in: .whitespaces).components(separatedBy: "|-") - // The color callback in JetBrains's fixture uses row numbers. - // Compare its verbatim geometry/style/arrow oracle, excluding color. - return parts[0] + "|" + parts[1] - }.sorted() - let actual = layout.rows.enumerated().flatMap { row, value -> [String] in - ["Node|\(row):\(value.lane)"] + value.printElements.map { element in - let direction = element.direction == .down ? "DOWN" : "UP" - let arrow = element.hasArrow ? "_ARROW" : "" - let style = element.isDotted ? "DASHED" : "SOLID" - return "Edge:\(direction)\(arrow):\(style)|\(row):\(element.position):\(element.adjacentPosition)" - } - }.sorted() - #expect(actual == expected) - assertContinuity(layout) - } - - @Test("30-row compact threshold preserves commits and exposes both destinations", arguments: [29, 30, 31]) - func longEdgeBoundary(_ span: Int) throws { - let commits = longEdge(span) - let layout = GitGraphLayoutService.layout(commits: commits) - let arrows = layout.rows.flatMap(\.printElements).filter(\.hasArrow) - #expect(layout.rows.count == commits.count) - if span < 30 { #expect(arrows.isEmpty) } - else { - #expect(arrows.count == 2) - #expect(Set(arrows.compactMap(\.targetHash)) == ["0", String(span)]) - #expect(layout.rows[span / 2].laneCount == 1) - } - assertContinuity(layout) - } - - @Test("Expanded mode keeps the 1,000-row safety threshold", arguments: [999, 1_000]) - func expandedBoundary(_ span: Int) { - let layout = GitGraphLayoutService.layout(commits: longEdge(span), options: .expanded) - #expect(layout.rows[span / 2].laneCount == (span < 1_000 ? 2 : 1)) - #expect(layout.rows.flatMap(\.printElements).filter(\.hasArrow).count == (span < 1_000 ? 2 : 4)) - assertContinuity(layout) - } - - @Test("Filtering bridges hidden ancestors without inventing unloaded parents") - func filterProjection() { - let commits = [commit("a", ["b"]), commit("b", ["c"]), commit("c", ["d"]), commit("d", [])] - let layout = GitGraphLayoutService.layout(commits: commits, visibleHashes: ["a", "d"]) - #expect(layout.rows.map(\.commit.hash) == ["a", "d"]) + @Test("A linear history stays in one lane and keeps its commits and labels") + func linear() throws { + let commits = [commit("C", ["B"], "HEAD -> main"), commit("B", ["A"]), commit("A", [])] + let layout = GitGraphCoreTestSupport.layout(commits: commits) + #expect(layout.rows.map(\.commit.hash) == ["C", "B", "A"]) + #expect(layout.rows.map(\.lane) == [0, 0, 0]) #expect(layout.laneCount == 1) #expect(!layout.hasMissingParents) - #expect(layout.rows.flatMap(\.printElements).allSatisfy { $0.isDotted }) - #expect(layout.rows[0].parentEdges.map(\.parentHash) == ["d"]) + #expect(layout.rows[0].labels.map(\.id) == ["head:HEAD", "branch:main"]) + #expect(layout.rows[0].nodeColorIndex == 3_343_801) + #expect(layout.rows[0].parentEdges.map(\.targetLane) == [0]) assertContinuity(layout) } - @Test("Filtered ancestors retain the unloaded boundary and resolve it after paging") - func filteredMissingParent() throws { - let page = [commit("a", ["b"]), commit("b", ["c"]), commit("unrelated", [])] - let lastRow = GitGraphLayoutService.layout(commits: page, visibleHashes: ["a"]) - #expect(lastRow.hasMissingParents) - #expect(lastRow.rows[0].parentEdges.map(\.parentHash) == ["c"]) - #expect(lastRow.rows[0].parentEdges.allSatisfy { $0.isMissing }) - #expect(lastRow.rows[0].printElements.isEmpty) - - let filtered = GitGraphLayoutService.layout(commits: page, visibleHashes: ["a", "unrelated"]) - #expect(filtered.hasMissingParents) - let prints = filtered.rows.flatMap(\.printElements) - #expect(!prints.isEmpty) - #expect(prints.allSatisfy { $0.isDotted && $0.targetHash == nil }) - #expect(prints.contains { $0.hasArrow && $0.isTerminal }) - assertContinuity(filtered) - - let loaded = page + [commit("c", [])] - let hiddenRoot = GitGraphLayoutService.layout(commits: loaded, visibleHashes: ["a", "unrelated"]) - #expect(!hiddenRoot.hasMissingParents) - #expect(hiddenRoot.rows[0].parentEdges.isEmpty) - let visibleRoot = GitGraphLayoutService.layout(commits: loaded, visibleHashes: ["a", "c"]) - #expect(!visibleRoot.hasMissingParents) - #expect(visibleRoot.rows[0].parentEdges.map(\.parentHash) == ["c"]) - #expect(visibleRoot.rows.flatMap(\.printElements).allSatisfy { $0.isDotted }) - assertContinuity(visibleRoot) - } - - @Test("Missing projection deduplicates hidden merge paths and stops at visible ancestors") - func filteredMissingMergePaths() { - let commits = [commit("a", ["left", "right", "missing"]), commit("peer", ["left"]), - commit("left", ["missing", "missing"]), commit("right", ["missing", "other"]), - commit("unrelated", ["unrelated-missing"])] - let layout = GitGraphLayoutService.layout(commits: commits, visibleHashes: ["a", "peer"]) - #expect(layout.hasMissingParents) - #expect(layout.rows[0].parentEdges.map(\.parentHash) == ["missing", "other"]) - #expect(layout.rows[1].parentEdges.map(\.parentHash) == ["missing"]) - let direct = layout.rows[0].parentEdges.first { $0.parentHash == "missing" } - #expect(layout.rows[0].printElements.filter { $0.edgeID == direct?.id }.allSatisfy { !$0.isDotted }) - - let stopped = GitGraphLayoutService.layout(commits: [commit("a", ["b"]), commit("b", ["c"]), commit("c", ["missing"])], - visibleHashes: ["a", "b"]) - #expect(stopped.rows[0].parentEdges.map(\.parentHash) == ["b"]) - #expect(stopped.rows[0].parentEdges.allSatisfy { !$0.isMissing }) - #expect(stopped.rows[1].parentEdges.map(\.parentHash) == ["missing"]) - let unrelated = GitGraphLayoutService.layout(commits: [commit("a", []), commit("hidden", ["missing"])], visibleHashes: ["a"]) - #expect(!unrelated.hasMissingParents) - } - - @Test("An ended branch gives its column back instead of leaving a hole") - func compactColumns() { - let layout = GitGraphLayoutService.layout(commits: [commit("a", ["b", "c"]), commit("b", []), commit("c", ["d"]), commit("d", [])]) - #expect(layout.rows[1].laneCount == 2) - #expect(layout.rows[2].laneCount == 1) - #expect(layout.rows[2].lane == 0) + @Test("A merge forks into a second lane and converges into the first-parent lane") + func merge() { + let layout = GitGraphCoreTestSupport.layout(commits: [ + commit("M", ["D", "C"]), commit("D", ["B"]), commit("C", ["B"]), commit("B", [])]) + #expect(layout.laneCount == 2) + #expect(layout.rows[0].parentEdges.map(\.targetLane) == [0, 1]) + #expect(layout.rows.map(\.lane) == [0, 0, 1, 0]) + #expect(layout.rows[2].parentEdges.first?.targetLane == 0) + #expect(layout.rows[0].isMerge) assertContinuity(layout) } - @Test("Pagination resolves missing parents without fake navigation targets") + @Test("A truncated parent is marked missing and has no navigation target") func missingParent() { - let head = commit("a", ["b", "b"]) - let page = GitGraphLayoutService.layout(commits: [head]) - #expect(page.hasMissingParents) - #expect(page.rows[0].parentEdges.count == 1) - #expect(page.rows[0].printElements.isEmpty) - #expect(page.rows[0].printElements.allSatisfy { $0.targetHash == nil }) - let full = GitGraphLayoutService.layout(commits: [head, commit("b", [])]) - #expect(!full.hasMissingParents) - #expect(full.rows[0].nodeColorIndex == page.rows[0].nodeColorIndex) - assertContinuity(full) - } - - @Test("Empty filters produce no graph or missing-history notice") - func emptyGraph() { - #expect(GitGraphLayoutService.layout(commits: []).rows.isEmpty) - let layout = GitGraphLayoutService.layout(commits: [commit("a", ["b"])], visibleHashes: []) - #expect(layout.rows.isEmpty) - #expect(layout.laneCount == 0) - #expect(!layout.hasMissingParents) - } - - @Test("5,000 hidden merge boundaries keep only the visible result", arguments: [false, true]) - func filteredMissingParentScaling(_ emptyFilter: Bool) throws { - // Each merge adds a distinct unloaded parent. Copying every suffix's - // full set retained ~12.5 million members for a one-row result. - let count = 5_000 - let history = (0.. GitCommit in - var parents = ["missing-\(row)"] - if row + 1 < count { parents.insert(String(row + 1), at: 0) } - return commit(String(row), parents) - } - let visible: Set = emptyFilter ? [] : ["0"] - let started = ContinuousClock.now - let layout = GitGraphLayoutService.layout(commits: history, visibleHashes: visible) - print("Filtered missing graph 5000, empty=\(emptyFilter): \(ContinuousClock.now - started)") - if emptyFilter { - #expect(layout.rows.isEmpty) - #expect(!layout.hasMissingParents) - } else { - #expect(layout.rows.count == 1) - let row = try #require(layout.rows.first) - #expect(Set(row.parentEdges.map(\.parentHash)) == Set((0..