// // DeslopLint.swift // Museion // // #6 (PRD S3.4): the native deslop lint — the SAME deterministic findings // the engine's deslop skill doctrine defines (banned-vocab tiers + em-dash // density), computed in Swift at pass invocation. No engine round-trip: // the same invocation posture as the #31 stats capture — pure Foundation, // deterministic, and a failed lint never blocks the pass. Findings land // as real fix cards (emitter `lint`, ADR-0006) through FixCardStore; the // GLOSSARY emitter contract keeps the engine from re-carding a live lint // finding, which is why emit() dedups against OPEN cards before submit. // // Data: `Resources/deslop-lint.json` is the bundled default, mirroring // the deslop SKILL.md tier doctrine verbatim (owner-facing — copy // exactly, never regenerate). `key`, `landscape`, `highlight`, and bare // `underscore` are deliberately omitted from the tiers: POS-ambiguous // (a regex can't tell the noun `key` from the adjective) and the phrase // `underscore` collides with the character name. A writer who wants // them adds them via `/deslop-lint.json` — the Home override wins // whenever it exists AND decodes (trivially editable without a recompile). // import Foundation /// #6 (S3.4): the native deslop lint. nonisolated like FixCardStore — /// pure compute plus one disk-touching emit the pass flow calls. nonisolated enum DeslopLint { /// The lint's editable data shape (`deslop-lint.json`, camelCase keys). struct Config: Codable, Equatable { struct Tier: Codable, Equatable { struct Phrase: Codable, Equatable { var phrase: String /// The plain word a mechanical-lane card can Apply directly; /// nil = demonstration (the rewrite needs judgment). var replacement: String? } var name: String var note: String /// How many occurrences this tier tolerates (0 = never; /// 1 = suspicious in density). var maxAllowed: Int var phrases: [Phrase] } var tiers: [Tier] var emDashBudget: Int } /// One deterministic finding — the card body before it becomes a card. /// (No `count` field: the occurrence count lives verbatim in the /// owner-facing `problem` string — "Appears 2×" — audit-deleted as /// write-only.) struct Finding: Equatable { var pattern: String var problem: String var diagnosticQuestion: String var fix: String var lane: FixCardStore.StoredFixCard.Lane var anchor: FixCardStore.StoredFixCard.Anchor } /// Created per access; no non-Sendable statics (repo convention, /// FixCardStore.codec). The config JSON is camelCase — a plain decoder. private static var decoder: JSONDecoder { JSONDecoder() } // MARK: - Config /// The bundled doctrine. Missing/undecodable → the no-op config: the /// lint stays silent, never crashes (the stats-capture posture). static func bundledConfig() -> Config { guard let url = Bundle.main.url(forResource: "deslop-lint", withExtension: "json"), let data = try? Data(contentsOf: url), let config = try? decoder.decode(Config.self, from: data) else { return Config(tiers: [], emDashBudget: .max) } return config } /// `/deslop-lint.json` wins when it exists AND decodes; any /// read/decode failure falls back to the bundled default (lenient, /// never fatal). `home: nil` → bundled (test-injectable). // ponytail: no bound on override size or values — a hostile 5000-phrase // override self-freezes the pass (same-privilege local file), a // negative emDashBudget junk-cards dash-free text; reject >500 phrases // / clamp negatives if a hand-edit ever bites. static func config(home: URL?) -> Config { guard let home, let data = try? Data(contentsOf: home.appendingPathComponent("deslop-lint.json")), let override = try? decoder.decode(Config.self, from: data) else { return bundledConfig() } return override } // MARK: - Compute (pure) /// The deterministic findings over `body`: the em-dash density finding /// first when over budget, then each tier's over-allowance phrases /// ordered by first-match position. ONE finding per phrase — never one /// per occurrence. Same body in, same findings out. // ponytail: lints the raw body as given — no fence/heading stripping; // the engine's pass does the context judgment (code fences, quotes) a // table lint can't. Strip contexts if false positives ever bite. static func compute(body: String, config: Config) -> [Finding] { var findings: [Finding] = [] let dashes = body.ranges(of: "—").count if dashes > config.emDashBudget { findings.append(Finding( pattern: "em-dash density", problem: "\(dashes) em-dashes in this piece — the budget is \(config.emDashBudget). " + "Most separation wants a comma or a period; 1-2 earned dashes are plenty. " + "The em-dash habit is the prompt-resistant AI tell.", diagnosticQuestion: "Does this aside need an em-dash, or would a comma or a period carry it?", fix: "", lane: .demonstration, anchor: .init(quote: "—", occurrence: 1), )) } for tier in config.tiers { var ranked: [(position: String.Index, finding: Finding)] = [] for entry in tier.phrases { guard let hit = scan(entry.phrase, in: body), hit.count > tier.maxAllowed else { continue } ranked.append((hit.first.lowerBound, vocabFinding(body: body, tier: tier, entry: entry, hit: hit))) } findings.append(contentsOf: ranked.sorted { $0.position < $1.position }.map(\.finding)) } return findings } /// Case-insensitive whole-word matches of `phrase` in `body`: ICU regex /// `(? (first: Range, count: Int)? { // Trust boundary (a hand-edited override): an empty or // whitespace-only phrase (submit's validation TRIMS) would match // everywhere, build a junk anchor, and fail submit's whole-call // validation — silently killing the entire lint. guard !phrase.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil } let pattern = "(?i)(?, count: Int), ) -> Finding { let quote = String(body[hit.first]) let fix = entry.replacement.map { replacement -> String in guard let quoteFirst = quote.first, quoteFirst.isUppercase, let fixFirst = replacement.first else { return replacement } return fixFirst.uppercased() + replacement.dropFirst() } ?? "" return Finding( pattern: entry.phrase, problem: "\(tier.name) AI vocabulary — \(tier.note). Appears \(hit.count)× in this piece. " + "Replace with the plain word.", diagnosticQuestion: "What plain word says this instead?", fix: fix, lane: entry.replacement == nil ? .demonstration : .mechanical, anchor: .init( quote: quote, occurrence: (body.ranges(of: quote).firstIndex(of: hit.first) ?? 0) + 1, ), ) } // MARK: - Emit /// Load config, compute, dedup, submit — the pass-flow hook (#6). /// Swallows every error: a failed lint must never fail the pass (the /// `captureFirstDraftStats` posture). `pieceURL` is the piece's /// post.md URL (already flushed at the call site). static func emit(body: String, pieceID: String, pieceURL: URL, kind: PassKind, home: URL?) { let findings = compute(body: body, config: config(home: home)) guard !findings.isEmpty else { return } // Dedup BEFORE submit: an OPEN card with the same pattern AND // anchor already covers the finding. Closed cards (applied/ // skipped/done) do NOT block — a still-present finding after the // writer closed a card re-emits (re-runs make progress). let open = FixCardStore.scan(pieceURL: pieceURL) .filter { $0.status == .open } let inputs = findings.compactMap { finding -> FixCardStore.Input? in let duplicate = open.contains { $0.pattern == finding.pattern && $0.anchor.quote == finding.anchor.quote && $0.anchor.occurrence == finding.anchor.occurrence } guard !duplicate else { return nil } return FixCardStore.Input( pattern: finding.pattern, problem: finding.problem, diagnosticQuestion: finding.diagnosticQuestion, fix: finding.fix, anchor: finding.anchor, lane: finding.lane, emitter: .lint, provenance: .init(piece: pieceID, date: nil, engine: nil, pass: kind == .pass1 ? 1 : 2), ) } guard !inputs.isEmpty else { return } // submit validates anchors against post.md on disk, stamps // id/date/rank, enforces the 10-card ceiling (the ranked head // survives), and writes the JSON files. Any failure → silence. try? FixCardStore.submit(piecePath: pieceURL.path, cards: inputs) } }