diff --git a/.swiftformat b/.swiftformat index f3d4fa5..cf56aab 100644 --- a/.swiftformat +++ b/.swiftformat @@ -1,3 +1,4 @@ --swiftversion 6.3 --language-mode 5 --indent tab +--test-case-name-format preserve # convention is backticked sentence names; filter-safe camelCase exceptions allowed (#195, #31/#134) diff --git a/.swiftlint.yml b/.swiftlint.yml index 28bac03..2250019 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -1,7 +1,14 @@ disabled_rules: - trailing_comma # SE-0439 allows them in Swift 6; SwiftFormat adds them + - identifier_name # short closure params/locals (tv/ns/lo/hi) are idiomatic, not a signal + - inclusive_language # master/masterRoot profile-root vocabulary is deliberate domain naming (2026-11-17) + - file_length # deliberately large cohesive units + - type_body_length # deliberately large cohesive units + - nesting # idiomatic nested CodingKeys/enums + - optional_data_string_conversion # intentional lossy String(decoding:) for process/file output excluded: - DerivedData + - spike # throwaway SPM experiments, not built into any target line_length: warning: 140 error: 180 diff --git a/AGENTS.md b/AGENTS.md index fae1b62..559067e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -135,7 +135,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (6992 symbols, 33873 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **museion** (7035 symbols, 34056 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). @@ -181,12 +181,15 @@ This project is indexed by GitNexus as **museion** (6992 symbols, 33873 relation ### Tooling & gates -- Bare `swiftlint .` exits 2 on main (error-severity findings in `spike/` + one tests file) — any lint GATE must scope to the pushed/changed Swift files, never the whole tree (#190) +- Repo-wide lint is green (#194 disabled deliberate-style rules; #195/#196 cleared every finding — `spike/` stays excluded as unbuilt experiments): bare `swiftlint .` reports zero violations and `swiftformat .` reformats nothing. Lint GATEs still scope to the pushed/changed Swift files, never the whole tree (settled #190 design) +- xcodebuild can serve STALE binaries on a source edited seconds before invocation (zero `SwiftCompile` lines, suite starts 3 s in) — rapid edit→test cycles and flip runs must `touch` the file and verify `SwiftCompile` lines in the run log before trusting any green (#197) +- SwiftFormat's default `swiftTestingTestCaseNames` rewrites camelCase `@Test` names back into backticked sentence style — renaming a test to a filter-safe plain identifier (#195, #31/#134) needs `--test-case-name-format preserve` in `.swiftformat`; `standard-identifiers` would dirty all ~496 backticked test names repo-wide - git resolves short refs through `refs/tags/` before `refs/remotes/` — hooks and scripts spell `refs/remotes//` in full or a fetched tag named `origin/main` shadows the ref (#190) - A bash function invoked before its definition no-ops (`command not found`) under `set -uo` without `-e` — hoist definitions above first use and guard rig verdicts by executed-check count, never the banner (#190) ### Testing - A model-owned real-clock ticker races a test's injected decisive ticks — a >1 s main-actor stall lets the live ticker complete a met goal first, flipping pins on elapsed-time text; give `start(...)` a `spawnsTicker: Bool = true` seam and opt machine tests out (#162) +- Two FSEvent-burst rescans can double-count one shared `PostScanCache` miss (both snapshot the count before either stamps it) → `contentRevision` double-bumps, benign over-invalidation — tests pinning settled-state revision must quiesce the burst (stability loop ≥ the 0.5 s FSEvents latency) before snapshotting (#197) - Real-Process fake-ACP tests flake under concurrent build/analyze load — verify a failure in isolation and run the definitive full suite on an idle machine (#30) - Verify xcodebuild runs by the xcresult executed count, never the SUCCEEDED banner — single-name `-only-testing` filters can match zero free-function Swift Testing tests and "pass" vacuously (#31); suite-member names with spaces/backticks ALSO fail to match — run the whole suite and count (#134) - `xcresulttool totalTestCount` counts a Swift Testing parameterized `@Test` as ONE test — its per-argument executions are `nodeType: "Arguments"` children; reconcile executed-count arithmetic from the children, not the function total (#178) @@ -217,6 +220,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | +| 2026-11-17 | [20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md](docs/devlog/20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md) | | 2026-11-17 | [20261117-issue190-full-test-verify-rail-pre-push-hook_log.md](docs/devlog/20261117-issue190-full-test-verify-rail-pre-push-hook_log.md) | | 2026-11-13 | [20261113-fold-typing-budget-pin_log.md](docs/devlog/20261113-fold-typing-budget-pin_log.md) | | 2026-11-13 | [20261113-cold-turkey-full-tokenization_log.md](docs/devlog/20261113-cold-turkey-full-tokenization_log.md) | diff --git a/Museion/LearningsPaneView.swift b/Museion/LearningsPaneView.swift index 598aea9..a346680 100644 --- a/Museion/LearningsPaneView.swift +++ b/Museion/LearningsPaneView.swift @@ -75,8 +75,10 @@ nonisolated enum LearningsIndex { ) else { return [] } var groups: [Group] = [] for dir in typeDirs.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) { - guard isPlainDirectory(dir), !dir.lastPathComponent.hasPrefix("."), let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) - else { continue } + guard isPlainDirectory(dir), !dir.lastPathComponent.hasPrefix("."), + let files = try? FileManager.default.contentsOfDirectory( + at: dir, includingPropertiesForKeys: nil, + ) else { continue } // #27: the pass clock feeds the decay verdict — clocked dirs // carry their count, foreign dirs nil (no verdict; Entry's audit). let currentPass = LearningDecay.isClocked(dir.lastPathComponent) @@ -109,9 +111,14 @@ nonisolated enum LearningsIndex { return groups } + /// Parens load-bearing for readability — `&&` out-binds `??` (probed; + /// a finish-audit misread the bare form as a dead symlink clause). + /// lstat semantics: a symlink-to-dir reports isDirectory=false, so + /// both halves refuse it; the link clause is the belt for any future + /// resolved-URL caller. private static func isPlainDirectory(_ url: URL) -> Bool { let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) - return values?.isDirectory ?? false && !(values?.isSymbolicLink ?? false) + return (values?.isDirectory ?? false) && !(values?.isSymbolicLink ?? false) } } diff --git a/Museion/MentorSessionModel.swift b/Museion/MentorSessionModel.swift index 7008445..a6f519b 100644 --- a/Museion/MentorSessionModel.swift +++ b/Museion/MentorSessionModel.swift @@ -149,13 +149,17 @@ nonisolated enum SessionRoster { let dir = directory ?? defaultDirectory do { try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + let rosterURL = URL(fileURLWithPath: dir).appendingPathComponent("sessions.json") try JSONEncoder().encode(entries).write( - to: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json"), + to: rosterURL, options: .atomic, ) // Finish-audit: names+ids only, but piece titles are the writer's // business — the default umask would hand them to every local user. - try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json").path) + // ponytail: post-hoc chmod leaves a sub-second world-readable window + // between write and chmod — createFile(0600)+rename if a hostile + // local account ever matters. + try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: rosterURL.path) } catch { // ponytail: the roster is a convenience index; a write failure must not crash the gate. } diff --git a/Museion/OutlineEditorView.swift b/Museion/OutlineEditorView.swift index b476b7b..98e5ed4 100644 --- a/Museion/OutlineEditorView.swift +++ b/Museion/OutlineEditorView.swift @@ -55,10 +55,7 @@ nonisolated enum OutlinePresenter { _ nodes: [OutlineNode], folded: Set, zoomRootID: UUID? = nil, ) -> [Row] { var rows: [Row] = [] - if let zoomRootID, - let rootPath = path(of: zoomRootID, in: nodes), - let root = node(at: rootPath, in: nodes) - { + if let zoomRootID, let rootPath = path(of: zoomRootID, in: nodes), let root = node(at: rootPath, in: nodes) { walk(root.children, parent: rootPath, depth: 0, folded: folded, into: &rows) } else { walk(nodes, parent: [], depth: 0, folded: folded, into: &rows) @@ -776,27 +773,14 @@ extension OutlineEditorView { } case let .hop(direction): // ↑/↓ hop VISIBLE blocks — folded subtrees are skipped. - let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last) - if let current = rows.firstIndex(where: { $0.id == focusedID }), - rows.indices.contains(current + direction) - { - focusedID = rows[current + direction].id - selectionAnchor = nil - pendingCaret = nil // caret at end of the target row - } + hopFocus(direction, clearsAnchor: true) case let .extend(direction): // ⇧↑/⇧↓: extend the block selection one visible row. First // press anchors at the focused row; a bare ↑/↓ or click clears. if let focusedID { extendSelection(to: focusedID) // arm the anchor at the current focus } - let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last) - if let current = rows.firstIndex(where: { $0.id == focusedID }), - rows.indices.contains(current + direction) - { - focusedID = rows[current + direction].id - pendingCaret = nil - } + hopFocus(direction, clearsAnchor: false) case .deselect: _ = handleEscape() // selection first, then zoom — same order as the monitor case .indent, .outdent, .moveUp, .moveDown, .enter: @@ -804,20 +788,27 @@ extension OutlineEditorView { } } + /// Move focus `direction` visible rows from its current position (nil at + /// the list edges — folded subtrees are skipped). `clearsAnchor` + /// distinguishes hop (clears the block-selection anchor) from extend. + private func hopFocus(_ direction: Int, clearsAnchor: Bool) { + let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last) + guard let current = rows.firstIndex(where: { $0.id == focusedID }), + rows.indices.contains(current + direction) + else { return } + focusedID = rows[current + direction].id + if clearsAnchor { + selectionAnchor = nil + } + pendingCaret = nil // caret at end of the target row + } + /// Tree-mutating ops (indent/outdent/move/enter). Serialize + route /// focus only when something actually changed (boundary no-ops are /// nil and leave the document alone). private func applyTree(_ op: OutlineRowTextView.StructureOp) { guard let focusedID else { return } - // Block selection + batchable op → run-wide apply. Moves treat - // the run as a unit (boundary leader no-ops the whole batch). - if let anchor = selectionAnchor, - let range = selectedRangeIDs(anchor: anchor, focus: focusedID), range.count > 1, - let batchOp = map(op) - { - if OutlinePresenter.applyBatch(batchOp, ids: range, to: &nodes) { - pushToDocument() - } + if applyBatchIfPossible(op, focus: focusedID) { return } guard let path = OutlinePresenter.path(of: focusedID, in: nodes) else { return } @@ -833,27 +824,52 @@ extension OutlineEditorView { case .moveDown: didChange = OutlineTree.move(&nodes, path: path, up: false) != nil case let .enter(caretGraphemes): - switch OutlineTree.enter(&nodes, path: path, caretOffset: caretGraphemes) { - case .noOp: - break - case let .outdented(newPath): - didChange = newPath != nil // nil = boundary no-op - case let .newNode(newPath, caret): - didChange = true - if let id = OutlinePresenter.node(at: newPath, in: nodes)?.id { - newFocus = (id, caret) - } - } + let enter = applyEnter(caretGraphemes: caretGraphemes, path: path) + didChange = enter.didChange + newFocus = enter.focus case .fold, .unfold, .hop, .extend, .deselect: return // unreachable — apply(_:) routes those to view state } - if didChange { - if let newFocus { - self.focusedID = newFocus.id - pendingCaret = newFocus.caret - } + commitIfChanged(didChange, newFocus) + } + + /// Serialize + route focus only when something actually changed. + private func commitIfChanged(_ didChange: Bool, _ newFocus: (id: UUID, caret: Int)?) { + guard didChange else { return } + if let newFocus { + focusedID = newFocus.id + pendingCaret = newFocus.caret + } + pushToDocument() + } + + /// Block-selection fast path: a batchable op over a multi-row run + /// (moves treat the run as a unit — a boundary leader no-ops the whole + /// batch). Returns true when the batch ran (caller stops here). + private func applyBatchIfPossible(_ op: OutlineRowTextView.StructureOp, focus: UUID) -> Bool { + guard let anchor = selectionAnchor, + let range = selectedRangeIDs(anchor: anchor, focus: focus), range.count > 1, + let batchOp = map(op) + else { return false } + if OutlinePresenter.applyBatch(batchOp, ids: range, to: &nodes) { pushToDocument() } + return true + } + + /// Split (⏎) at `path`: serialize through OutlineTree.enter; focus + /// follows the NEW node when one was created (nil path = boundary + /// no-op). + private func applyEnter(caretGraphemes: Int, path: [Int]) -> (didChange: Bool, focus: (id: UUID, caret: Int)?) { + switch OutlineTree.enter(&nodes, path: path, caretOffset: caretGraphemes) { + case .noOp: + return (false, nil) + case let .outdented(newPath): + return (newPath != nil, nil) // nil = boundary no-op + case let .newNode(newPath, caret): + let id = OutlinePresenter.node(at: newPath, in: nodes)?.id + return (true, id.map { ($0, caret) }) + } } /// The selected row ids in visible order (anchor↔focus, inclusive). diff --git a/Museion/ProfileBackup.swift b/Museion/ProfileBackup.swift index acea7ed..f32d878 100644 --- a/Museion/ProfileBackup.swift +++ b/Museion/ProfileBackup.swift @@ -84,9 +84,7 @@ nonisolated enum ProfileBackup { // Age check against the newest existing snapshot (#15: skips record no // state; the normal age check governs retry). - if let newest = sortedSnapshots(in: backupsRoot).first, - now.timeIntervalSince(newest.timestamp) < snapshotInterval - { + if let newest = sortedSnapshots(in: backupsRoot).first, now.timeIntervalSince(newest.timestamp) < snapshotInterval { return .skippedFresh } diff --git a/Museion/ProfileProvisioner.swift b/Museion/ProfileProvisioner.swift index 3bd2dbf..e8213ea 100644 --- a/Museion/ProfileProvisioner.swift +++ b/Museion/ProfileProvisioner.swift @@ -139,16 +139,16 @@ nonisolated enum ProfileProvisioner { return logFailure(.failed(profile: profile, phase: phase, excerpt: excerpt)) } + let env = SurfaceEnv( + hermesBinary: hermesBinary, + profileRoot: profileRoot, + masterRoot: masterRoot, + manifest: manifest, + serverBinaryPath: serverBinaryPath, + timeout: timeout, + ) for surface in ProfileSurface.allCases { - switch provisionSurface( - surface, - hermesBinary: hermesBinary, - profileRoot: profileRoot, - masterRoot: masterRoot, - manifest: manifest, - serverBinaryPath: serverBinaryPath, - timeout: timeout, - ) { + switch provisionSurface(surface, env: env) { case let .seeded(deltaCopied, deltaPresent): copied += deltaCopied present += deltaPresent @@ -165,20 +165,27 @@ nonisolated enum ProfileProvisioner { return .seeded(copied: copied, present: present) } + /// Per-`perform` context threaded into every surface pass — everything + /// except the surface itself (the loop variable), so the per-surface + /// seam stays under the parameter-count ceiling. + private struct SurfaceEnv { + let hermesBinary: String? + let profileRoot: String + let masterRoot: String + let manifest: [String] + let serverBinaryPath: String? + let timeout: TimeInterval + } + /// Phases 1–4 for ONE surface profile (#134): create (or adopt), write /// defaults on fresh profiles via the CLI rail, link skills per /// allocation, register museion-tools (#23). private static func provisionSurface( _ surface: ProfileSurface, - hermesBinary: String?, - profileRoot: String, - masterRoot: String, - manifest: [String], - serverBinaryPath: String?, - timeout: TimeInterval, + env: SurfaceEnv, ) -> Outcome { let fileManager = FileManager.default - let profileDir = ProfileLayout.profileDir(surface.profileName, root: profileRoot) + let profileDir = ProfileLayout.profileDir(surface.profileName, root: env.profileRoot) // Phase 1 — profile create. Dir-check first; spawn only when // missing (#45). `museion` is adopted, never re-created (ADR-0014). @@ -186,12 +193,12 @@ nonisolated enum ProfileProvisioner { // carry only Museion's curated set — coding and writing never mix, G3). var createdFresh = false if !fileManager.fileExists(atPath: profileDir) { - guard let binary = hermesBinary else { + guard let binary = env.hermesBinary else { return .failed(profile: surface.profileName, phase: .create, excerpt: "hermes binary not found") } let run = EngineProbe.execute( [binary, "profile", "create", surface.profileName, "--no-alias", "--no-skills"], - timeout: timeout, + timeout: env.timeout, ) // #43: exit 1 + "already exists" on stdout = success (a // concurrent create — not ours, so not fresh); all errors print on stdout. @@ -208,10 +215,10 @@ nonisolated enum ProfileProvisioner { // profile (interrupted before its marker landed) is healed, and // the adopted museion is never touched — its model is the user's. if createdFresh || (surface != .chat && !markerExists(at: profileDir)) { - guard let binary = hermesBinary else { + guard let binary = env.hermesBinary else { return .failed(profile: surface.profileName, phase: .configure, excerpt: "hermes binary not found") } - if let failure = configureDefaults(profile: surface.profileName, hermesBinary: binary, timeout: timeout) { + if let failure = configureDefaults(profile: surface.profileName, hermesBinary: binary, timeout: env.timeout) { return failure } // A marker we couldn't record = configure incomplete — surface it @@ -224,7 +231,7 @@ nonisolated enum ProfileProvisioner { // Phase 3 — per-profile skills: symlinks per allocation + the // copy-era → symlink migration (#133). - let linked = linkSkills(surface: surface, profileDir: profileDir, masterRoot: masterRoot, manifest: manifest) + let linked = linkSkills(surface: surface, profileDir: profileDir, masterRoot: env.masterRoot, manifest: env.manifest) if case .failed = linked { return linked } @@ -232,7 +239,7 @@ nonisolated enum ProfileProvisioner { // Phase 4 — museion-tools registration per profile (ADR-0008 // amendment). nil on either binary is the test-injection seam; // production always has both after a gate pass. - guard let hermesBinary, let serverBinaryPath else { + guard let hermesBinary = env.hermesBinary, let serverBinaryPath = env.serverBinaryPath else { Logger(subsystem: subsystem, category: "provisioning") .info("museion-tools registration skipped: engine or server binary missing") return linked @@ -241,7 +248,7 @@ nonisolated enum ProfileProvisioner { profile: surface.profileName, hermesBinary: hermesBinary, serverBinaryPath: serverBinaryPath, - timeout: timeout, + timeout: env.timeout, ) { return failure } @@ -511,6 +518,12 @@ nonisolated extension ProfileProvisioner { !name.isEmpty && name.allSatisfy { ($0.isLowercase && $0.isLetter) || $0.isNumber || $0 == "-" } } + /// True when `path` is a symlink (lstat-true, before any open) — the + /// payload never ships one, so a linked entry refuses the tree match. + private static func isSymlinked(_ path: String) -> Bool { + (try? FileManager.default.destinationOfSymbolicLink(atPath: path)) != nil + } + /// Recursive byte-comparison of two dir trees — same entry names, every /// file byte-identical. `.DS_Store` is filtered from BOTH listings before /// the name-equality check (Finder noise, not a user edit — a @@ -532,9 +545,7 @@ nonisolated extension ProfileProvisioner { let rhsPath = (rhs as NSString).appendingPathComponent(name) // Neither side may carry a symlink at this entry (lstat-true, // before any open) — the payload never ships one. - if (try? fileManager.destinationOfSymbolicLink(atPath: lhsPath)) != nil - || (try? fileManager.destinationOfSymbolicLink(atPath: rhsPath)) != nil - { + if isSymlinked(lhsPath) || isSymlinked(rhsPath) { return false } var lhsIsDirectory: ObjCBool = false, rhsIsDirectory: ObjCBool = false diff --git a/Museion/ProseListTextView.swift b/Museion/ProseListTextView.swift index 26dd482..2eddd10 100644 --- a/Museion/ProseListTextView.swift +++ b/Museion/ProseListTextView.swift @@ -377,10 +377,7 @@ final class ProseListTextView: NSTextView { guard let scalar = Unicode.Scalar(Int(char)) else { return false } return CharacterSet.whitespacesAndNewlines.contains(scalar) } - if index > 0, index < length, - !isGap(buffer.character(at: index - 1)), - !isGap(buffer.character(at: index)) - { + if index > 0, index < length, !isGap(buffer.character(at: index - 1)), !isGap(buffer.character(at: index)) { while index < length, !isGap(buffer.character(at: index)) { index += 1 } diff --git a/Museion/ProsePresenter.swift b/Museion/ProsePresenter.swift index be824ff..586a46d 100644 --- a/Museion/ProsePresenter.swift +++ b/Museion/ProsePresenter.swift @@ -38,6 +38,39 @@ nonisolated enum ProsePresenter { classify(line, inFence: false) } + /// A fence delimiter line (``` or ~~~ prefix) — delimiter lines are + /// fences even inside a fence (they close it). + static func isFenceDelimiter(_ trimmed: Substring) -> Bool { + trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") + } + + /// Pure rule/mark syntax (horizontal rules, dinkus) — no content. + static func isRuleSyntax(_ trimmed: Substring) -> Bool { + trimmed.allSatisfy { $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" } + } + + /// CommonMark ATX heading level (1–6) of a trimmed line — a heading + /// needs 1–6 hashes followed by a space or end-of-line; 7+ hashes or a + /// glued-on word is body text. + static func headingLevel(of trimmed: Substring) -> Int? { + let hashes = trimmed.prefix(while: { $0 == "#" }).count + guard hashes > 0, hashes <= 6 else { return nil } // CommonMark caps at 6; 7+ is body + let after = trimmed.dropFirst(hashes) + guard after.hasPrefix(" ") || after.isEmpty else { return nil } + return hashes + } + + /// Heading ladder for a valid ATX level — 1–3 are named steps, 4–6 + /// share the h4+ rung (CommonMark). + private static func headingKind(_ hashes: Int) -> LineKind { + switch hashes { + case 1: .heading1 + case 2: .heading2 + case 3: .heading3 + default: .heading4Plus + } + } + /// Delimiter lines are fences even inside a fence (they close it) — so the /// delim test runs before the inFence shortcut and `applyStyles` toggles /// on `kind == .fence` instead of re-deriving the prefix. @@ -46,28 +79,19 @@ nonisolated enum ProsePresenter { if trimmed.isEmpty { return .blank } - if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") { + if isFenceDelimiter(trimmed) { return .fence } if inFence { return .fenceInterior } - let hashes = trimmed.prefix(while: { $0 == "#" }).count - if hashes > 0, hashes <= 6 { // CommonMark caps at 6; 7+ is body - let after = trimmed.dropFirst(hashes) - if after.hasPrefix(" ") || after.isEmpty { - switch hashes { - case 1: return .heading1 - case 2: return .heading2 - case 3: return .heading3 - default: return .heading4Plus - } - } + if let hashes = headingLevel(of: trimmed) { + return headingKind(hashes) } if trimmed.hasPrefix(">") { return .quote } - if trimmed.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) { + if isRuleSyntax(trimmed) { return .syntaxOnly } if line.firstMatch(of: listMarkerPattern) != nil { @@ -102,7 +126,7 @@ nonisolated enum ProsePresenter { var count = 0 for line in text.split(separator: "\n", omittingEmptySubsequences: false) { let trimmed = line.drop(while: { $0 == " " || $0 == "\t" }) - if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") { + if isFenceDelimiter(trimmed) { count += 1 } } @@ -171,58 +195,76 @@ nonisolated enum ProsePresenter { /// Count unclosed fences before `end` (``` or ~~~ delim lines toggle). private static func fenceState(_ nsText: NSString, upTo end: Int) -> Bool { var inFence = false - for line in contentLines(nsText, in: NSRange(location: 0, length: min(end, nsText.length))) { - if classify(line.text, inFence: inFence) == .fence { - inFence.toggle() - } + let prefix = NSRange(location: 0, length: min(end, nsText.length)) + for line in contentLines(nsText, in: prefix) where classify(line.text, inFence: inFence) == .fence { + inFence.toggle() } return inFence } + /// The #…​ ATX marker of a heading line, dimmed to the code face. + private static func dimHeadingMarker(_ out: NSMutableAttributedString, line: Line) { + let lead = line.text.prefix(while: { $0 == " " || $0 == "\t" }).utf16.count + let hashes = line.text.dropFirst(lead).prefix(while: { $0 == "#" }).utf16.count + let marker = NSRange(location: line.content.location + lead, length: min(hashes + 1, line.content.length - lead)) + if marker.length > 0 { + out.addAttributes(ProseTypography.codeAttributes, range: marker) + } + } + + /// Kinds whose text content carries inline trait styling (bold/italic/ + /// code/link spans). + static func carriesInlineTraits(_ kind: LineKind) -> Bool { + kind == .body || kind == .quote || kind == .listMarker + } + + /// Non-empty UTF-16 marker range of `pattern` at the line start, or nil. + private static func markerRange(_ pattern: Regex, in line: Line) -> NSRange? { + guard let marker = markerRangeUTF16(pattern, in: line.text), marker.length > 0 else { return nil } + return marker + } + + /// List marker dim + hanging indent: wrapped list lines align with the + /// item's text, not the paragraph margin — the marker prefix (leading + /// whitespace + "- "/"1. ") sets headIndent, mirroring reading.css's + /// hanging lists (padding-left + outside markers; #ui-r1, sol#13; #ui-r2 + /// argon#53 flush fix). Nested items hang at their own prefix width. + /// The prefix is measured in the EXACT attributes it renders in + /// (listMarkerAttributes — the line's face and size), so the + /// continuation lands flush; a different measuring face drifts + /// per-glyph (~4pt left in r1). ponytail: a tab in the prefix measures + /// at the default tab stop; the corpus uses spaces — widen if tabbed + /// lists drift. + private static func applyListMarker(_ out: NSMutableAttributedString, line: Line) { + guard let marker = markerRange(listMarkerPattern, in: line) else { return } + out.addAttributes(ProseTypography.listMarkerAttributes, range: shifted(marker, into: line.content)) + let prefix = String(line.text.prefix(NSMaxRange(marker))) + let indent = NSAttributedString( + string: prefix, + attributes: ProseTypography.listMarkerAttributes, + ).size().width + let hanging = NSMutableParagraphStyle() + hanging.setParagraphStyle(paragraph(.body)) + hanging.headIndent = indent + // #ui-r7 sol#29: inter-item rhythm (reading.css list margins) + // — before-space only, the CSS block has no bottom margin. + hanging.paragraphSpacingBefore = ProseTypography.listSpacingBefore + out.addAttribute(.paragraphStyle, value: hanging, range: line.full) + } + private static func styleLine(_ out: NSMutableAttributedString, line: Line, kind: LineKind, isTitle: Bool = false) { guard line.full.length > 0 else { return } out.setAttributes(isTitle ? ProseTypography.titleAttributes : attributes(for: kind), range: line.full) let dim = ProseTypography.codeAttributes // codeFont + syntaxColor switch kind { case .heading1, .heading2, .heading3, .heading4Plus: - let lead = line.text.prefix(while: { $0 == " " || $0 == "\t" }).utf16.count - let hashes = line.text.dropFirst(lead).prefix(while: { $0 == "#" }).utf16.count - let marker = NSRange(location: line.content.location + lead, length: min(hashes + 1, line.content.length - lead)) - if marker.length > 0 { - out.addAttributes(dim, range: marker) - } + dimHeadingMarker(out, line: line) case .quote: - if let marker = markerRangeUTF16(quoteMarkerPattern, in: line.text), marker.length > 0 { + if let marker = markerRange(quoteMarkerPattern, in: line) { out.addAttributes(dim, range: shifted(marker, into: line.content)) } case .listMarker: - if let marker = markerRangeUTF16(listMarkerPattern, in: line.text), marker.length > 0 { - out.addAttributes(ProseTypography.listMarkerAttributes, range: shifted(marker, into: line.content)) - // Hanging indent (#ui-r1, sol#13; #ui-r2 argon#53 flush - // fix): wrapped list lines align with the item's text, not - // the paragraph margin — the marker prefix (leading - // whitespace + "- "/"1. ") sets headIndent, mirroring - // reading.css's hanging lists (padding-left + outside - // markers). Nested items hang at their own prefix width. - // The prefix is measured in the EXACT attributes it - // renders in (listMarkerAttributes — the line's face and - // size), so the continuation lands flush; a different - // measuring face drifts per-glyph (~4pt left in r1). - // ponytail: a tab in the prefix measures at the default tab - // stop; the corpus uses spaces — widen if tabbed lists drift. - let prefix = String(line.text.prefix(NSMaxRange(marker))) - let indent = NSAttributedString( - string: prefix, - attributes: ProseTypography.listMarkerAttributes, - ).size().width - let hanging = NSMutableParagraphStyle() - hanging.setParagraphStyle(paragraph(.body)) - hanging.headIndent = indent - // #ui-r7 sol#29: inter-item rhythm (reading.css list margins) - // — before-space only, the CSS block has no bottom margin. - hanging.paragraphSpacingBefore = ProseTypography.listSpacingBefore - out.addAttribute(.paragraphStyle, value: hanging, range: line.full) - } + applyListMarker(out, line: line) case .syntaxOnly: if line.content.length > 0 { out.addAttributes(dim, range: line.content) @@ -232,7 +274,7 @@ nonisolated enum ProsePresenter { case .fenceInterior, .blank, .body: break } - if kind == .body || kind == .quote || kind == .listMarker { + if carriesInlineTraits(kind) { styleInline(out, content: line.content, text: line.text) } } @@ -256,98 +298,119 @@ nonisolated enum ProsePresenter { private nonisolated(unsafe) static let linkPattern = /\[[^\]\n]*\]\([^)\n]*\)/ /// Trait-style inline constructs. Marks dim; content gets real traits. - /// Priority: code > link > bold > italic; later matches skip claimed spans. + /// Priority: code > link > bold > italic; later matches skip claimed + /// spans (`claim` is the shared overlap gate, so each family's loop + /// stays honest about the ones before it). private static func styleInline(_ out: NSMutableAttributedString, content: NSRange, text: String) { guard content.length > 0 else { return } var claimed: [Range] = [] + styleCodeAndLinks(out, content: content, text: text, claimed: &claimed) + styleEmphasis(out, content: content, text: text, claimed: &claimed) + dimStraySyntax(out, content: content, text: text, claimed: &claimed) + } - func claim(_ span: Range) -> Bool { - guard !claimed.contains(where: { $0.overlaps(span) }) else { return false } - claimed.append(span) - return true - } + /// Claim `span` unless an earlier (higher-priority) match overlaps it. + private static func claim(_ claimed: inout [Range], _ span: Range) -> Bool { + guard !claimed.contains(where: { $0.overlaps(span) }) else { return false } + claimed.append(span) + return true + } - func dim(_ utf16: Range) { - let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count) - out.addAttributes(ProseTypography.codeAttributes, range: range) - } + /// Dim a utf16 span in the code face (marks, brackets, stray syntax). + private static func dim(_ out: NSMutableAttributedString, content: NSRange, _ utf16: Range) { + let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count) + out.addAttributes(ProseTypography.codeAttributes, range: range) + } - func attr(_ utf16: Range, _ attrs: [NSAttributedString.Key: Any]) { - let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count) - out.addAttributes(attrs, range: range) - } + /// Apply `attrs` to a utf16 span. + private static func attr(_ out: NSMutableAttributedString, content: NSRange, _ utf16: Range, _ attrs: [NSAttributedString.Key: Any]) { + let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count) + out.addAttributes(attrs, range: range) + } - let boldFont = ProseTypography.boldBodyFont - let italicFont = ProseTypography.italicBodyFont + /// Inline code + links (priority 1–2). Code: marks + content in the code + /// face, content at ink. Links: label ink + underline (CSS: ink text, + /// muted rule); the brackets, ]( and the URL dim (reading hides them; + /// dim is the editor's closest parity move). + private static func styleCodeAndLinks( + _ out: NSMutableAttributedString, content: NSRange, text: String, claimed: inout [Range], + ) { let codeFont = ProseTypography.codeFont let ink: [NSAttributedString.Key: Any] = [.foregroundColor: ProseTypography.foregroundColor] let linkAttrs: [NSAttributedString.Key: Any] = [ .underlineStyle: NSUnderlineStyle.single.rawValue, .underlineColor: ProseTypography.mutedColor, ] - // inline code — marks + content in the code face, content at ink for match in text.matches(of: codePattern) { let span = match.range.utf16Range(in: text) - guard claim(span) else { continue } - dim(span.lowerBound ..< span.lowerBound + 1) - dim(span.upperBound - 1 ..< span.upperBound) - attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: codeFont].merging(ink) { _, new in new }) + guard claim(&claimed, span) else { continue } + dim(out, content: content, span.lowerBound ..< span.lowerBound + 1) + dim(out, content: content, span.upperBound - 1 ..< span.upperBound) + attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: codeFont].merging(ink) { _, new in new }) } - // links — label ink + underline (CSS: ink text, muted rule); the - // brackets, ]( and the URL dim (reading hides them; dim is the - // editor's closest parity move). for match in text.matches(of: linkPattern) { let span = match.range.utf16Range(in: text) - guard claim(span) else { continue } + guard claim(&claimed, span) else { continue } let whole = match.output // whole match (no capture groups) guard let sep = whole.firstRange(of: "](") else { continue } // sep indices are valid in text (Substring shares indices) let sepOffset = text.utf16.distance(from: text.utf16.startIndex, to: sep.lowerBound.samePosition(in: text.utf16)!) let label = span.lowerBound + 1 ..< sepOffset - dim(span.lowerBound ..< span.lowerBound + 1) // [ - attr(label, linkAttrs) - dim(sepOffset ..< span.upperBound) // ](url) + dim(out, content: content, span.lowerBound ..< span.lowerBound + 1) // [ + attr(out, content: content, label, linkAttrs) + dim(out, content: content, sepOffset ..< span.upperBound) // ](url) } - // bold + } + + /// Bold + italic (priority 3–4). CommonMark: intraword `_` never + /// emphasizes (file_name_here); intraword `*` does. No lookbehind in + /// swift-regex, so boundary chars are checked by hand. + private static func styleEmphasis( + _ out: NSMutableAttributedString, content: NSRange, text: String, claimed: inout [Range], + ) { + let boldFont = ProseTypography.boldBodyFont + let italicFont = ProseTypography.italicBodyFont for match in text.matches(of: boldPattern) { let span = match.range.utf16Range(in: text) - guard claim(span) else { continue } - dim(span.lowerBound ..< span.lowerBound + 2) - dim(span.upperBound - 2 ..< span.upperBound) - attr(span.lowerBound + 2 ..< span.upperBound - 2, [.font: boldFont]) + guard claim(&claimed, span) else { continue } + dim(out, content: content, span.lowerBound ..< span.lowerBound + 2) + dim(out, content: content, span.upperBound - 2 ..< span.upperBound) + attr(out, content: content, span.lowerBound + 2 ..< span.upperBound - 2, [.font: boldFont]) } - // italic — two forms. CommonMark: intraword `_` never emphasizes - // (file_name_here); intraword `*` does. No lookbehind in swift-regex, - // so boundary chars are checked by hand. for match in text.matches(of: emStarPattern) { let span = match.range.utf16Range(in: text) - guard claim(span) else { continue } + guard claim(&claimed, span) else { continue } let lo = charBefore(text, span.lowerBound) let hi = charAfter(text, span.upperBound) - if lo == "*" || hi == "*" || lo == "_" || hi == "_" { + if isMarkAdjacent(lo, hi) { continue } - dim(span.lowerBound ..< span.lowerBound + 1) - dim(span.upperBound - 1 ..< span.upperBound) - attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont]) + dim(out, content: content, span.lowerBound ..< span.lowerBound + 1) + dim(out, content: content, span.upperBound - 1 ..< span.upperBound) + attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont]) } for match in text.matches(of: emUnderPattern) { let span = match.range.utf16Range(in: text) - guard claim(span) else { continue } + guard claim(&claimed, span) else { continue } let lo = charBefore(text, span.lowerBound) let hi = charAfter(text, span.upperBound) - if lo == "*" || hi == "*" || lo == "_" || hi == "_" { + if isMarkAdjacent(lo, hi) { continue } - if lo?.isLetter == true || lo?.isNumber == true || hi?.isLetter == true || hi?.isNumber == true { + if isIntraword(lo, hi) { continue } - dim(span.lowerBound ..< span.lowerBound + 1) - dim(span.upperBound - 1 ..< span.upperBound) - attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont]) + dim(out, content: content, span.lowerBound ..< span.lowerBound + 1) + dim(out, content: content, span.upperBound - 1 ..< span.upperBound) + attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont]) } - // fallback: dim stray syntax chars outside claimed spans + } + + /// Fallback: dim stray syntax chars outside claimed spans. + private static func dimStraySyntax( + _ out: NSMutableAttributedString, content: NSRange, text: String, claimed: inout [Range], + ) { let syntax = inlineSyntax for (offset, codeUnit) in text.utf16.enumerated() { guard let scalar = Unicode.Scalar(codeUnit).map({ Character($0) }), syntax.contains(scalar) else { continue } @@ -355,10 +418,22 @@ nonisolated enum ProsePresenter { if claimed.contains(where: { $0.overlaps(unit) }) { continue } - dim(unit) + dim(out, content: content, unit) } } + /// True when the char at either boundary of an emphasis span is itself + /// a mark (`**foo**`'s inner `*` is bold, not emphasis). + private static func isMarkAdjacent(_ lo: Character?, _ hi: Character?) -> Bool { + lo == "*" || hi == "*" || lo == "_" || hi == "_" + } + + /// True when an `_…_` span sits inside a word (file_name_here never + /// emphasizes). + private static func isIntraword(_ lo: Character?, _ hi: Character?) -> Bool { + lo?.isLetter == true || lo?.isNumber == true || hi?.isLetter == true || hi?.isNumber == true + } + // MARK: Base attributes static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] { diff --git a/Museion/ProseTypography.swift b/Museion/ProseTypography.swift index 0267a33..0d7e9d2 100644 --- a/Museion/ProseTypography.swift +++ b/Museion/ProseTypography.swift @@ -31,10 +31,12 @@ nonisolated enum ProseTypography { /// Headings = Concourse OT (the designer's own pairing with Valkyrie); /// Semibold carries heading weight better than Book on screen. - nonisolated(unsafe) static let headingFont: NSFont = .init(name: "ConcourseOT6Semibold", size: heading1Size) ?? NSFont.systemFont(ofSize: heading1Size, weight: .semibold) + nonisolated(unsafe) static let headingFont: NSFont = .init(name: "ConcourseOT6Semibold", size: heading1Size) + ?? NSFont.systemFont(ofSize: heading1Size, weight: .semibold) /// h2 = the headings face at CSS's 0.85× ladder step (#77). - nonisolated(unsafe) static let heading2Font: NSFont = .init(name: "ConcourseOT6Semibold", size: heading2Size) ?? NSFont.systemFont(ofSize: heading2Size, weight: .semibold) + nonisolated(unsafe) static let heading2Font: NSFont = .init(name: "ConcourseOT6Semibold", size: heading2Size) + ?? NSFont.systemFont(ofSize: heading2Size, weight: .semibold) /// h3 = body face, sized up, weight 600 (CSS h3: body-face w600). The B /// cut has no 600 member — the bold trait (700, real or synthesized) is diff --git a/Museion/ReadingPresenter.swift b/Museion/ReadingPresenter.swift index d202cc8..8ea6c20 100644 --- a/Museion/ReadingPresenter.swift +++ b/Museion/ReadingPresenter.swift @@ -104,7 +104,7 @@ nonisolated enum ReadingPresenter { // swiftlint:disable:next force_try let regex = try! NSRegularExpression(pattern: #"\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#) let mutable = NSMutableString(string: html) - regex.replaceMatches(in: mutable, range: NSMakeRange(0, mutable.length), withTemplate: "<$2 data-source-line=\"$1\"") + regex.replaceMatches(in: mutable, range: NSRange(location: 0, length: mutable.length), withTemplate: "<$2 data-source-line=\"$1\"") return mutable as String } @@ -207,7 +207,8 @@ nonisolated enum ReadingPresenter { /// apex failure / missing binary → editing-treated source text (#69's /// fallback rule: fallback = the source, not a second renderer). static func fallbackPage(_ text: String) -> String { - "
\(escapeHTML(text))
" + "" + + "
\(escapeHTML(text))
" } static func escapeHTML(_ text: String) -> String { diff --git a/Museion/ReadingSurface.swift b/Museion/ReadingSurface.swift index 4c00754..bf5840c 100644 --- a/Museion/ReadingSurface.swift +++ b/Museion/ReadingSurface.swift @@ -172,6 +172,13 @@ struct ReadingSurface: NSViewRepresentable { wv.evaluateJavaScript(ReadingSurface.entryScrollJS(line)) } + /// True for our own loadHTMLString main-frame load (file URL or + /// about:blank) — the only navigation reading allows in-app. + private func isOwnMainFrameLoad(_ nav: WKNavigationAction) -> Bool { + guard nav.targetFrame?.isMainFrame == true, let url = nav.request.url else { return false } + return url.scheme == "file" || url.absoluteString == "about:blank" + } + /// Allow our own loadHTMLString main-frame load (about:blank); a /// blanket .cancel would kill the page before it paints. Everything /// else is cancelled — reading never navigates in-app (#74 lesson). @@ -180,9 +187,7 @@ struct ReadingSurface: NSViewRepresentable { decidePolicyFor nav: WKNavigationAction, decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void, ) { - if nav.targetFrame?.isMainFrame == true, - let url = nav.request.url, url.scheme == "file" || url.absoluteString == "about:blank" - { + if isOwnMainFrameLoad(nav) { decisionHandler(.allow) return } diff --git a/Museion/WorkspaceView.swift b/Museion/WorkspaceView.swift index bb02166..b8008ca 100644 --- a/Museion/WorkspaceView.swift +++ b/Museion/WorkspaceView.swift @@ -574,9 +574,12 @@ private struct OutlineGuardSheet: View { VStack(alignment: .leading, spacing: 12) { Text("Open as outline or prose?") .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) - Text("This outline has paragraph lines between its bullets. The outliner can't show them — opening as an outline drops them on the next save. Prose mode shows everything.") - .font(.callout) - .foregroundStyle(DesignTokens.muted) + Text( + "This outline has paragraph lines between its bullets. The outliner can't show them — opening as an outline " + + "drops them on the next save. Prose mode shows everything.", + ) + .font(.callout) + .foregroundStyle(DesignTokens.muted) Text("Outline mode keeps its bullets, indentation, and folding. You can convert or clean up later.") .font(.callout) .foregroundStyle(DesignTokens.muted) diff --git a/Museion/WritingLockState.swift b/Museion/WritingLockState.swift index 9291cf3..1ea4d60 100644 --- a/Museion/WritingLockState.swift +++ b/Museion/WritingLockState.swift @@ -299,12 +299,19 @@ enum WritingLockKiosk { return false } + private static func shouldRefuse(_ event: NSEvent) -> Bool { + WritingLockState.active?.isLocked == true + && refusesKey( + keyCode: event.keyCode, + characters: event.charactersIgnoringModifiers, + modifiers: event.modifierFlags, + ) + } + private static func installRefusalMonitor() { guard refusalMonitor == nil else { return } refusalMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in - if WritingLockState.active?.isLocked == true, - Self.refusesKey(keyCode: event.keyCode, characters: event.charactersIgnoringModifiers, modifiers: event.modifierFlags) - { + if Self.shouldRefuse(event) { return nil // swallowed — the lock holds } return event diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index fa99109..c20eebb 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -12,6 +12,7 @@ Owned by the root AGENTS.md contract. - Uses Swift Testing (`@Test`, `#expect`) — not XCTest. - Always give `@Suite` its string argument — bare `@Suite` is stripped by this repo's swiftformat. +- `@Test` names: backticked sentence style is the convention; plain lowercase-camel identifiers are the deliberate exception where name-level `-only-testing` addressability matters (#195) — `.swiftformat` sets `--test-case-name-format preserve`, so both shapes are format-clean. - Imports `@testable import Museion`; app code is default-MainActor, so cross-actor tests need `@MainActor` or nonisolated declarations in app code. - Deployment target and versions follow the app target; leave `CURRENT_PROJECT_VERSION = 1` here. diff --git a/MuseionTests/LearningsPaneTests.swift b/MuseionTests/LearningsPaneTests.swift index 676aefe..c41f734 100644 --- a/MuseionTests/LearningsPaneTests.swift +++ b/MuseionTests/LearningsPaneTests.swift @@ -124,6 +124,25 @@ struct LearningsPaneTests { #expect(LearningsIndex.scan(home: home).isEmpty) } + /// Scenario: the skip posture Post.scan pins, on this scan — a symlinked + /// type dir must not be followed. Defended in depth: the lstat guard + /// (a symlink reports isDirectory=false) AND contentsOfDirectory's own + /// refusal of a symlinked entry — flip-verified: the pin fails only when + /// BOTH go traversal-shaped (fileExists guard + resolved-URL listing). + @Test func `a symlinked type dir never surfaces`() throws { + let home = try makeHome { home in + try writeLearning(home, "posts", "20261021-one-real-entry.md", "# real\n") + } + let learnings = home.appendingPathComponent("learnings", isDirectory: true) + try FileManager.default.createSymbolicLink( + at: learnings.appendingPathComponent("linked", isDirectory: true), + withDestinationURL: learnings.appendingPathComponent("posts", isDirectory: true), + ) + let groups = LearningsIndex.scan(home: home) + #expect(groups.map(\.type) == ["posts"]) // the link's alias never groups + #expect(groups.flatMap(\.entries).count == 1) // its view of posts never doubles + } + // MARK: Decay surface (#27, S4.2) /// Scenario: Entry carries the decay verdict — visible learnings read diff --git a/MuseionTests/LibrarySearchTests.swift b/MuseionTests/LibrarySearchTests.swift index 5130730..7e59549 100644 --- a/MuseionTests/LibrarySearchTests.swift +++ b/MuseionTests/LibrarySearchTests.swift @@ -96,7 +96,8 @@ struct LibrarySearchTests { /// while it `isFresh` for the CURRENT key. The controller pins drive /// the real rescan rail (write verbs + the rail's own rescan Task) and /// prove archive, trash, and a same-query body edit each move the -/// revision — without that signal a standing snapshot outlives the +/// revision, and an unchanged rescan over a quiesced FSEvent burst +/// keeps it — without that signal a standing snapshot outlives the /// library it searched (archived rows linger in the results; edited /// bodies never enter or leave them until the query changes). @Suite("library search snapshot invalidation") @@ -192,9 +193,22 @@ struct LibrarySearchSnapshotTests { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Settled\n", home: home) try await pollUntil { model.posts.contains { $0.id == post.id } } + // The FSEvent burst can still hold a sibling rescan that snapshotted + // its miss count BEFORE the landing scan stamped the shared + // PostScanCache — both count the same first read, each bumps the + // revision (#144's counter; an extra bump only over-invalidates a + // search snapshot). This pin is the SETTLED contract: wait out the + // burst (FSEvents latency is 0.5 s) before snapshotting. + var quiet = false + for _ in 0 ..< 20 where !quiet { + let seen = model.contentRevision + try await Task.sleep(nanoseconds: 500_000_000) + quiet = model.contentRevision == seen + } + #expect(quiet) // endless revision churn would never settle let settled = model.contentRevision - await model.rescan() // nothing changed since the last scan — all cache hits + await model.rescan() // nothing changed since the burst — all cache hits #expect(model.contentRevision == settled) } diff --git a/MuseionTests/PolishSeamTests.swift b/MuseionTests/PolishSeamTests.swift index 2a58a08..c0c65df 100644 --- a/MuseionTests/PolishSeamTests.swift +++ b/MuseionTests/PolishSeamTests.swift @@ -18,7 +18,7 @@ struct PolishSeamTests { /// whitespace-only buffer has none (nil); a buffer with no leading /// blanks returns 0. The same walker styles the title line and hops /// programmatic carets past the invisible blank fragment. - @Test func `firstContentLocation skips leading blanks`() { + @Test func firstContentLocationSkipsLeadingBlanks() { let plain = "Title\n\nbody" as NSString #expect(ProsePresenter.firstContentLocation(plain) == 0) let blankLead = "\n\n \nTitle\nbody" as NSString @@ -31,7 +31,7 @@ struct PolishSeamTests { /// The ladder keeps the full path, then each shorter variant with one /// more leading component kept whole; ≤2 components has nothing to /// elide. `elide` picks the longest candidate that fits. - @Test func `ElidedPathText candidate ladder and elision`() { + @Test func elidedPathTextCandidateLadderAndElision() { let path = "/Users/alex/Library/Mobile Documents/com~apple~CloudDocs/Museion" let ladder = ElidedPathText.candidates(path) #expect(ladder.first == path) diff --git a/MuseionTests/PostStoreTests.swift b/MuseionTests/PostStoreTests.swift index 1b0f844..11ed076 100644 --- a/MuseionTests/PostStoreTests.swift +++ b/MuseionTests/PostStoreTests.swift @@ -532,7 +532,8 @@ func readPiece(_ home: URL, root: String, project: String, _ id: String) throws withIntermediateDirectories: true, ) } - #expect(!decomposed.utf8.elementsEqual("한국".utf8)) // two byte sequences, one name — Swift ==/Set already fold; the explicit key pins the contract + // two byte sequences, one name — Swift ==/Set already fold; the explicit key pins the contract + #expect(!decomposed.utf8.elementsEqual("한국".utf8)) #expect(PostStore.availableSlug(for: "한국", home: home) == "한국-2") } diff --git a/MuseionTests/ProfileProvisionerFailureTests.swift b/MuseionTests/ProfileProvisionerFailureTests.swift index ba4afd0..eef50ab 100644 --- a/MuseionTests/ProfileProvisionerFailureTests.swift +++ b/MuseionTests/ProfileProvisionerFailureTests.swift @@ -44,14 +44,17 @@ struct ProfileProvisionerFailureTests { func configUntouched() -> Bool { (try? String(contentsOfFile: configPath, encoding: .utf8)) == config } + // Shared per-phase runner: same binary/root/payload master, the + // server seam varying per phase (default = perform's own default). + func pass(_ payload: String, server: String? = Bundle.main.executableURL?.path) -> ProfileProvisioner.Outcome { + ProfileProvisioner.perform( + hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload, + masterRoot: master, serverBinaryPath: server, + ) + } // Failed pass: registration never reached, config untouched. - let failed = ProfileProvisioner.perform( - hermesBinary: binary, - profileRoot: profileRoot, - payloadRoot: badPayload, - masterRoot: master, - ) + let failed = pass(badPayload) guard case .failed = failed else { Issue.record("expected copy failure, got \(failed)") return @@ -61,13 +64,7 @@ struct ProfileProvisionerFailureTests { // Skipped pass: nil serverBinaryPath is the test seam — nothing // registers, config untouched. (The failed pass already seeded the // shared master — 2 present there, only the 6 profile links copy.) - let skipped = ProfileProvisioner.perform( - hermesBinary: binary, - profileRoot: profileRoot, - payloadRoot: goodPayload, - masterRoot: master, - serverBinaryPath: nil, - ) + let skipped = pass(goodPayload, server: nil) #expect(skipped == .seeded(copied: 6, present: 2)) #expect(configUntouched()) for profile in ["museion", "museion-pass1", "museion-pass2"] { @@ -77,13 +74,7 @@ struct ProfileProvisionerFailureTests { // Registering pass: the CLI rail ran (markers + invocations per // profile) and still not one byte of config.yaml is written by the // provisioner — the entry lands through the CLI, or not at all. - let registered = ProfileProvisioner.perform( - hermesBinary: binary, - profileRoot: profileRoot, - payloadRoot: goodPayload, - masterRoot: master, - serverBinaryPath: "/fake/Museion.app/Contents/MacOS/Museion", - ) + let registered = pass(goodPayload, server: "/fake/Museion.app/Contents/MacOS/Museion") #expect(registered == .seeded(copied: 0, present: 8)) #expect(configUntouched()) #expect(FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-registered-museion"))) diff --git a/MuseionTests/ProfileProvisionerTests.swift b/MuseionTests/ProfileProvisionerTests.swift index 69c50e4..05445c7 100644 --- a/MuseionTests/ProfileProvisionerTests.swift +++ b/MuseionTests/ProfileProvisionerTests.swift @@ -44,8 +44,8 @@ struct SeedSkill { /// and `config unset ` (argv log `/config-unset-`, /// store line removed, "✓ Unset …"; unset-when-absent = the not-set line, /// exit 1) — the live-probed wire shapes HermesSettingsWriter pins. -// #136: the config rail (set/get/unset over the config-store map) — its -// own literal so makeFakeHermes stays under its function-body ceiling. +/// #136: the config rail (set/get/unset over the config-store map) — its +/// own literal so makeFakeHermes stays under its function-body ceiling. private func fakeHermesConfigCLI() -> String { """ if [[ "$1" == "-p" && "$3" == "config" && "$4" == "set" ]]; then @@ -94,6 +94,67 @@ private func fakeHermesConfigCLI() -> String { """ } +/// #23: the mcp rail (list/add over marker files) — its own literal so +/// makeFakeHermes stays under its function-body ceiling (config-rail +/// precedent directly above). +private func fakeHermesMcpCLI() -> String { + """ + if [[ "$1" == "-p" && "$3" == "mcp" ]]; then + PROFILE="$2" + if [[ "$4" == "list" ]]; then + if [[ -f "${0:h}/mcp-registered-$PROFILE" ]]; then + print "museion-tools enabled" + exit 0 + fi + print "No MCP servers configured." + exit 0 + fi + if [[ "$4" == "add" ]]; then + if [[ "$5" != "museion-tools" || "$6" != "--command" || -z "$7" || "$8" != "--args" || "$9" != "--serve-mcp" ]]; then + print "Error: mcp add unexpected argv: $5 $6 $7 $8 $9" + exit 1 + fi + if [[ -f "${0:h}/mcp-add-fails" ]]; then + print "Error: mcp add exploded" + exit 1 + fi + read -r ANSWER + if [[ "$ANSWER" != "y" ]]; then + print "Cancelled." + exit 1 + fi + print -r -- "$*" > "${0:h}/mcp-add-invocation-$PROFILE" + touch "${0:h}/mcp-registered-$PROFILE" + print "Saved 'museion-tools' to ${0:h}/profiles/$PROFILE/config.yaml" + exit 0 + fi + fi + """ +} + +/// Fake `hermes`: `profile create ` behaves per `mode` (#43 semantics). +/// - ok: creates the dir, exit 0. exists: creates the dir, "already exists" on +/// stdout, exit 1 (the create race). fail: "Error: create exploded", exit 1. +/// stderr-only: error on stderr with empty stdout (#48 fallback). +/// +/// Also speaks `mcp` and `config set` behind the `-p ` global flag +/// (#23, #134): `mcp list` prints "museion-tools" iff +/// `/mcp-registered-` exists, else "No MCP servers +/// configured."; `mcp add` verifies its argv, reads ONE "y" line from stdin +/// (mismatch/EOF → "Cancelled.", exit 1 — nothing saved), records the exact +/// invocation in `/mcp-add-invocation-`, drops the +/// per-profile marker, prints "Saved 'museion-tools' to …" (verified wire +/// strings). `config set [--force]` appends the exact argv to +/// `/config-set-` and prints the verified "✓ Set …" +/// line. `/mcp-add-fails` / `config-set-fails` / `config-unset-fails` +/// force the matching failure. Every `profile create` name appends to +/// `/profile-create-log`. +/// #136: `config set` also records KEY=VALUE into +/// `/config-store-` (dedup per key), and the fake speaks +/// `config get ` (store value, or the not-set line on stderr exit 1) +/// and `config unset ` (argv log `/config-unset-`, +/// store line removed, "✓ Unset …"; unset-when-absent = the not-set line, +/// exit 1) — the live-probed wire shapes HermesSettingsWriter pins. func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> String { let path = (dir as NSString).appendingPathComponent(name) let createBlock = switch mode { @@ -128,36 +189,7 @@ func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> St print -r -- "$NAME" >> "${0:h}/profile-create-log" \(createBlock) fi - if [[ "$1" == "-p" && "$3" == "mcp" ]]; then - PROFILE="$2" - if [[ "$4" == "list" ]]; then - if [[ -f "${0:h}/mcp-registered-$PROFILE" ]]; then - print "museion-tools enabled" - exit 0 - fi - print "No MCP servers configured." - exit 0 - fi - if [[ "$4" == "add" ]]; then - if [[ "$5" != "museion-tools" || "$6" != "--command" || -z "$7" || "$8" != "--args" || "$9" != "--serve-mcp" ]]; then - print "Error: mcp add unexpected argv: $5 $6 $7 $8 $9" - exit 1 - fi - if [[ -f "${0:h}/mcp-add-fails" ]]; then - print "Error: mcp add exploded" - exit 1 - fi - read -r ANSWER - if [[ "$ANSWER" != "y" ]]; then - print "Cancelled." - exit 1 - fi - print -r -- "$*" > "${0:h}/mcp-add-invocation-$PROFILE" - touch "${0:h}/mcp-registered-$PROFILE" - print "Saved 'museion-tools' to ${0:h}/profiles/$PROFILE/config.yaml" - exit 0 - fi - fi + \(fakeHermesMcpCLI()) \(fakeHermesConfigCLI()) exit 97 """ diff --git a/MuseionTests/ProfileSurfaceTests.swift b/MuseionTests/ProfileSurfaceTests.swift index 269c28d..27efd51 100644 --- a/MuseionTests/ProfileSurfaceTests.swift +++ b/MuseionTests/ProfileSurfaceTests.swift @@ -343,7 +343,8 @@ struct ProfileSurfaceTests { ) #expect(outcome == .seeded(copied: 8, present: 0)) for profile in ProfileSurface.allCases { - #expect(!FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-add-invocation-\(profile.profileName)"))) + let invocation = (binDir as NSString).appendingPathComponent("mcp-add-invocation-\(profile.profileName)") + #expect(!FileManager.default.fileExists(atPath: invocation)) } } diff --git a/MuseionTests/ProsePresenterTests.swift b/MuseionTests/ProsePresenterTests.swift index 69a4c60..58533d7 100644 --- a/MuseionTests/ProsePresenterTests.swift +++ b/MuseionTests/ProsePresenterTests.swift @@ -58,7 +58,11 @@ struct ProsePresenterTests { // sample at the heading TEXT, not offset 0 (the dimmed marker) let h1 = attributed.attribute(.font, at: ns.range(of: "H1").location, effectiveRange: nil) as? NSFont #expect(h1?.pointSize == 30) - #expect(h1?.fontName.contains("ConcourseOT") == true || h1?.fontName.contains("Semibold") == true || h1?.fontName.contains("Bold") == true) + #expect( + h1?.fontName.contains("ConcourseOT") == true + || h1?.fontName.contains("Semibold") == true + || h1?.fontName.contains("Bold") == true, + ) let h2 = attributed.attribute(.font, at: ns.range(of: "H2").location, effectiveRange: nil) as? NSFont #expect(h2?.pointSize == 22) let h3 = attributed.attribute(.font, at: ns.range(of: "H3").location, effectiveRange: nil) as? NSFont diff --git a/MuseionTests/ReadingPresenterTests.swift b/MuseionTests/ReadingPresenterTests.swift index c3fc526..5645f14 100644 --- a/MuseionTests/ReadingPresenterTests.swift +++ b/MuseionTests/ReadingPresenterTests.swift @@ -27,7 +27,8 @@ struct ReadingPresenterTests { @Test func `stamper rewrites attributes`() { let html = "

T

\n\n

A

\n\n
    \n
  • B
  • \n
" - #expect(ReadingPresenter.stampHTML(html) == "

T

\n

A

\n
    \n
  • B
  • \n
") + let expected = "

T

\n

A

\n
    \n
  • B
  • \n
" + #expect(ReadingPresenter.stampHTML(html) == expected) } /// The #68 click→edit map: blocks are monotonic, lines are 1-based, and diff --git a/docs/devlog/20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md b/docs/devlog/20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md new file mode 100644 index 0000000..95ab5f1 --- /dev/null +++ b/docs/devlog/20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md @@ -0,0 +1,72 @@ +# Close out: repo-wide swiftlint green becomes the documented lint contract (#197) + +> **Date:** 2026-11-17 +> **Type:** issue +> **Reference:** https://git.babylondreams.de/AlexKucera/Museion/issues/197 + +## Goal + +With #195 and #196 done, make the docs and code comments honest about repo-wide lint being green: refresh the pre-push hook's stale "pre-existing violations" rationale (gate semantics unchanged), prune/replace the stale #190 learning in AGENTS.md, confirm the root lint line is literally true — and land a green full unit suite. + +Tree composition note: the working tree also carries the uncommitted #194/#195/#196 batches (lint policy, test renames + `.swiftformat` name-format pin, warning-fix sweep) from earlier sessions today; this session implemented #197 on top, then ran a three-reviewer finish-audit over the whole 27-file diff. + +## What Was Done + +- `scripts/hooks/pre-push` — all three stale rationale blocks refreshed (header "pre-existing findings", gate block "a bare `swiftlint .` gate can never pass", NEW-ref note "pre-existing violations could never clear it") to the settled #190 design wording. Comment-only; gate logic byte-identical (reviewer grep-verified). +- `AGENTS.md` — the Tooling & gates learning rewritten to the true contract: repo-wide lint green (#194 policy, #195/#196 cleared every finding, `spike/` excluded as unbuilt), bare `swiftlint .` = 0 violations + `swiftformat .` reformats nothing, gates stay push-scoped. Root lint line confirmed literally true by execution. +- `MuseionTests/LibrarySearchTests.swift` — hardened `an unchanged rescan keeps the revision` against a pre-existing watcher-race flake: two FSEvent-burst rescans can snapshot the shared `PostScanCache` miss count before either stamps it, double-counting one first read → `contentRevision` double-bump (benign over-invalidation). The test now quiesces the burst (bounded 20 × 0.5 s stability loop, own deadline, post-loop `#expect`) before snapshotting. Suite scenario header names the fourth pin. +- Finish-audit (3 parallel reviewers: ponytail / security / general over the full uncommitted diff): + - Reviewer's "dead symlink clause" bug in `LearningsIndex.isPlainDirectory` **disproved by scratch probes** — `&&` out-binds `??` (`a ?? false && b` parses as `(a ?? false) && b`; second `??`/`&&` precedence claim probe-settled in this repo, see #26) and `URL.resourceValues` is lstat-style (symlink-to-dir → `isDirectory=false`). Kept parens + doc as readability hygiene; the expression had fooled a capable reviewer. + - `Museion/LearningsPaneView.swift` — guard reordered so the cheap rejections (`isPlainDirectory`, dot-prefix) short-circuit before the directory listing. + - `MuseionTests/LearningsPaneTests.swift` — new pin `a symlinked type dir never surfaces` (the documented "same skip posture as Post.scan" contract was unpinned). Flip-verified: the contract is **defended in depth** (lstat guard AND `contentsOfDirectory`'s own refusal of a symlinked entry URL) — the pin fails only when both go traversal-shaped (fileExists guard + resolved-URL listing failed the pin + a sibling pin; restored green). + - `Museion/MentorSessionModel.swift` — pre-existing `sessions.json` world-readable sub-second window (atomic write → 0o600 chmod) parked with a `ponytail:` ceiling comment naming the upgrade path (createFile-0600 + rename). + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Fix the LibrarySearchTests race in the TEST, not the model | The model's revision over-bump only over-invalidates a search snapshot (conservative-safe); serializing rescans or making the miss counter race-free is real machinery for a signal that tolerates false positives. The test's timing assumption was the bug (#147 family). | +| Keep parens in `isPlainDirectory` despite the finding being disproved | Behavior-identical, two characters, and the bare form demonstrably costs reviewer time — this audit burned a slot misreading it. | +| Symlink pin added although no behavior changed | The documented contract was unpinned; the flip cycle showed it is held up by two accidental mechanisms, exactly the kind of seam a future "simplification" breaks silently. | +| Chmod window parked, not fixed | Pre-existing, local-only, single-user workstation threat model; from-creation 0600 changes a pinned write path — ceiling comment names the trigger (hostile local account). | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Full suite failed 1/692 on first run (`an unchanged rescan keeps the revision`, `contentRevision 2 ≠ 1`) | Two FSEvent-burst rescans double-count one shared `PostScanCache` miss; the test snapshotted mid-burst | Quiesce loop before snapshotting; verified in isolation (7/7), full (693/693) | +| Flip cycle "passed" with the guard flipped — twice | **xcodebuild served stale binaries**: a source edit made seconds before invocation was not compiled (zero `SwiftCompile` lines, suite start 3 s after invocation) | `touch` the file and verify `SwiftCompile` lines in the run log before trusting any green; with that, guard-flip green → both-belts flip red → restored green | +| Reviewer precedence claim contradicted the code's comment | `a ?? b && c` precedence is genuinely easy to misread (this repo's second such dispute) | Scratch probes settle it empirically — never rewrite comments on a reviewer's word | +| `swiftlint` line_length (187 chars) after the guard reorder | swiftformat merges adjacent guards into one long condition list | Wrap the call arguments inside the condition (the shape the same function already uses for its root listing); format-stable on re-run | +| Rail scoped reruns looked green during the flip | Stale-build hazard above | Always confirm compile lines in the run log for rapid edit→test cycles | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `scripts/hooks/pre-push` | Three stale rationale comment blocks refreshed; logic untouched | +| `AGENTS.md` | Tooling & gates learning rewritten to the true lint contract | +| `MuseionTests/LibrarySearchTests.swift` | Quiesce loop hardening + scenario header names the settled-state pin | +| `Museion/LearningsPaneView.swift` | Guard reorder, parens + doc on `isPlainDirectory` | +| `MuseionTests/LearningsPaneTests.swift` | New symlink-skip pin with flip-verified doc | +| `Museion/MentorSessionModel.swift` | Ceiling comment on the roster chmod window | + +(The commit also carries the #194/#195/#196 batches from earlier sessions: `.swiftlint.yml`, `.swiftformat`, `MuseionTests/AGENTS.md`, `PolishSeamTests.swift`, and the #196 warning-fix sweep across 11 app files + test files + `prototypes/GateUIPrototype.swift`.) + +## Open Items & Next Steps + +- [ ] User: commit + push (carries `Closes #197`; #194–#196 already closed on the tracker), verify auto-close +- [ ] Candidate project learning: xcodebuild can skip recompiling a source edited seconds before invocation — flip/edit-test cycles must `touch` and verify `SwiftCompile` lines in the run log +- [ ] Parked: roster 0600-from-creation if a hostile local account ever matters (`Museion/MentorSessionModel.swift` ceiling comment) + +## Verification + +- `swiftlint .` — 0 violations / 130 files, exit 0 +- `swiftformat .` — 0/141 formatted, tree unchanged +- `./scripts/test-full-test.sh` — 23/23 hook acceptance checks +- `./scripts/full-test.sh` — **693 executed / 693 passed / 0 failed** (run `20261117T151013Z-Museion`; no source file newer than the run — the green attaches to the committed bytes) +- GitNexus: `detect-changes` risk **critical** (breadth: 100+ symbols across the four-ticket mechanical batch — affected-scope checked by the 3-reviewer fanout, probes, and the suite); `analyze` reindexed (7,035 nodes / 34,056 edges) + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 7166a99..e621563 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-11-17 | issue | [20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md](20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md) | Lint-green doc truth (#197) + finish-audit; watcher-race test quiesced, symlink pin flip-verified, stale-xcodebuild hazard found; 693/693 | | 2026-11-17 | feat | [20261117-issue190-full-test-verify-rail-pre-push-hook_log.md](20261117-issue190-full-test-verify-rail-pre-push-hook_log.md) | Classis full-test.sh ported as the verify rail + pre-push hook; 4-round finish-audit; suite 692/692 via the rail, hook rig 23/23 | | 2026-11-13 | opt | [20261113-fold-typing-budget-pin_log.md](20261113-fold-typing-budget-pin_log.md) | Unticketed pin (brief-24): typing-cost guard for the #142 re-key — per-call line-scan observer through the real keystroke pipeline; zero scans beside a fold at N/2N, exact-count control 206/406, mutation-checked | | 2026-11-13 | opt | [20261113-cold-turkey-full-tokenization_log.md](20261113-cold-turkey-full-tokenization_log.md) | Unticketed opt (argus digest): minutes feeds skip word counting entirely; DraftStats.words count-only — no token array per keystroke; +3 pins (RED-first rail-trip seam, corpus equivalence), suite 684 | diff --git a/prototypes/GateUIPrototype.swift b/prototypes/GateUIPrototype.swift index 3853964..e86f72f 100644 --- a/prototypes/GateUIPrototype.swift +++ b/prototypes/GateUIPrototype.swift @@ -240,7 +240,11 @@ struct MockWorkspace: View { } private var previewText: String { - String(repeating: "The essay argues itself into a corner by the third paragraph, and the prose knows it. Sentences shorten. Claims retreat. ", count: 6) + String( + repeating: "The essay argues itself into a corner by the third paragraph, and the prose knows it. " + + "Sentences shorten. Claims retreat. ", + count: 6, + ) } } @@ -316,7 +320,9 @@ struct VariantA: View { switch model.phase { case .checking: "Running hermes acp --check." case .passed: "Hermes \(model.version) answered the health check. The mentor is available." - case .failed: "The Hermes engine wasn't found or didn't answer. Museion can't run Passes or Sessions without it — the editor below stays available." + case .failed: + "The Hermes engine wasn't found or didn't answer. Museion can't run Passes or Sessions " + + "without it — the editor below stays available." } } } diff --git a/scripts/hooks/pre-push b/scripts/hooks/pre-push index 8fc926d..c999b20 100755 --- a/scripts/hooks/pre-push +++ b/scripts/hooks/pre-push @@ -5,8 +5,8 @@ # 1. no push while a full-test run is live — concurrent load flakes the # real-process suites (#30), and pushing mid-verification defeats the run; # 2. lint gate scoped to the push's own Swift files — failing closed on -# violations there (the repo tree carries pre-existing findings a bare -# repo-wide gate could never clear); +# violations there (settled #190 design: the gate guards what the +# push itself carries, not the whole tree); # 3. autofix guard — a lint autofix pass that rewrites files AFTER # verification must not ride the push untested: the push fails, the # rewrite gets reviewed and re-verified via scripts/full-test.sh. @@ -44,11 +44,10 @@ if [[ -n $live ]]; then exit 1 fi -# 2. Lint gate, scoped to THIS PUSH's Swift files (#190): the repo tree -# carries pre-existing swiftlint findings (warning noise repo-wide, -# error-severity in spike/ experiments and one tests file) — a bare -# `swiftlint .` gate can never pass here and would block every push. -# The gate is the push's own files; no Swift in the push → nothing to gate. +# 2. Lint gate, scoped to THIS PUSH's Swift files (#190): the gate guards +# what the push itself carries — settled #190 design, kept even now +# that bare `swiftlint .` runs green repo-wide (#195/#196 cleared the +# last findings). No Swift in the push → nothing to gate. before="$(git status --porcelain)" zero=0000000000000000000000000000000000000000 # Default-branch base for NEW-ref scoping: the project's default branch at @@ -63,7 +62,7 @@ while read -r lref lsha rref rsha; do [[ "$lsha" == "$zero" ]] && continue # ref deletion — no content to lint if [[ "$rsha" == "$zero" ]]; then # NEW ref: lint the delta against the default branch, never the whole - # tree (pre-existing violations could never clear it). No resolvable + # tree (the gate is the push's delta, not the repo). No resolvable # base FAILS CLOSED — a silent skip is a vacuous pass (#31/#134 class). base="$(git merge-base "$lsha" "$default_ref" 2>/dev/null || true)" [[ -n "$base" ]] || {