From 7e4e62da3d18fdcdbe53c639668ff0356545f3d5 Mon Sep 17 00:00:00 2001 From: Mazze LeCzzare Frazer Date: Wed, 23 Sep 2026 04:58:29 -0400 Subject: [PATCH 1/5] Fix circuit edge updates and isolation reports --- Package.swift | 29 +++--- .../SynapseCore/Circuit/CircuitTypes.swift | 11 ++- .../SynapseCore/Circuit/SynapticCircuit.swift | 1 + Sources/SynapseCore/SynapseCore.swift | 24 +++-- Sources/contextsynapse/main.swift | 34 ++++--- Tests/BayesianConvergenceTests.swift | 95 ++++++++++++++++++- 6 files changed, 152 insertions(+), 42 deletions(-) diff --git a/Package.swift b/Package.swift index f9fa0c5..4cdc87d 100644 --- a/Package.swift +++ b/Package.swift @@ -1,18 +1,25 @@ // swift-tools-version:5.8 import PackageDescription +var products: [Product] = [ + .executable(name: "contextsynapse", targets: ["contextsynapse"]), + .library(name: "SynapseCore", targets: ["SynapseCore"]) +] + +var targets: [Target] = [ + .target(name: "SynapseCore", path: "Sources/SynapseCore"), + .executableTarget(name: "contextsynapse", dependencies: ["SynapseCore"], path: "Sources/contextsynapse"), + .testTarget(name: "BayesianConvergenceTests", dependencies: ["SynapseCore"], path: "Tests") +] + +#if os(macOS) +products.append(.executable(name: "ContextSynapseApp", targets: ["ContextSynapseApp"])) +targets.append(.executableTarget(name: "ContextSynapseApp", dependencies: ["SynapseCore"], path: "Sources/ContextSynapseApp")) +#endif + let package = Package( name: "ContextSynapse", platforms: [.macOS(.v13)], - products: [ - .executable(name: "contextsynapse", targets: ["contextsynapse"]), - .executable(name: "ContextSynapseApp", targets: ["ContextSynapseApp"]), - .library(name: "SynapseCore", targets: ["SynapseCore"]) - ], - targets: [ - .target(name: "SynapseCore", path: "Sources/SynapseCore"), - .executableTarget(name: "contextsynapse", dependencies: ["SynapseCore"], path: "Sources/contextsynapse"), - .executableTarget(name: "ContextSynapseApp", dependencies: ["SynapseCore"], path: "Sources/ContextSynapseApp"), - .testTarget(name: "BayesianConvergenceTests", dependencies: ["SynapseCore"], path: "Tests") - ] + products: products, + targets: targets ) diff --git a/Sources/SynapseCore/Circuit/CircuitTypes.swift b/Sources/SynapseCore/Circuit/CircuitTypes.swift index afb7efc..f83ef59 100644 --- a/Sources/SynapseCore/Circuit/CircuitTypes.swift +++ b/Sources/SynapseCore/Circuit/CircuitTypes.swift @@ -254,15 +254,20 @@ public struct CircuitEdge: Sendable, Codable, Equatable { } public init(source: UUID, target: UUID, weight: Double) { - self.id = UUID() + self.init(id: UUID(), source: source, target: target, weight: weight) + } + + private init(id: UUID, source: UUID, target: UUID, weight: Double) { + self.id = id self.sourceID = source self.targetID = target self.weight = max(0.0, min(1.0, weight)) } - /// Returns a copy with updated weight (edges are immutable from outside the circuit). + /// Returns a copy with updated weight while preserving the edge identity. + /// Callers retain the original ID for future updates and persistence references. public func withWeight(_ newWeight: Double) -> CircuitEdge { - CircuitEdge(source: sourceID, target: targetID, weight: newWeight) + CircuitEdge(id: id, source: sourceID, target: targetID, weight: newWeight) } } diff --git a/Sources/SynapseCore/Circuit/SynapticCircuit.swift b/Sources/SynapseCore/Circuit/SynapticCircuit.swift index fb8bf56..badda95 100644 --- a/Sources/SynapseCore/Circuit/SynapticCircuit.swift +++ b/Sources/SynapseCore/Circuit/SynapticCircuit.swift @@ -345,6 +345,7 @@ public actor SynapticCircuit { } } } + guard !next.isEmpty else { break } frontier = next depth += 1 } diff --git a/Sources/SynapseCore/SynapseCore.swift b/Sources/SynapseCore/SynapseCore.swift index dbeb3c7..f51c631 100644 --- a/Sources/SynapseCore/SynapseCore.swift +++ b/Sources/SynapseCore/SynapseCore.swift @@ -282,6 +282,18 @@ public class SynapseCore { /// Fault injection probability (0.0 by default). Can be set via env var CONTEXT_SYNAPSE_FAULT_PROB public var faultProbability: Double = 0.0 + + /// Sanitize a user identifier so it can only name a local state directory. + /// Path separators, traversal dots, whitespace, and other punctuation are dropped; + /// ASCII letters, digits, hyphen, and underscore are preserved. + public static func sanitizeUserIdentifier(_ user: String) -> String { + let allowedScalars = Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_".unicodeScalars) + var sanitized = "" + for scalar in user.unicodeScalars where allowedScalars.contains(scalar) { + sanitized.unicodeScalars.append(scalar) + } + return sanitized + } /// Simple logging helper for debugging and error tracking private func logError(_ message: String, error: Error? = nil) { @@ -290,15 +302,11 @@ public class SynapseCore { } public init(folderName: String = "ContextSynapse", user: String = "default") { - // Validate and sanitize user input to prevent directory traversal - // Remove path separators and dots to prevent traversal attacks - let sanitizedUser = user - .components(separatedBy: CharacterSet(charactersIn: "/\\:.")) - .joined() + // Validate and sanitize user input to prevent directory traversal. + let sanitizedUser = Self.sanitizeUserIdentifier(user) - // Ensure the sanitized user is not empty and is alphanumeric with limited special chars - guard !sanitizedUser.isEmpty, - sanitizedUser.rangeOfCharacter(from: CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-_"))) != nil else { + // Ensure the sanitized user is not empty after dropping unsupported characters. + guard !sanitizedUser.isEmpty else { fatalError("Invalid user identifier: must contain alphanumeric characters") } diff --git a/Sources/contextsynapse/main.swift b/Sources/contextsynapse/main.swift index 2379b48..cc5b2eb 100644 --- a/Sources/contextsynapse/main.swift +++ b/Sources/contextsynapse/main.swift @@ -21,9 +21,9 @@ while scanIndex < args.count { let core = SynapseCore(user: selectedUser) // MARK: - Lighthouse persistence -// Stored in AppSupport alongside run logs so Edgar remembers -// the lighthouse across invocations within a session. -// File: ~/Library/Application Support/ContextSynapse//lighthouse.json +// Stored in the same sanitized per-user AppSupport directory as config, +// regions, and run logs so Edgar remembers the lighthouse across invocations. +// File: ~/Library/Application Support/ContextSynapse/users//lighthouse.json private struct LighthouseRecord: Codable { let id: String @@ -33,16 +33,14 @@ private struct LighthouseRecord: Codable { let setAt: String } -func lighthouseStorageURL(user: String) -> URL { - let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! - return base - .appendingPathComponent("ContextSynapse") - .appendingPathComponent(user) +func lighthouseStorageURL(core: SynapseCore) -> URL { + core.usersDir + .appendingPathComponent(core.currentUser) .appendingPathComponent("lighthouse.json") } -func loadLighthouse(user: String) -> SynapseContent? { - let url = lighthouseStorageURL(user: user) +func loadLighthouse(core: SynapseCore) -> SynapseContent? { + let url = lighthouseStorageURL(core: core) guard let data = try? Data(contentsOf: url), let record = try? JSONDecoder().decode(LighthouseRecord.self, from: data) else { return nil @@ -55,8 +53,8 @@ func loadLighthouse(user: String) -> SynapseContent? { ) } -func saveLighthouse(_ content: SynapseContent, user: String) { - let url = lighthouseStorageURL(user: user) +func saveLighthouse(_ content: SynapseContent, core: SynapseCore) { + let url = lighthouseStorageURL(core: core) try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) let record = LighthouseRecord( id: content.id, @@ -70,8 +68,8 @@ func saveLighthouse(_ content: SynapseContent, user: String) { } } -func clearLighthouse(user: String) { - try? FileManager.default.removeItem(at: lighthouseStorageURL(user: user)) +func clearLighthouse(core: SynapseCore) { + try? FileManager.default.removeItem(at: lighthouseStorageURL(core: core)) } // MARK: - --lighthouse and --resync @@ -79,7 +77,7 @@ func clearLighthouse(user: String) { if let lighthouseIdx = args.firstIndex(of: "--lighthouse"), lighthouseIdx + 1 < args.count { let label = args[lighthouseIdx + 1] let content = SynapseContent(id: UUID().uuidString, text: label) - saveLighthouse(content, user: selectedUser) + saveLighthouse(content, core: core) RavenRenderer.render(state: .perched, frameIndex: 0, lighthouseLabel: label, rotScore: 0.0) print("") @@ -89,7 +87,7 @@ if let lighthouseIdx = args.firstIndex(of: "--lighthouse"), lighthouseIdx + 1 < } if args.contains("--resync") { - clearLighthouse(user: selectedUser) + clearLighthouse(core: core) RavenRenderer.render(state: .resync, frameIndex: 0, lighthouseLabel: nil, rotScore: 0.0) print("") print("\u{001B}[38;5;51m⚓ Lighthouse cleared. Set a new one with --lighthouse \"description\"\u{001B}[0m") @@ -277,7 +275,7 @@ let currentContent = SynapseContent( functionNames: [] ) -let activeLighthouse = loadLighthouse(user: selectedUser) +let activeLighthouse = loadLighthouse(core: core) var rotScore: Double = 0.0 var edgarState: RavenState = .dormant @@ -330,7 +328,7 @@ let run = SynapseCore.RunLog( chosenDomain: chosenDomain, assembledPrompt: finalPrompt, context: [ - "user": selectedUser, + "user": core.currentUser, "app": flagApp ?? "unknown", "focus": flagFocus ?? "unknown", "timeBucket": activeTriggers.joined(separator: ","), diff --git a/Tests/BayesianConvergenceTests.swift b/Tests/BayesianConvergenceTests.swift index 3df0a77..2da7c80 100644 --- a/Tests/BayesianConvergenceTests.swift +++ b/Tests/BayesianConvergenceTests.swift @@ -11,11 +11,19 @@ final class BayesianConvergenceTests: XCTestCase { } @discardableResult - private func runProcess(executable: String, arguments: [String], in directory: URL) throws -> (status: Int32, stdout: String, stderr: String) { + private func runProcess( + executable: String, + arguments: [String], + in directory: URL, + environment: [String: String]? = nil + ) throws -> (status: Int32, stdout: String, stderr: String) { let process = Process() process.currentDirectoryURL = directory process.executableURL = URL(fileURLWithPath: executable) process.arguments = arguments + if let environment { + process.environment = environment + } let stdoutPipe = Pipe() let stderrPipe = Pipe() @@ -208,6 +216,56 @@ final class BayesianConvergenceTests: XCTestCase { XCTAssertEqual(reloadedRegions.map { $0.name }, ["NorthAmerica", "EMEA", "APAC"]) } + + func testUserIdentifierSanitizationDropsUnsupportedCharacters() throws { + let rawUser = " Ada/../Name:🔥_Team-42 " + XCTAssertEqual(SynapseCore.sanitizeUserIdentifier(rawUser), "AdaName_Team-42") + + let core = SynapseCore( + folderName: "ContextSynapseTests_UserSanitize_\(UUID().uuidString)", + user: rawUser + ) + defer { try? FileManager.default.removeItem(at: core.appSupport) } + + XCTAssertEqual(core.currentUser, "AdaName_Team-42") + XCTAssertTrue(core.configURL.path.contains("/users/AdaName_Team-42/config.json")) + } + + func testLighthouseUsesSanitizedUserDirectory() throws { + let executable = try ensureCLIExecutable() + let rawUser = "../Ada.Name-\(UUID().uuidString)" + + let setResult = try runProcess( + executable: executable.path, + arguments: ["--user", rawUser, "--lighthouse", "Keep research local"], + in: repositoryRootURL() + ) + XCTAssertEqual(setResult.status, 0, "Lighthouse command failed.\nstdout:\n\(setResult.stdout)\nstderr:\n\(setResult.stderr)") + + let verificationCore = SynapseCore(user: rawUser) + let expectedURL = verificationCore.usersDir + .appendingPathComponent(verificationCore.currentUser) + .appendingPathComponent("lighthouse.json") + let legacyUnsafeURL = verificationCore.appSupport + .appendingPathComponent(rawUser) + .appendingPathComponent("lighthouse.json") + defer { + try? FileManager.default.removeItem(at: verificationCore.usersDir.appendingPathComponent(verificationCore.currentUser)) + try? FileManager.default.removeItem(at: legacyUnsafeURL.deletingLastPathComponent().standardizedFileURL) + } + + XCTAssertTrue(FileManager.default.fileExists(atPath: expectedURL.path), "Lighthouse should be stored with the sanitized user state") + XCTAssertFalse(FileManager.default.fileExists(atPath: legacyUnsafeURL.standardizedFileURL.path), "Lighthouse should not be written through the raw --user path") + + let queryResult = try runProcess( + executable: executable.path, + arguments: ["--user", rawUser, "stay aligned"], + in: repositoryRootURL() + ) + XCTAssertEqual(queryResult.status, 0, "Query command failed.\nstdout:\n\(queryResult.stdout)\nstderr:\n\(queryResult.stderr)") + XCTAssertTrue(queryResult.stdout.contains("Keep research local"), "Query should reload the lighthouse from the sanitized user state") + } + func testExportAndImportAcceptUserFlagBeforeCommandFlag() throws { let executable = try ensureCLIExecutable() let tempDir = FileManager.default.temporaryDirectory @@ -220,7 +278,7 @@ final class BayesianConvergenceTests: XCTestCase { in: repositoryRootURL() ) XCTAssertEqual(exportResult.status, 0, "Export command failed.\nstdout:\n\(exportResult.stdout)\nstderr:\n\(exportResult.stderr)") - XCTAssertTrue(exportResult.stdout.contains("Successfully exported state"), "Unexpected export output: \(exportResult.stdout)") + XCTAssertTrue(exportResult.stdout.contains("session folded"), "Unexpected export output: \(exportResult.stdout)") XCTAssertTrue(FileManager.default.fileExists(atPath: exportFile.path), "Export file was not created") let importResult = try runProcess( @@ -234,3 +292,36 @@ final class BayesianConvergenceTests: XCTestCase { try? FileManager.default.removeItem(at: exportFile) } } + +extension BayesianConvergenceTests { + func testUpdatingEdgeWeightPreservesEdgeIdentity() async throws { + let circuit = SynapticCircuit() + let source = SynapticNode(synapseID: "source") + let target = SynapticNode(synapseID: "target") + let edge = CircuitEdge(source: source.id, target: target.id, weight: 0.2) + + await circuit.register(source) + await circuit.register(target) + await circuit.connect(edge) + await circuit.updateEdgeWeight(id: edge.id, weight: 0.8) + await circuit.updateEdgeWeight(id: edge.id, weight: 0.5) + + let snapshot = await circuit.snapshot() + XCTAssertEqual(snapshot.edges.count, 1) + XCTAssertEqual(snapshot.edges.first?.id, edge.id) + XCTAssertEqual(snapshot.edges.first?.weight, 0.5) + } + + func testFaultInjectionReportsIsolatedNodeAsTooIsolated() async throws { + let circuit = SynapticCircuit() + let isolatedNode = SynapticNode(synapseID: "isolated") + await circuit.register(isolatedNode) + _ = await circuit.forwardPass() + + let report = await circuit.injectFault(intoSynapse: "isolated", severity: 1.0) + XCTAssertEqual(report.propagationDepth, 0) + XCTAssertEqual(report.affectedNodeCount, 0) + XCTAssertTrue(report.isTooIsolated) + XCTAssertFalse(report.isHealthy) + } +} From 2c25e37b2c976f39e9bc1079990e2062e077facb Mon Sep 17 00:00:00 2001 From: Mazze LeCzzare Frazer <225266999+mazze93@users.noreply.github.com> Date: Wed, 21 Oct 2026 17:47:50 -0400 Subject: [PATCH 2/5] fix(tests): mark throwing SynapseCore init with try in PersistenceFailureTests #40 made SynapseCore.init(folderName:user:baseOverride:) throwing; the persistence-failure tests landed on main afterwards and called it without try, so CI failed to compile. Verified locally: swift build + swift test, 226 tests, 0 failures. Signed-off-by: Mazze LeCzzare Frazer Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TfxFgJK5GcRzMzXfgumDM8 --- Tests/PersistenceFailureTests.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tests/PersistenceFailureTests.swift b/Tests/PersistenceFailureTests.swift index a4b8c1a..234ccf3 100644 --- a/Tests/PersistenceFailureTests.swift +++ b/Tests/PersistenceFailureTests.swift @@ -32,7 +32,7 @@ final class PersistenceFailureTests: XCTestCase { let root = try makeReadOnlyRoot() defer { makeWritableAgain(root) } - let core = SynapseCore(folderName: "CS_\(UUID().uuidString)", + let core = try SynapseCore(folderName: "CS_\(UUID().uuidString)", user: "u", baseOverride: root) @@ -46,7 +46,7 @@ final class PersistenceFailureTests: XCTestCase { let root = try makeReadOnlyRoot() defer { makeWritableAgain(root) } - let core = SynapseCore(folderName: "CS_\(UUID().uuidString)", + let core = try SynapseCore(folderName: "CS_\(UUID().uuidString)", user: "u", baseOverride: root) @@ -70,7 +70,7 @@ final class PersistenceFailureTests: XCTestCase { try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: root) } - let core = SynapseCore(folderName: "CS_\(UUID().uuidString)", + let core = try SynapseCore(folderName: "CS_\(UUID().uuidString)", user: "u", baseOverride: root) From 1153ae0ac6da6cbc1dda8d3cf47ed3bf9981b614 Mon Sep 17 00:00:00 2001 From: Mazze LeCzzare Date: Thu, 29 Oct 2026 19:43:23 -0400 Subject: [PATCH 3/5] fix(storage): preserve existing case-variant default owners --- Sources/SynapseCore/UserStorage.swift | 9 ++++++--- Tests/UserStorageTests.swift | 28 +++++++++++++++++++++++++++ docs/journal/DECISIONS.md | 4 ++++ 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/Sources/SynapseCore/UserStorage.swift b/Sources/SynapseCore/UserStorage.swift index f477570..4f29105 100644 --- a/Sources/SynapseCore/UserStorage.swift +++ b/Sources/SynapseCore/UserStorage.swift @@ -25,9 +25,7 @@ enum UserStorage { let forbidden = CharacterSet.controlCharacters.union(CharacterSet(charactersIn: "/\\:")) guard !user.isEmpty, user.utf8.count <= 200, user.rangeOfCharacter(from: forbidden) == nil, - user.rangeOfCharacter(from: .alphanumerics) != nil, - // The nonthrowing built-in default initializer owns this namespace. - user.lowercased() != "default" || user == "default" else { + user.rangeOfCharacter(from: .alphanumerics) != nil else { throw ValidationError.invalidIdentifier } let fm = FileManager.default @@ -43,6 +41,11 @@ enum UserStorage { guard profile.id == user else { throw ValidationError.conflictingOwner } } } else { + // Preserve exact existing owners (including Default/DEFAULT), but + // reserve new case variants of the built-in namespace. + guard user.lowercased() != "default" || user == "default" else { + throw ValidationError.invalidIdentifier + } let legacy = user.components(separatedBy: CharacterSet(charactersIn: "/\\:.")).joined() if legacy != user, !legacy.isEmpty, fm.fileExists(atPath: usersDir.appendingPathComponent(legacy).path) { diff --git a/Tests/UserStorageTests.swift b/Tests/UserStorageTests.swift index 2789622..f367679 100644 --- a/Tests/UserStorageTests.swift +++ b/Tests/UserStorageTests.swift @@ -76,6 +76,34 @@ final class UserStorageTests: XCTestCase { } } + func testExistingDefaultCaseVariantRetainsItsOwnerAndState() throws { + for name in ["Default", "DEFAULT"] { + try withRoot { root in + let directory = root.appendingPathComponent("ContextSynapse/users/" + name) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let profile = UserProfile(id: name, displayName: name, createdAt: "old", lastUsedAt: "old") + let profileURL = directory.appendingPathComponent("profile.json") + try JSONEncoder().encode(profile).write(to: profileURL) + let marker = Data("existing session".utf8) + try marker.write(to: directory.appendingPathComponent("session.json")) + let core = try SynapseCore(user: name, baseOverride: root) + XCTAssertEqual(core.currentUser, name) + XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("session.json")), marker) + let owner = try JSONDecoder().decode(UserProfile.self, from: Data(contentsOf: profileURL)) + XCTAssertEqual(owner.id, name) + } + } + } + + func testNewDefaultCaseVariantsAreRejectedBeforeWrites() throws { + try withRoot { root in + for name in ["Default", "DEFAULT"] { + XCTAssertThrowsError(try SynapseCore(user: name, baseOverride: root)) + } + XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("ContextSynapse").path)) + } + } + func testInvalidIdentifiersThrowBeforeCreatingState() throws { try withRoot { root in for name in ["", "🔥", "***", "..", "../Ada", "Ada/B", "Ada\\B", "Ada:B", "Ada\nB"] { diff --git a/docs/journal/DECISIONS.md b/docs/journal/DECISIONS.md index 8c5a220..ce3a12c 100644 --- a/docs/journal/DECISIONS.md +++ b/docs/journal/DECISIONS.md @@ -251,3 +251,7 @@ - 2026-10-05 · Reconcile PR #40 with current main before storage repair: keep main's edge identity, LighthouseStore migration, strict concurrency, GUI persistence seam and later session/ledger work; retain PR #40's isolated-frontier depth fix and move its new circuit coverage to a sibling test file · PR #44 contains overlapping older implementations but is not an ancestor of main; its unique-added-file check against main is empty, which alone does not establish commit equivalence. No PR was closed or merged · reverse: revert the PR #40 repair commit, not the earlier main changes. - 2026-10-05 · Preserve safe raw user names (including spaces and dots) instead of dropping characters; reject invalid input with a recoverable error before state writes; refuse ambiguous legacy aliases and profile/case conflicts rather than guessing ownership · preserves existing space-named config/regions/logs/session state and uses main's raw-name lighthouse migration. A historical dot-stripped directory must be selected explicitly or backed up and renamed by its owner · reverse: provide an explicit, owner-confirmed migration tool before relaxing ambiguity checks. + +## 2026-10-29 — PR #40 final review repair + +- 2026-10-29 · Preserve existing exact-owned `Default`/`DEFAULT` namespaces before rejecting creation of new variants of the built-in default. Greptile identified that the early validation guard made legacy saved state inaccessible. Move the reservation to the new-directory branch and test existing ownership/session preservation plus rejection before writes. Reverse: revert this focused validation adjustment only if a replacement preserves existing owners. From 358e7a01d4b87fd13b908a871342367a6c59cd6c Mon Sep 17 00:00:00 2001 From: Mazze LeCzzare Frazer Date: Mon, 9 Nov 2026 20:40:05 +0000 Subject: [PATCH 4/5] fix(storage): report a legacy alias by its stored spelling On a case-insensitive volume the stripped legacy name can match a directory spelled differently. The error then named an identifier that failed the exact-name check with conflictingOwner. Report the on-disk entry instead, and cover it with a regression test (skipped on case-sensitive volumes). Co-Authored-By: Claude Opus 5.5 --- Sources/SynapseCore/UserStorage.swift | 13 ++++++++++++- Tests/UserStorageTests.swift | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/Sources/SynapseCore/UserStorage.swift b/Sources/SynapseCore/UserStorage.swift index 4f29105..a345876 100644 --- a/Sources/SynapseCore/UserStorage.swift +++ b/Sources/SynapseCore/UserStorage.swift @@ -49,8 +49,19 @@ enum UserStorage { let legacy = user.components(separatedBy: CharacterSet(charactersIn: "/\\:.")).joined() if legacy != user, !legacy.isEmpty, fm.fileExists(atPath: usersDir.appendingPathComponent(legacy).path) { - throw ValidationError.ambiguousLegacy(legacy) + // Report the name as stored on disk: on a case-insensitive volume + // `legacy` may match a directory spelled differently, and only the + // stored spelling passes the exact-name check above. + throw ValidationError.ambiguousLegacy(storedName(matching: legacy, in: usersDir) ?? legacy) } } } + + /// The directory entry that `name` resolves to on this volume: an exact + /// match first, then a case- or normalization-insensitive one. + static func storedName(matching name: String, in usersDir: URL) -> String? { + guard let names = try? FileManager.default.contentsOfDirectory(atPath: usersDir.path) else { return nil } + if names.contains(name) { return name } + return names.first { $0.compare(name, options: [.caseInsensitive]) == .orderedSame } + } } diff --git a/Tests/UserStorageTests.swift b/Tests/UserStorageTests.swift index f367679..c7ca15e 100644 --- a/Tests/UserStorageTests.swift +++ b/Tests/UserStorageTests.swift @@ -62,6 +62,24 @@ final class UserStorageTests: XCTestCase { } } + func testAmbiguousLegacyNamesTheStoredSpelling() throws { + try withRoot { root in + _ = try SynapseCore(user: "adaname", baseOverride: root) + let usersDir = root.appendingPathComponent("ContextSynapse/users") + guard FileManager.default.fileExists(atPath: usersDir.appendingPathComponent("AdaName").path) else { + throw XCTSkip("Case-sensitive volume: the legacy alias cannot differ from the stored name by case.") + } + XCTAssertThrowsError(try UserStorage.validate("Ada.Name", usersDir: usersDir)) { error in + guard case UserStorage.ValidationError.ambiguousLegacy(let key) = error else { + return XCTFail("Expected ambiguousLegacy, got \(error)") + } + // The reported name must be the one that opens the stored state. + XCTAssertEqual(key, "adaname") + XCTAssertNoThrow(try UserStorage.validate(key, usersDir: usersDir)) + } + } + } + func testConflictingProfileIsNotOverwritten() throws { try withRoot { root in let directory = root.appendingPathComponent("ContextSynapse/users/Ada") From b18a16fb752b5fb7a8265d3443ca5466baac607a Mon Sep 17 00:00:00 2001 From: Mazze LeCzzare Frazer Date: Mon, 9 Nov 2026 20:44:25 +0000 Subject: [PATCH 5/5] test(storage): check the stored-spelling alias outside the error handler XCTAssertThrowsError's handler is non-throwing, so the follow-up validate call inside it failed to compile. Capture the reported key and assert on it after the throw. Co-Authored-By: Claude Opus 5.5 --- Tests/UserStorageTests.swift | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/Tests/UserStorageTests.swift b/Tests/UserStorageTests.swift index c7ca15e..770cbea 100644 --- a/Tests/UserStorageTests.swift +++ b/Tests/UserStorageTests.swift @@ -69,13 +69,18 @@ final class UserStorageTests: XCTestCase { guard FileManager.default.fileExists(atPath: usersDir.appendingPathComponent("AdaName").path) else { throw XCTSkip("Case-sensitive volume: the legacy alias cannot differ from the stored name by case.") } + var reported: String? XCTAssertThrowsError(try UserStorage.validate("Ada.Name", usersDir: usersDir)) { error in - guard case UserStorage.ValidationError.ambiguousLegacy(let key) = error else { - return XCTFail("Expected ambiguousLegacy, got \(error)") + if case UserStorage.ValidationError.ambiguousLegacy(let key) = error { + reported = key + } else { + XCTFail("Expected ambiguousLegacy, got \(error)") } - // The reported name must be the one that opens the stored state. - XCTAssertEqual(key, "adaname") - XCTAssertNoThrow(try UserStorage.validate(key, usersDir: usersDir)) + } + // The reported name must be the one that opens the stored state. + XCTAssertEqual(reported, "adaname") + if let reported { + XCTAssertNoThrow(try UserStorage.validate(reported, usersDir: usersDir)) } } }