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

+10 -3
View File
@@ -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)
}
}
+6 -2
View File
@@ -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.
}
+60 -44
View File
@@ -55,10 +55,7 @@ nonisolated enum OutlinePresenter {
_ nodes: [OutlineNode], folded: Set<UUID>, 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).
+1 -3
View File
@@ -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
}
+37 -26
View File
@@ -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
+1 -4
View File
@@ -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
}
+177 -102
View File
@@ -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<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) {
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<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 {
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<Int>], _ span: Range<Int>) -> Bool {
guard !claimed.contains(where: { $0.overlaps(span) }) else { return false }
claimed.append(span)
return true
}
func dim(_ utf16: Range<Int>) {
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<Int>) {
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]) {
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<Int>, _ 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<Int>],
) {
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<Int>],
) {
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<Int>],
) {
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] {
+4 -2
View File
@@ -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
+3 -2
View File
@@ -104,7 +104,7 @@ nonisolated enum ReadingPresenter {
// swiftlint:disable:next force_try
let regex = try! NSRegularExpression(pattern: #"<!--S:(\d+)-->\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 {
"<!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 {
+8 -3
View File
@@ -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
}
+6 -3
View File
@@ -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)
+10 -3
View File
@@ -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