chore(lint): repo-wide green becomes the contract
CI / ci (push) Canceled after 0s

Close the lint arc #194-#197: deliberate-style rule disables with
rationales (#194), filter-safe test renames + --test-case-name-format
preserve (#195), every surviving warning fixed through the sanctioned
lint-stable shapes (#196), and the docs now state the true contract
(#197): bare swiftlint . reports zero violations and swiftformat .
reformats nothing, while push gates stay scoped to the push's own
files (settled #190 design) — the pre-push hook's stale 'pre-existing
violations' rationale blocks refreshed, gate logic untouched.

Also in the sweep: quiesce the FSEvent-burst watcher race in
LibrarySearchTests (two rescans double-count one shared PostScanCache
miss; benign revision over-bump), pin the learnings scan's symlink-skip
contract (flip-verified — defended in depth by the lstat guard AND
contentsOfDirectory's own symlink refusal), reorder that scan's guard
so cheap rejections precede the directory listing, and park the roster
chmod window with a ceiling comment.

Finish-audit: 3 reviewers, 0 blocking; the one code finding was
disproved by probe (&& out-binds ?? — the guard was correct). Suite
693/693 via scripts/full-test.sh; swiftlint 0 violations; swiftformat
0/141; hook rig 23/23.

Closes #197
This commit is contained in:
AlexKucera committed 2026-11-17 16:29:46 +01:00
1 parent 0ab00eb7b6
commit d7fd11cf0d
29 files changed
+549 -269

No files matched your search

+1
View File
@@ -1,3 +1,4 @@
--swiftversion 6.3 --swiftversion 6.3
--language-mode 5 --language-mode 5
--indent tab --indent tab
--test-case-name-format preserve # convention is backticked sentence names; filter-safe camelCase exceptions allowed (#195, #31/#134)
+7
View File
@@ -1,7 +1,14 @@
disabled_rules: disabled_rules:
- trailing_comma # SE-0439 allows them in Swift 6; SwiftFormat adds them - 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: excluded:
- DerivedData - DerivedData
- spike # throwaway SPM experiments, not built into any target
line_length: line_length:
warning: 140 warning: 140
error: 180 error: 180
+6 -2
View File
@@ -135,7 +135,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
<!-- gitnexus:start --> <!-- gitnexus:start -->
# GitNexus — Code Intelligence # 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). > 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
<!-- distill-learnings: project-learnings --> <!-- distill-learnings: project-learnings -->
### Tooling & gates ### 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/<remote>/<branch>` in full or a fetched tag named `origin/main` shadows the ref (#190) - git resolves short refs through `refs/tags/` before `refs/remotes/` — hooks and scripts spell `refs/remotes/<remote>/<branch>` 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) - 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 ### 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) - 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) - 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) - 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) - `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
<!-- write-log: window-start --> <!-- write-log: window-start -->
| Date | Log | | 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-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-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) | | 2026-11-13 | [20261113-cold-turkey-full-tokenization_log.md](docs/devlog/20261113-cold-turkey-full-tokenization_log.md) |
+10 -3
View File
@@ -75,8 +75,10 @@ nonisolated enum LearningsIndex {
) else { return [] } ) else { return [] }
var groups: [Group] = [] var groups: [Group] = []
for dir in typeDirs.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) { 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) guard isPlainDirectory(dir), !dir.lastPathComponent.hasPrefix("."),
else { continue } let files = try? FileManager.default.contentsOfDirectory(
at: dir, includingPropertiesForKeys: nil,
) else { continue }
// #27: the pass clock feeds the decay verdict — clocked dirs // #27: the pass clock feeds the decay verdict — clocked dirs
// carry their count, foreign dirs nil (no verdict; Entry's audit). // carry their count, foreign dirs nil (no verdict; Entry's audit).
let currentPass = LearningDecay.isClocked(dir.lastPathComponent) let currentPass = LearningDecay.isClocked(dir.lastPathComponent)
@@ -109,9 +111,14 @@ nonisolated enum LearningsIndex {
return groups 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 { private static func isPlainDirectory(_ url: URL) -> Bool {
let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
return values?.isDirectory ?? false && !(values?.isSymbolicLink ?? false) return (values?.isDirectory ?? false) && !(values?.isSymbolicLink ?? false)
} }
} }
+6 -2
View File
@@ -149,13 +149,17 @@ nonisolated enum SessionRoster {
let dir = directory ?? defaultDirectory let dir = directory ?? defaultDirectory
do { do {
try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
let rosterURL = URL(fileURLWithPath: dir).appendingPathComponent("sessions.json")
try JSONEncoder().encode(entries).write( try JSONEncoder().encode(entries).write(
to: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json"), to: rosterURL,
options: .atomic, options: .atomic,
) )
// Finish-audit: names+ids only, but piece titles are the writer's // Finish-audit: names+ids only, but piece titles are the writer's
// business — the default umask would hand them to every local user. // 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 { } catch {
// ponytail: the roster is a convenience index; a write failure must not crash the gate. // ponytail: the roster is a convenience index; a write failure must not crash the gate.
} }
+60 -44
View File
@@ -55,10 +55,7 @@ nonisolated enum OutlinePresenter {
_ nodes: [OutlineNode], folded: Set<UUID>, zoomRootID: UUID? = nil, _ nodes: [OutlineNode], folded: Set<UUID>, zoomRootID: UUID? = nil,
) -> [Row] { ) -> [Row] {
var rows: [Row] = [] var rows: [Row] = []
if let zoomRootID, if let zoomRootID, let rootPath = path(of: zoomRootID, in: nodes), let root = node(at: rootPath, in: nodes) {
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) walk(root.children, parent: rootPath, depth: 0, folded: folded, into: &rows)
} else { } else {
walk(nodes, parent: [], depth: 0, folded: folded, into: &rows) walk(nodes, parent: [], depth: 0, folded: folded, into: &rows)
@@ -776,27 +773,14 @@ extension OutlineEditorView {
} }
case let .hop(direction): case let .hop(direction):
// ↑/↓ hop VISIBLE blocks — folded subtrees are skipped. // ↑/↓ hop VISIBLE blocks — folded subtrees are skipped.
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last) hopFocus(direction, clearsAnchor: true)
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
}
case let .extend(direction): case let .extend(direction):
// ⇧↑/⇧↓: extend the block selection one visible row. First // ⇧↑/⇧↓: extend the block selection one visible row. First
// press anchors at the focused row; a bare ↑/↓ or click clears. // press anchors at the focused row; a bare ↑/↓ or click clears.
if let focusedID { if let focusedID {
extendSelection(to: focusedID) // arm the anchor at the current focus extendSelection(to: focusedID) // arm the anchor at the current focus
} }
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last) hopFocus(direction, clearsAnchor: false)
if let current = rows.firstIndex(where: { $0.id == focusedID }),
rows.indices.contains(current + direction)
{
focusedID = rows[current + direction].id
pendingCaret = nil
}
case .deselect: case .deselect:
_ = handleEscape() // selection first, then zoom — same order as the monitor _ = handleEscape() // selection first, then zoom — same order as the monitor
case .indent, .outdent, .moveUp, .moveDown, .enter: 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 /// Tree-mutating ops (indent/outdent/move/enter). Serialize + route
/// focus only when something actually changed (boundary no-ops are /// focus only when something actually changed (boundary no-ops are
/// nil and leave the document alone). /// nil and leave the document alone).
private func applyTree(_ op: OutlineRowTextView.StructureOp) { private func applyTree(_ op: OutlineRowTextView.StructureOp) {
guard let focusedID else { return } guard let focusedID else { return }
// Block selection + batchable op → run-wide apply. Moves treat if applyBatchIfPossible(op, focus: focusedID) {
// 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()
}
return return
} }
guard let path = OutlinePresenter.path(of: focusedID, in: nodes) else { return } guard let path = OutlinePresenter.path(of: focusedID, in: nodes) else { return }
@@ -833,27 +824,52 @@ extension OutlineEditorView {
case .moveDown: case .moveDown:
didChange = OutlineTree.move(&nodes, path: path, up: false) != nil didChange = OutlineTree.move(&nodes, path: path, up: false) != nil
case let .enter(caretGraphemes): case let .enter(caretGraphemes):
switch OutlineTree.enter(&nodes, path: path, caretOffset: caretGraphemes) { let enter = applyEnter(caretGraphemes: caretGraphemes, path: path)
case .noOp: didChange = enter.didChange
break newFocus = enter.focus
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)
}
}
case .fold, .unfold, .hop, .extend, .deselect: case .fold, .unfold, .hop, .extend, .deselect:
return // unreachable — apply(_:) routes those to view state return // unreachable — apply(_:) routes those to view state
} }
if didChange { commitIfChanged(didChange, newFocus)
if let newFocus { }
self.focusedID = newFocus.id
pendingCaret = newFocus.caret /// 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() 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). /// The selected row ids in visible order (anchor↔focus, inclusive).
+1 -3
View File
@@ -84,9 +84,7 @@ nonisolated enum ProfileBackup {
// Age check against the newest existing snapshot (#15: skips record no // Age check against the newest existing snapshot (#15: skips record no
// state; the normal age check governs retry). // state; the normal age check governs retry).
if let newest = sortedSnapshots(in: backupsRoot).first, if let newest = sortedSnapshots(in: backupsRoot).first, now.timeIntervalSince(newest.timestamp) < snapshotInterval {
now.timeIntervalSince(newest.timestamp) < snapshotInterval
{
return .skippedFresh return .skippedFresh
} }
+37 -26
View File
@@ -139,16 +139,16 @@ nonisolated enum ProfileProvisioner {
return logFailure(.failed(profile: profile, phase: phase, excerpt: excerpt)) 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 { for surface in ProfileSurface.allCases {
switch provisionSurface( switch provisionSurface(surface, env: env) {
surface,
hermesBinary: hermesBinary,
profileRoot: profileRoot,
masterRoot: masterRoot,
manifest: manifest,
serverBinaryPath: serverBinaryPath,
timeout: timeout,
) {
case let .seeded(deltaCopied, deltaPresent): case let .seeded(deltaCopied, deltaPresent):
copied += deltaCopied copied += deltaCopied
present += deltaPresent present += deltaPresent
@@ -165,20 +165,27 @@ nonisolated enum ProfileProvisioner {
return .seeded(copied: copied, present: present) 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 /// Phases 1–4 for ONE surface profile (#134): create (or adopt), write
/// defaults on fresh profiles via the CLI rail, link skills per /// defaults on fresh profiles via the CLI rail, link skills per
/// allocation, register museion-tools (#23). /// allocation, register museion-tools (#23).
private static func provisionSurface( private static func provisionSurface(
_ surface: ProfileSurface, _ surface: ProfileSurface,
hermesBinary: String?, env: SurfaceEnv,
profileRoot: String,
masterRoot: String,
manifest: [String],
serverBinaryPath: String?,
timeout: TimeInterval,
) -> Outcome { ) -> Outcome {
let fileManager = FileManager.default 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 // Phase 1 — profile create. Dir-check first; spawn only when
// missing (#45). `museion` is adopted, never re-created (ADR-0014). // 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). // carry only Museion's curated set — coding and writing never mix, G3).
var createdFresh = false var createdFresh = false
if !fileManager.fileExists(atPath: profileDir) { 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") return .failed(profile: surface.profileName, phase: .create, excerpt: "hermes binary not found")
} }
let run = EngineProbe.execute( let run = EngineProbe.execute(
[binary, "profile", "create", surface.profileName, "--no-alias", "--no-skills"], [binary, "profile", "create", surface.profileName, "--no-alias", "--no-skills"],
timeout: timeout, timeout: env.timeout,
) )
// #43: exit 1 + "already exists" on stdout = success (a // #43: exit 1 + "already exists" on stdout = success (a
// concurrent create — not ours, so not fresh); all errors print on stdout. // 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 // profile (interrupted before its marker landed) is healed, and
// the adopted museion is never touched — its model is the user's. // the adopted museion is never touched — its model is the user's.
if createdFresh || (surface != .chat && !markerExists(at: profileDir)) { 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") 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 return failure
} }
// A marker we couldn't record = configure incomplete — surface it // 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 // Phase 3 — per-profile skills: symlinks per allocation + the
// copy-era → symlink migration (#133). // 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 { if case .failed = linked {
return linked return linked
} }
@@ -232,7 +239,7 @@ nonisolated enum ProfileProvisioner {
// Phase 4 — museion-tools registration per profile (ADR-0008 // Phase 4 — museion-tools registration per profile (ADR-0008
// amendment). nil on either binary is the test-injection seam; // amendment). nil on either binary is the test-injection seam;
// production always has both after a gate pass. // 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") Logger(subsystem: subsystem, category: "provisioning")
.info("museion-tools registration skipped: engine or server binary missing") .info("museion-tools registration skipped: engine or server binary missing")
return linked return linked
@@ -241,7 +248,7 @@ nonisolated enum ProfileProvisioner {
profile: surface.profileName, profile: surface.profileName,
hermesBinary: hermesBinary, hermesBinary: hermesBinary,
serverBinaryPath: serverBinaryPath, serverBinaryPath: serverBinaryPath,
timeout: timeout, timeout: env.timeout,
) { ) {
return failure return failure
} }
@@ -511,6 +518,12 @@ nonisolated extension ProfileProvisioner {
!name.isEmpty && name.allSatisfy { ($0.isLowercase && $0.isLetter) || $0.isNumber || $0 == "-" } !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 /// Recursive byte-comparison of two dir trees — same entry names, every
/// file byte-identical. `.DS_Store` is filtered from BOTH listings before /// file byte-identical. `.DS_Store` is filtered from BOTH listings before
/// the name-equality check (Finder noise, not a user edit — a /// 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) let rhsPath = (rhs as NSString).appendingPathComponent(name)
// Neither side may carry a symlink at this entry (lstat-true, // Neither side may carry a symlink at this entry (lstat-true,
// before any open) — the payload never ships one. // before any open) — the payload never ships one.
if (try? fileManager.destinationOfSymbolicLink(atPath: lhsPath)) != nil if isSymlinked(lhsPath) || isSymlinked(rhsPath) {
|| (try? fileManager.destinationOfSymbolicLink(atPath: rhsPath)) != nil
{
return false return false
} }
var lhsIsDirectory: ObjCBool = false, rhsIsDirectory: ObjCBool = false var lhsIsDirectory: ObjCBool = false, rhsIsDirectory: ObjCBool = false
+1 -4
View File
@@ -377,10 +377,7 @@ final class ProseListTextView: NSTextView {
guard let scalar = Unicode.Scalar(Int(char)) else { return false } guard let scalar = Unicode.Scalar(Int(char)) else { return false }
return CharacterSet.whitespacesAndNewlines.contains(scalar) return CharacterSet.whitespacesAndNewlines.contains(scalar)
} }
if index > 0, index < length, if index > 0, index < length, !isGap(buffer.character(at: index - 1)), !isGap(buffer.character(at: index)) {
!isGap(buffer.character(at: index - 1)),
!isGap(buffer.character(at: index))
{
while index < length, !isGap(buffer.character(at: index)) { while index < length, !isGap(buffer.character(at: index)) {
index += 1 index += 1
} }
+177 -102
View File
@@ -38,6 +38,39 @@ nonisolated enum ProsePresenter {
classify(line, inFence: false) 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 /// Delimiter lines are fences even inside a fence (they close it) — so the
/// delim test runs before the inFence shortcut and `applyStyles` toggles /// delim test runs before the inFence shortcut and `applyStyles` toggles
/// on `kind == .fence` instead of re-deriving the prefix. /// on `kind == .fence` instead of re-deriving the prefix.
@@ -46,28 +79,19 @@ nonisolated enum ProsePresenter {
if trimmed.isEmpty { if trimmed.isEmpty {
return .blank return .blank
} }
if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") { if isFenceDelimiter(trimmed) {
return .fence return .fence
} }
if inFence { if inFence {
return .fenceInterior return .fenceInterior
} }
let hashes = trimmed.prefix(while: { $0 == "#" }).count if let hashes = headingLevel(of: trimmed) {
if hashes > 0, hashes <= 6 { // CommonMark caps at 6; 7+ is body return headingKind(hashes)
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 trimmed.hasPrefix(">") { if trimmed.hasPrefix(">") {
return .quote return .quote
} }
if trimmed.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) { if isRuleSyntax(trimmed) {
return .syntaxOnly return .syntaxOnly
} }
if line.firstMatch(of: listMarkerPattern) != nil { if line.firstMatch(of: listMarkerPattern) != nil {
@@ -102,7 +126,7 @@ nonisolated enum ProsePresenter {
var count = 0 var count = 0
for line in text.split(separator: "\n", omittingEmptySubsequences: false) { for line in text.split(separator: "\n", omittingEmptySubsequences: false) {
let trimmed = line.drop(while: { $0 == " " || $0 == "\t" }) let trimmed = line.drop(while: { $0 == " " || $0 == "\t" })
if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") { if isFenceDelimiter(trimmed) {
count += 1 count += 1
} }
} }
@@ -171,58 +195,76 @@ nonisolated enum ProsePresenter {
/// Count unclosed fences before `end` (``` or ~~~ delim lines toggle). /// Count unclosed fences before `end` (``` or ~~~ delim lines toggle).
private static func fenceState(_ nsText: NSString, upTo end: Int) -> Bool { private static func fenceState(_ nsText: NSString, upTo end: Int) -> Bool {
var inFence = false var inFence = false
for line in contentLines(nsText, in: NSRange(location: 0, length: min(end, nsText.length))) { let prefix = NSRange(location: 0, length: min(end, nsText.length))
if classify(line.text, inFence: inFence) == .fence { for line in contentLines(nsText, in: prefix) where classify(line.text, inFence: inFence) == .fence {
inFence.toggle() inFence.toggle()
}
} }
return inFence 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<Substring>, 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) { private static func styleLine(_ out: NSMutableAttributedString, line: Line, kind: LineKind, isTitle: Bool = false) {
guard line.full.length > 0 else { return } guard line.full.length > 0 else { return }
out.setAttributes(isTitle ? ProseTypography.titleAttributes : attributes(for: kind), range: line.full) out.setAttributes(isTitle ? ProseTypography.titleAttributes : attributes(for: kind), range: line.full)
let dim = ProseTypography.codeAttributes // codeFont + syntaxColor let dim = ProseTypography.codeAttributes // codeFont + syntaxColor
switch kind { switch kind {
case .heading1, .heading2, .heading3, .heading4Plus: case .heading1, .heading2, .heading3, .heading4Plus:
let lead = line.text.prefix(while: { $0 == " " || $0 == "\t" }).utf16.count dimHeadingMarker(out, line: line)
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)
}
case .quote: 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)) out.addAttributes(dim, range: shifted(marker, into: line.content))
} }
case .listMarker: case .listMarker:
if let marker = markerRangeUTF16(listMarkerPattern, in: line.text), marker.length > 0 { applyListMarker(out, line: line)
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)
}
case .syntaxOnly: case .syntaxOnly:
if line.content.length > 0 { if line.content.length > 0 {
out.addAttributes(dim, range: line.content) out.addAttributes(dim, range: line.content)
@@ -232,7 +274,7 @@ nonisolated enum ProsePresenter {
case .fenceInterior, .blank, .body: case .fenceInterior, .blank, .body:
break break
} }
if kind == .body || kind == .quote || kind == .listMarker { if carriesInlineTraits(kind) {
styleInline(out, content: line.content, text: line.text) styleInline(out, content: line.content, text: line.text)
} }
} }
@@ -256,98 +298,119 @@ nonisolated enum ProsePresenter {
private nonisolated(unsafe) static let linkPattern = /\[[^\]\n]*\]\([^)\n]*\)/ private nonisolated(unsafe) static let linkPattern = /\[[^\]\n]*\]\([^)\n]*\)/
/// Trait-style inline constructs. Marks dim; content gets real traits. /// 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) { private static func styleInline(_ out: NSMutableAttributedString, content: NSRange, text: String) {
guard content.length > 0 else { return } guard content.length > 0 else { return }
var claimed: [Range<Int>] = [] var claimed: [Range<Int>] = []
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<Int>) -> Bool { /// Claim `span` unless an earlier (higher-priority) match overlaps it.
guard !claimed.contains(where: { $0.overlaps(span) }) else { return false } private static func claim(_ claimed: inout [Range<Int>], _ span: Range<Int>) -> Bool {
claimed.append(span) guard !claimed.contains(where: { $0.overlaps(span) }) else { return false }
return true claimed.append(span)
} return true
}
func dim(_ utf16: Range<Int>) { /// Dim a utf16 span in the code face (marks, brackets, stray syntax).
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count) private static func dim(_ out: NSMutableAttributedString, content: NSRange, _ utf16: Range<Int>) {
out.addAttributes(ProseTypography.codeAttributes, range: range) let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
} out.addAttributes(ProseTypography.codeAttributes, range: range)
}
func attr(_ utf16: Range<Int>, _ attrs: [NSAttributedString.Key: Any]) { /// Apply `attrs` to a utf16 span.
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count) private static func attr(_ out: NSMutableAttributedString, content: NSRange, _ utf16: Range<Int>, _ attrs: [NSAttributedString.Key: Any]) {
out.addAttributes(attrs, range: range) let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
} out.addAttributes(attrs, range: range)
}
let boldFont = ProseTypography.boldBodyFont /// Inline code + links (priority 1–2). Code: marks + content in the code
let italicFont = ProseTypography.italicBodyFont /// 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<Int>],
) {
let codeFont = ProseTypography.codeFont let codeFont = ProseTypography.codeFont
let ink: [NSAttributedString.Key: Any] = [.foregroundColor: ProseTypography.foregroundColor] let ink: [NSAttributedString.Key: Any] = [.foregroundColor: ProseTypography.foregroundColor]
let linkAttrs: [NSAttributedString.Key: Any] = [ let linkAttrs: [NSAttributedString.Key: Any] = [
.underlineStyle: NSUnderlineStyle.single.rawValue, .underlineStyle: NSUnderlineStyle.single.rawValue,
.underlineColor: ProseTypography.mutedColor, .underlineColor: ProseTypography.mutedColor,
] ]
// inline code — marks + content in the code face, content at ink // inline code — marks + content in the code face, content at ink
for match in text.matches(of: codePattern) { for match in text.matches(of: codePattern) {
let span = match.range.utf16Range(in: text) let span = match.range.utf16Range(in: text)
guard claim(span) else { continue } guard claim(&claimed, span) else { continue }
dim(span.lowerBound ..< span.lowerBound + 1) dim(out, content: content, span.lowerBound ..< span.lowerBound + 1)
dim(span.upperBound - 1 ..< span.upperBound) dim(out, content: content, span.upperBound - 1 ..< span.upperBound)
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: codeFont].merging(ink) { _, new in new }) 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) { for match in text.matches(of: linkPattern) {
let span = match.range.utf16Range(in: text) 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) let whole = match.output // whole match (no capture groups)
guard let sep = whole.firstRange(of: "](") else { continue } guard let sep = whole.firstRange(of: "](") else { continue }
// sep indices are valid in text (Substring shares indices) // 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 sepOffset = text.utf16.distance(from: text.utf16.startIndex, to: sep.lowerBound.samePosition(in: text.utf16)!)
let label = span.lowerBound + 1 ..< sepOffset let label = span.lowerBound + 1 ..< sepOffset
dim(span.lowerBound ..< span.lowerBound + 1) // [ dim(out, content: content, span.lowerBound ..< span.lowerBound + 1) // [
attr(label, linkAttrs) attr(out, content: content, label, linkAttrs)
dim(sepOffset ..< span.upperBound) // ](url) 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<Int>],
) {
let boldFont = ProseTypography.boldBodyFont
let italicFont = ProseTypography.italicBodyFont
for match in text.matches(of: boldPattern) { for match in text.matches(of: boldPattern) {
let span = match.range.utf16Range(in: text) let span = match.range.utf16Range(in: text)
guard claim(span) else { continue } guard claim(&claimed, span) else { continue }
dim(span.lowerBound ..< span.lowerBound + 2) dim(out, content: content, span.lowerBound ..< span.lowerBound + 2)
dim(span.upperBound - 2 ..< span.upperBound) dim(out, content: content, span.upperBound - 2 ..< span.upperBound)
attr(span.lowerBound + 2 ..< span.upperBound - 2, [.font: boldFont]) 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) { for match in text.matches(of: emStarPattern) {
let span = match.range.utf16Range(in: text) 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 lo = charBefore(text, span.lowerBound)
let hi = charAfter(text, span.upperBound) let hi = charAfter(text, span.upperBound)
if lo == "*" || hi == "*" || lo == "_" || hi == "_" { if isMarkAdjacent(lo, hi) {
continue continue
} }
dim(span.lowerBound ..< span.lowerBound + 1) dim(out, content: content, span.lowerBound ..< span.lowerBound + 1)
dim(span.upperBound - 1 ..< span.upperBound) dim(out, content: content, span.upperBound - 1 ..< span.upperBound)
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont]) attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont])
} }
for match in text.matches(of: emUnderPattern) { for match in text.matches(of: emUnderPattern) {
let span = match.range.utf16Range(in: text) 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 lo = charBefore(text, span.lowerBound)
let hi = charAfter(text, span.upperBound) let hi = charAfter(text, span.upperBound)
if lo == "*" || hi == "*" || lo == "_" || hi == "_" { if isMarkAdjacent(lo, hi) {
continue continue
} }
if lo?.isLetter == true || lo?.isNumber == true || hi?.isLetter == true || hi?.isNumber == true { if isIntraword(lo, hi) {
continue continue
} }
dim(span.lowerBound ..< span.lowerBound + 1) dim(out, content: content, span.lowerBound ..< span.lowerBound + 1)
dim(span.upperBound - 1 ..< span.upperBound) dim(out, content: content, span.upperBound - 1 ..< span.upperBound)
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont]) 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<Int>],
) {
let syntax = inlineSyntax let syntax = inlineSyntax
for (offset, codeUnit) in text.utf16.enumerated() { for (offset, codeUnit) in text.utf16.enumerated() {
guard let scalar = Unicode.Scalar(codeUnit).map({ Character($0) }), syntax.contains(scalar) else { continue } 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) }) { if claimed.contains(where: { $0.overlaps(unit) }) {
continue 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 // MARK: Base attributes
static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] { static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] {
+4 -2
View File
@@ -31,10 +31,12 @@ nonisolated enum ProseTypography {
/// Headings = Concourse OT (the designer's own pairing with Valkyrie); /// Headings = Concourse OT (the designer's own pairing with Valkyrie);
/// Semibold carries heading weight better than Book on screen. /// 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). /// 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 /// 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 /// cut has no 600 member — the bold trait (700, real or synthesized) is
+3 -2
View File
@@ -104,7 +104,7 @@ nonisolated enum ReadingPresenter {
// swiftlint:disable:next force_try // swiftlint:disable:next force_try
let regex = try! NSRegularExpression(pattern: #"<!--S:(\d+)-->\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#) let regex = try! NSRegularExpression(pattern: #"<!--S:(\d+)-->\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#)
let mutable = NSMutableString(string: html) 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 return mutable as String
} }
@@ -207,7 +207,8 @@ nonisolated enum ReadingPresenter {
/// apex failure / missing binary → editing-treated source text (#69's /// apex failure / missing binary → editing-treated source text (#69's
/// fallback rule: fallback = the source, not a second renderer). /// fallback rule: fallback = the source, not a second renderer).
static func fallbackPage(_ text: String) -> String { static func fallbackPage(_ text: String) -> String {
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(styleSheet())</style></head><body><pre data-source-line=\"1\">\(escapeHTML(text))</pre></body></html>" "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(styleSheet())</style></head>" +
"<body><pre data-source-line=\"1\">\(escapeHTML(text))</pre></body></html>"
} }
static func escapeHTML(_ text: String) -> String { static func escapeHTML(_ text: String) -> String {
+8 -3
View File
@@ -172,6 +172,13 @@ struct ReadingSurface: NSViewRepresentable {
wv.evaluateJavaScript(ReadingSurface.entryScrollJS(line)) 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 /// Allow our own loadHTMLString main-frame load (about:blank); a
/// blanket .cancel would kill the page before it paints. Everything /// blanket .cancel would kill the page before it paints. Everything
/// else is cancelled — reading never navigates in-app (#74 lesson). /// else is cancelled — reading never navigates in-app (#74 lesson).
@@ -180,9 +187,7 @@ struct ReadingSurface: NSViewRepresentable {
decidePolicyFor nav: WKNavigationAction, decidePolicyFor nav: WKNavigationAction,
decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void, decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void,
) { ) {
if nav.targetFrame?.isMainFrame == true, if isOwnMainFrameLoad(nav) {
let url = nav.request.url, url.scheme == "file" || url.absoluteString == "about:blank"
{
decisionHandler(.allow) decisionHandler(.allow)
return return
} }
+6 -3
View File
@@ -574,9 +574,12 @@ private struct OutlineGuardSheet: View {
VStack(alignment: .leading, spacing: 12) { VStack(alignment: .leading, spacing: 12) {
Text("Open as outline or prose?") Text("Open as outline or prose?")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) .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.") Text(
.font(.callout) "This outline has paragraph lines between its bullets. The outliner can't show them — opening as an outline " +
.foregroundStyle(DesignTokens.muted) "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.") Text("Outline mode keeps its bullets, indentation, and folding. You can convert or clean up later.")
.font(.callout) .font(.callout)
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
+10 -3
View File
@@ -299,12 +299,19 @@ enum WritingLockKiosk {
return false 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() { private static func installRefusalMonitor() {
guard refusalMonitor == nil else { return } guard refusalMonitor == nil else { return }
refusalMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in refusalMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
if WritingLockState.active?.isLocked == true, if Self.shouldRefuse(event) {
Self.refusesKey(keyCode: event.keyCode, characters: event.charactersIgnoringModifiers, modifiers: event.modifierFlags)
{
return nil // swallowed — the lock holds return nil // swallowed — the lock holds
} }
return event return event
+1
View File
@@ -12,6 +12,7 @@ Owned by the root AGENTS.md contract.
- Uses Swift Testing (`@Test`, `#expect`) — not XCTest. - Uses Swift Testing (`@Test`, `#expect`) — not XCTest.
- Always give `@Suite` its string argument — bare `@Suite` is stripped by this repo's swiftformat. - 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. - 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. - Deployment target and versions follow the app target; leave `CURRENT_PROJECT_VERSION = 1` here.
+19
View File
@@ -124,6 +124,25 @@ struct LearningsPaneTests {
#expect(LearningsIndex.scan(home: home).isEmpty) #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) // MARK: Decay surface (#27, S4.2)
/// Scenario: Entry carries the decay verdict — visible learnings read /// Scenario: Entry carries the decay verdict — visible learnings read
+16 -2
View File
@@ -96,7 +96,8 @@ struct LibrarySearchTests {
/// while it `isFresh` for the CURRENT key. The controller pins drive /// while it `isFresh` for the CURRENT key. The controller pins drive
/// the real rescan rail (write verbs + the rail's own rescan Task) and /// 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 /// 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 /// library it searched (archived rows linger in the results; edited
/// bodies never enter or leave them until the query changes). /// bodies never enter or leave them until the query changes).
@Suite("library search snapshot invalidation") @Suite("library search snapshot invalidation")
@@ -192,9 +193,22 @@ struct LibrarySearchSnapshotTests {
let (model, home) = try makeModelHome() let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Settled\n", home: home) let post = try PostStore.writeNew(body: "# Settled\n", home: home)
try await pollUntil { model.posts.contains { $0.id == post.id } } 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 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) #expect(model.contentRevision == settled)
} }
+2 -2
View File
@@ -18,7 +18,7 @@ struct PolishSeamTests {
/// whitespace-only buffer has none (nil); a buffer with no leading /// whitespace-only buffer has none (nil); a buffer with no leading
/// blanks returns 0. The same walker styles the title line and hops /// blanks returns 0. The same walker styles the title line and hops
/// programmatic carets past the invisible blank fragment. /// programmatic carets past the invisible blank fragment.
@Test func `firstContentLocation skips leading blanks`() { @Test func firstContentLocationSkipsLeadingBlanks() {
let plain = "Title\n\nbody" as NSString let plain = "Title\n\nbody" as NSString
#expect(ProsePresenter.firstContentLocation(plain) == 0) #expect(ProsePresenter.firstContentLocation(plain) == 0)
let blankLead = "\n\n \nTitle\nbody" as NSString 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 /// The ladder keeps the full path, then each shorter variant with one
/// more leading component kept whole; ≤2 components has nothing to /// more leading component kept whole; ≤2 components has nothing to
/// elide. `elide` picks the longest candidate that fits. /// 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 path = "/Users/alex/Library/Mobile Documents/com~apple~CloudDocs/Museion"
let ladder = ElidedPathText.candidates(path) let ladder = ElidedPathText.candidates(path)
#expect(ladder.first == path) #expect(ladder.first == path)
+2 -1
View File
@@ -532,7 +532,8 @@ func readPiece(_ home: URL, root: String, project: String, _ id: String) throws
withIntermediateDirectories: true, 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") #expect(PostStore.availableSlug(for: "한국", home: home) == "한국-2")
} }
@@ -44,14 +44,17 @@ struct ProfileProvisionerFailureTests {
func configUntouched() -> Bool { func configUntouched() -> Bool {
(try? String(contentsOfFile: configPath, encoding: .utf8)) == config (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. // Failed pass: registration never reached, config untouched.
let failed = ProfileProvisioner.perform( let failed = pass(badPayload)
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: badPayload,
masterRoot: master,
)
guard case .failed = failed else { guard case .failed = failed else {
Issue.record("expected copy failure, got \(failed)") Issue.record("expected copy failure, got \(failed)")
return return
@@ -61,13 +64,7 @@ struct ProfileProvisionerFailureTests {
// Skipped pass: nil serverBinaryPath is the test seam — nothing // Skipped pass: nil serverBinaryPath is the test seam — nothing
// registers, config untouched. (The failed pass already seeded the // registers, config untouched. (The failed pass already seeded the
// shared master — 2 present there, only the 6 profile links copy.) // shared master — 2 present there, only the 6 profile links copy.)
let skipped = ProfileProvisioner.perform( let skipped = pass(goodPayload, server: nil)
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: goodPayload,
masterRoot: master,
serverBinaryPath: nil,
)
#expect(skipped == .seeded(copied: 6, present: 2)) #expect(skipped == .seeded(copied: 6, present: 2))
#expect(configUntouched()) #expect(configUntouched())
for profile in ["museion", "museion-pass1", "museion-pass2"] { for profile in ["museion", "museion-pass1", "museion-pass2"] {
@@ -77,13 +74,7 @@ struct ProfileProvisionerFailureTests {
// Registering pass: the CLI rail ran (markers + invocations per // Registering pass: the CLI rail ran (markers + invocations per
// profile) and still not one byte of config.yaml is written by the // profile) and still not one byte of config.yaml is written by the
// provisioner — the entry lands through the CLI, or not at all. // provisioner — the entry lands through the CLI, or not at all.
let registered = ProfileProvisioner.perform( let registered = pass(goodPayload, server: "/fake/Museion.app/Contents/MacOS/Museion")
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: goodPayload,
masterRoot: master,
serverBinaryPath: "/fake/Museion.app/Contents/MacOS/Museion",
)
#expect(registered == .seeded(copied: 0, present: 8)) #expect(registered == .seeded(copied: 0, present: 8))
#expect(configUntouched()) #expect(configUntouched())
#expect(FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-registered-museion"))) #expect(FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-registered-museion")))
+64 -32
View File
@@ -44,8 +44,8 @@ struct SeedSkill {
/// and `config unset <key>` (argv log `<binaryDir>/config-unset-<profile>`, /// and `config unset <key>` (argv log `<binaryDir>/config-unset-<profile>`,
/// store line removed, "✓ Unset …"; unset-when-absent = the not-set line, /// store line removed, "✓ Unset …"; unset-when-absent = the not-set line,
/// exit 1) — the live-probed wire shapes HermesSettingsWriter pins. /// exit 1) — the live-probed wire shapes HermesSettingsWriter pins.
// #136: the config rail (set/get/unset over the config-store map) — its /// #136: the config rail (set/get/unset over the config-store map) — its
// own literal so makeFakeHermes stays under its function-body ceiling. /// own literal so makeFakeHermes stays under its function-body ceiling.
private func fakeHermesConfigCLI() -> String { private func fakeHermesConfigCLI() -> String {
""" """
if [[ "$1" == "-p" && "$3" == "config" && "$4" == "set" ]]; then 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 <name>` 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 <profile>` global flag
/// (#23, #134): `mcp list` prints "museion-tools" iff
/// `<binaryDir>/mcp-registered-<profile>` 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 `<binaryDir>/mcp-add-invocation-<profile>`, drops the
/// per-profile marker, prints "Saved 'museion-tools' to …" (verified wire
/// strings). `config set <key> <value> [--force]` appends the exact argv to
/// `<binaryDir>/config-set-<profile>` and prints the verified "✓ Set …"
/// line. `<binaryDir>/mcp-add-fails` / `config-set-fails` / `config-unset-fails`
/// force the matching failure. Every `profile create` name appends to
/// `<binaryDir>/profile-create-log`.
/// #136: `config set` also records KEY=VALUE into
/// `<binaryDir>/config-store-<profile>` (dedup per key), and the fake speaks
/// `config get <key>` (store value, or the not-set line on stderr exit 1)
/// and `config unset <key>` (argv log `<binaryDir>/config-unset-<profile>`,
/// 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 { func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> String {
let path = (dir as NSString).appendingPathComponent(name) let path = (dir as NSString).appendingPathComponent(name)
let createBlock = switch mode { 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" print -r -- "$NAME" >> "${0:h}/profile-create-log"
\(createBlock) \(createBlock)
fi fi
if [[ "$1" == "-p" && "$3" == "mcp" ]]; then \(fakeHermesMcpCLI())
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
\(fakeHermesConfigCLI()) \(fakeHermesConfigCLI())
exit 97 exit 97
""" """
+2 -1
View File
@@ -343,7 +343,8 @@ struct ProfileSurfaceTests {
) )
#expect(outcome == .seeded(copied: 8, present: 0)) #expect(outcome == .seeded(copied: 8, present: 0))
for profile in ProfileSurface.allCases { 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))
} }
} }
+5 -1
View File
@@ -58,7 +58,11 @@ struct ProsePresenterTests {
// sample at the heading TEXT, not offset 0 (the dimmed marker) // 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 let h1 = attributed.attribute(.font, at: ns.range(of: "H1").location, effectiveRange: nil) as? NSFont
#expect(h1?.pointSize == 30) #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 let h2 = attributed.attribute(.font, at: ns.range(of: "H2").location, effectiveRange: nil) as? NSFont
#expect(h2?.pointSize == 22) #expect(h2?.pointSize == 22)
let h3 = attributed.attribute(.font, at: ns.range(of: "H3").location, effectiveRange: nil) as? NSFont let h3 = attributed.attribute(.font, at: ns.range(of: "H3").location, effectiveRange: nil) as? NSFont
+2 -1
View File
@@ -27,7 +27,8 @@ struct ReadingPresenterTests {
@Test @Test
func `stamper rewrites attributes`() { func `stamper rewrites attributes`() {
let html = "<h1>T</h1>\n<!--S:1-->\n<p>A</p>\n<!--S:12-->\n<ul>\n<li>B</li>\n</ul>" let html = "<h1>T</h1>\n<!--S:1-->\n<p>A</p>\n<!--S:12-->\n<ul>\n<li>B</li>\n</ul>"
#expect(ReadingPresenter.stampHTML(html) == "<h1>T</h1>\n<p data-source-line=\"1\">A</p>\n<ul data-source-line=\"12\">\n<li>B</li>\n</ul>") let expected = "<h1>T</h1>\n<p data-source-line=\"1\">A</p>\n<ul data-source-line=\"12\">\n<li>B</li>\n</ul>"
#expect(ReadingPresenter.stampHTML(html) == expected)
} }
/// The #68 click→edit map: blocks are monotonic, lines are 1-based, and /// The #68 click→edit map: blocks are monotonic, lines are 1-based, and
@@ -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*
+1
View File
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index --> <!-- write-log: full-index -->
| Date | Type | File | Summary | | 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-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-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 | | 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 |
+8 -2
View File
@@ -240,7 +240,11 @@ struct MockWorkspace: View {
} }
private var previewText: String { 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 { switch model.phase {
case .checking: "Running hermes acp --check." case .checking: "Running hermes acp --check."
case .passed: "Hermes \(model.version) answered the health check. The mentor is available." 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."
} }
} }
} }
+7 -8
View File
@@ -5,8 +5,8 @@
# 1. no push while a full-test run is live — concurrent load flakes the # 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; # 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 # 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 # violations there (settled #190 design: the gate guards what the
# repo-wide gate could never clear); # push itself carries, not the whole tree);
# 3. autofix guard — a lint autofix pass that rewrites files AFTER # 3. autofix guard — a lint autofix pass that rewrites files AFTER
# verification must not ride the push untested: the push fails, the # verification must not ride the push untested: the push fails, the
# rewrite gets reviewed and re-verified via scripts/full-test.sh. # rewrite gets reviewed and re-verified via scripts/full-test.sh.
@@ -44,11 +44,10 @@ if [[ -n $live ]]; then
exit 1 exit 1
fi fi
# 2. Lint gate, scoped to THIS PUSH's Swift files (#190): the repo tree # 2. Lint gate, scoped to THIS PUSH's Swift files (#190): the gate guards
# carries pre-existing swiftlint findings (warning noise repo-wide, # what the push itself carries — settled #190 design, kept even now
# error-severity in spike/ experiments and one tests file) — a bare # that bare `swiftlint .` runs green repo-wide (#195/#196 cleared the
# `swiftlint .` gate can never pass here and would block every push. # last findings). No Swift in the push → nothing to gate.
# The gate is the push's own files; no Swift in the push → nothing to gate.
before="$(git status --porcelain)" before="$(git status --porcelain)"
zero=0000000000000000000000000000000000000000 zero=0000000000000000000000000000000000000000
# Default-branch base for NEW-ref scoping: the project's default branch at # 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 [[ "$lsha" == "$zero" ]] && continue # ref deletion — no content to lint
if [[ "$rsha" == "$zero" ]]; then if [[ "$rsha" == "$zero" ]]; then
# NEW ref: lint the delta against the default branch, never the whole # 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 FAILS CLOSED — a silent skip is a vacuous pass (#31/#134 class).
base="$(git merge-base "$lsha" "$default_ref" 2>/dev/null || true)" base="$(git merge-base "$lsha" "$default_ref" 2>/dev/null || true)"
[[ -n "$base" ]] || { [[ -n "$base" ]] || {