Cotton code
576 lines · 25.6 KB · SwiftRaw
// A Swift screen's argument names, held against the crate's own tool catalogue.//// THE GAP THIS CLOSES. A write from a screen is two stringly-typed halves with// no compiler between them: Swift sends `writer.run("update_project", ["id": …])`// and Rust reads a JSON object against an `input_schema` that is// `additionalProperties: false` on every tool. A name the tool does not take is// a refusal or a silent wrong act at runtime, and NOTHING in this tree saw it —// `ScreenWriterTests` is about the invalidation decision and drives one fake tool// name through `ScriptedCore`, so it cannot. Ten call sites shipped with wrong// names before this guard existed: creating a project, archiving one, restoring// one, keeping a memory entry, pinning one, restoring a dropped one and// un-filing any record were all dead on arrival.//// The repo already knows this shape: `RouteTableTests` reads `routes.rs` by// path and `ProjectFactsTests` reads `constants.rs`. The catalogue is in the// same repo. This is the reader it was missing.//// WHAT THE SWEEP CAN AND CANNOT REACH — the floor is a floor, and the next// reader should know where it stops://   • Reached: a call spelled `run(…)`, `answering(…)` or one carrying a//     `tool:` argument label, whose FIRST argument is a string literal SHAPED//     LIKE A TOOL NAME (snake_case — see `isToolNameShaped`, which keeps a//     screen's own private `run` helper out without letting a misspelled tool//     name through), and//     whose arguments are an inline dictionary literal — including one wrapped//     in `.object(…)`, and including a literal merged onto a variable//     (`args.merging(["restore": …])`), where the merged names are checked//     against the schema but `required` is not, since the variable half may//     carry it.//   • NOT reached: a dictionary built up in a variable (`var args: [...]`,//     then `args["note"] = …`) — the tool name is still checked, the argument//     names are not, and every such site is NAMED by//     `testTheSweepSaysWhatItCouldNotReach` rather than passed over in//     silence. Also not reached: a tool name held in a variable//     (`run(tool, args)` — the local forwarder's own body, whose CALLERS are//     swept), and any future forwarder not spelled `run` or `answering`.//// Path ownership (rule (b) of AGENTS.md's by-path guard rule): the catalogue// lives at `crates/cotton-tools/src/mcp/catalogue.rs` and is the RUST TOOLS// lane's — ordinary source since step 5i (it was generated from the TypeScript// server's protocol until the flip deleted that package). Grep that path// repo-wide (test directories and every open worktree included) before moving// it. `SourceSweep.mustRead` makes a read that finds nothing fail loudly, with// the path in the message, before any comparison runs.import Foundationimport XCTest// MARK: - The catalogue, as data/// One tool's `input_schema`, reduced to the two things a caller can get wrong.struct ToolSchema {    let properties: Set<String>    let required: [String]}enum ToolCatalogue {    static let path = "crates/cotton-tools/src/mcp/catalogue.rs"    /// Every `ToolDef`'s `name` → its `input_schema`, parsed as JSON.    ///    /// The generated file writes each schema on ONE line as a Rust raw string,    /// and escalates the hash count (`r#"…"#` → `r##"…"##`) when the JSON    /// itself contains `"#` — `update_project` is the one that does today, and    /// a reader that only knew `r#"` silently lost it.    static func schemas(in text: String) -> [String: ToolSchema] {        var out: [String: ToolSchema] = [:]        var pending: String?        for rawLine in text.split(separator: "\n", omittingEmptySubsequences: false) {            let line = rawLine.trimmingCharacters(in: .whitespaces)            if line.hasPrefix("name: \""), line.hasSuffix("\","), line.count > 9 {                pending = String(line.dropFirst(7).dropLast(2))                continue            }            guard line.hasPrefix("input_schema: r"), let name = pending else { continue }            var body = String(line.dropFirst("input_schema: r".count))            var hashes = ""            while body.hasPrefix("#") {                hashes.append("#")                body.removeFirst()            }            guard body.hasPrefix("\"") else { continue }            body.removeFirst()            let tail = "\"" + hashes + ","            guard body.hasSuffix(tail) else { continue }            body.removeLast(tail.count)            if let schema = parse(body) {                out[name] = schema            }            pending = nil        }        return out    }    private static func parse(_ json: String) -> ToolSchema? {        guard let data = json.data(using: .utf8) else { return nil }        guard let any = try? JSONSerialization.jsonObject(with: data) else { return nil }        guard let object = any as? [String: Any] else { return nil }        let properties = (object["properties"] as? [String: Any]).map { Set($0.keys) } ?? []        let required = (object["required"] as? [String]) ?? []        return ToolSchema(properties: properties, required: required)    }}// MARK: - The call sites, out of the Swift/// One `run(tool, args)`-shaped call, as the sweep could read it.struct ToolCallSite {    let file: String    let line: Int    let tool: String    /// `nil` when the arguments are not an inline literal.    let argumentNames: [String]?    /// The literal IS the whole argument, so `required` can be checked too.    let argumentsAreWhole: Bool}enum ToolCallSweep {    /// Every comment character replaced by a space, newlines kept.    ///    /// `SourceSweep.withoutComments` answers "does this pattern appear in the    /// code", which is all its three callers need. This guard reports a LINE    /// NUMBER, so it needs the offsets to survive: a comment that quotes a tool    /// name (`ReadSource::Tool("list_projects")` in `DockVocabulary.swift`)    /// must not read as a call site, and the call sites that remain must still    /// be where the file says they are.    static func blankingComments(_ text: String) -> [Character] {        var out: [Character] = []        out.reserveCapacity(text.count)        let chars = Array(text)        var i = 0        while i < chars.count {            let ch = chars[i]            let next = i + 1 < chars.count ? chars[i + 1] : nil            if ch == "\"" {                let end = endOfString(chars, from: i)                out.append(contentsOf: chars[i..<end])                i = end                continue            }            if ch == "/", next == "/" {                while i < chars.count, chars[i] != "\n" {                    out.append(" ")                    i += 1                }                continue            }            if ch == "/", next == "*" {                var depth = 0                while i < chars.count {                    if chars[i] == "/", i + 1 < chars.count, chars[i + 1] == "*" {                        depth += 1                        out.append(" ")                        out.append(" ")                        i += 2                        continue                    }                    if chars[i] == "*", i + 1 < chars.count, chars[i + 1] == "/" {                        depth -= 1                        out.append(" ")                        out.append(" ")                        i += 2                        if depth == 0 { break }                        continue                    }                    out.append(chars[i] == "\n" ? "\n" : " ")                    i += 1                }                continue            }            out.append(ch)            i += 1        }        return out    }    private static func isIdent(_ ch: Character) -> Bool {        ch == "_" || ch.isLetter || ch.isNumber    }    /// `chars[start] == "\""`; the index just past the closing quote.    private static func endOfString(_ chars: [Character], from start: Int) -> Int {        var i = start + 1        while i < chars.count {            if chars[i] == "\\" {                i += 2                continue            }            if chars[i] == "\"" { return i + 1 }            i += 1        }        return chars.count    }    /// `chars[start] == open`; the index just past the matching close.    private static func matchingBracket(        _ chars: [Character], from start: Int, open: Character, close: Character    ) -> Int? {        var depth = 0        var i = start        while i < chars.count {            let ch = chars[i]            if ch == "\"" {                i = endOfString(chars, from: i)                continue            }            if ch == open {                depth += 1            } else if ch == close {                depth -= 1                if depth == 0 { return i + 1 }            }            i += 1        }        return nil    }    private static func skipSpace(_ chars: [Character], _ i: Int, end: Int) -> Int {        var j = i        while j < end, chars[j] == " " || chars[j] == "\n" || chars[j] == "\t" { j += 1 }        return j    }    /// Steps over `label:` when one is there. Whitespace is skipped either way    /// — a call written across several lines starts with a newline, and a    /// reader that only skipped space when it found a label would see one.    private static func skipLabel(_ chars: [Character], _ i: Int, end: Int) -> Int {        let afterSpace = skipSpace(chars, i, end: end)        var j = afterSpace        while j < end, isIdent(chars[j]) { j += 1 }        guard j > afterSpace else { return afterSpace }        let afterIdent = skipSpace(chars, j, end: end)        guard afterIdent < end, chars[afterIdent] == ":" else { return afterSpace }        return skipSpace(chars, afterIdent + 1, end: end)    }    /// The keys of a Swift dictionary literal, at its TOP level only — a string    /// inside `.string("archived")` or a nested `.object([…])` is a value, not    /// an argument name.    static func topLevelKeys(_ chars: [Character], from start: Int, to end: Int) -> [String] {        var keys: [String] = []        var brackets = 0        var parens = 0        var i = start        while i < end {            let ch = chars[i]            if ch == "\"" {                let close = endOfString(chars, from: i)                let literal = String(chars[(i + 1)..<max(i + 1, close - 1)])                var k = close                while k < end, chars[k] == " " || chars[k] == "\n" || chars[k] == "\t" { k += 1 }                if brackets == 1, parens == 0, k < end, chars[k] == ":" {                    keys.append(literal)                }                i = close                continue            }            switch ch {            case "[": brackets += 1            case "]": brackets -= 1            case "(": parens += 1            case ")": parens -= 1            default: break            }            i += 1        }        return keys    }    /// Where a call's `(` sits, for every call this sweep knows how to read.    private static func callOpenings(_ chars: [Character]) -> [Int] {        var found: Set<Int> = []        var i = 0        while i < chars.count {            guard isIdent(chars[i]), i == 0 || !isIdent(chars[i - 1]) else {                i += 1                continue            }            let start = i            while i < chars.count, isIdent(chars[i]) { i += 1 }            let word = String(chars[start..<i])            let after = skipSpace(chars, i, end: chars.count)            if word == "run" || word == "answering" {                if after < chars.count, chars[after] == "(" { found.insert(after) }            } else if word == "tool" {                // `WriteRequest(tool: "update_album", args: …)` — the label                // form, which is how several screens spell a write. Any                // callee is read, so a new wrapper is swept without being                // listed here; a function that takes a tool's KEY (`bin`,                // `todos`) therefore spells its label otherwise                // (`HomeTiles.view(ofTool:)`).                if after < chars.count, chars[after] == ":" {                    var back = start - 1                    while back >= 0, chars[back] == " " || chars[back] == "\n" || chars[back] == "\t" {                        back -= 1                    }                    if back >= 0, chars[back] == "(" { found.insert(back) }                }            }        }        return found.sorted()    }    /// A tool name is snake_case and nothing else — the catalogue is generated    /// and every name in it has this shape. The check is here rather than at    /// the catalogue lookup ON PURPOSE: a MISSPELLED tool name is still    /// snake_case (`update_pge`), so it reaches the lookup and fails there,    /// which is the whole point of this guard. What this rejects is a call that    /// was never a tool call — `run` is not a reserved word, and a screen may    /// have a local helper of that name. The retired Themes screen had exactly    /// one: `run(_ text: String, _ font: Font, …)` building an    /// `AttributedString`, whose `run(", ", body, ink)` this sweep read as a    /// tool named `, ` until the two lanes met.    static func isToolNameShaped(_ name: String) -> Bool {        guard let first = name.first, first.isLowercase, first.isLetter else { return false }        return name.allSatisfy { ($0.isLetter && $0.isLowercase) || $0.isNumber || $0 == "_" }    }    /// Reads one call. `nil` when the first argument is not a string literal,    /// which is the `run(tool, args)` forwarder and its own declaration.    static func read(_ chars: [Character], at openParen: Int, file: String) -> ToolCallSite? {        guard let close = matchingBracket(chars, from: openParen, open: "(", close: ")") else {            return nil        }        let innerStart = openParen + 1        let innerEnd = close - 1        var i = skipLabel(chars, innerStart, end: innerEnd)        guard i < innerEnd, chars[i] == "\"" else { return nil }        let nameEnd = endOfString(chars, from: i)        let tool = String(chars[(i + 1)..<max(i + 1, nameEnd - 1)])        guard isToolNameShaped(tool) else { return nil }        var line = 1        for index in 0..<openParen where chars[index] == "\n" { line += 1 }        i = skipSpace(chars, nameEnd, end: innerEnd)        guard i < innerEnd, chars[i] == "," else {            // No arguments at all — every `required` name is missing.            return ToolCallSite(                file: file, line: line, tool: tool, argumentNames: [], argumentsAreWhole: true            )        }        var second = skipLabel(chars, i + 1, end: innerEnd)        second = skipSpace(chars, second, end: innerEnd)        // `.object([…])` is the same literal wearing a wrapper.        let wrapper = ".object("        if second + wrapper.count < innerEnd,            String(chars[second..<(second + wrapper.count)]) == wrapper        {            second = skipSpace(chars, second + wrapper.count, end: innerEnd)        }        let startsWithLiteral = second < innerEnd && chars[second] == "["        var bracket = startsWithLiteral ? second : -1        if bracket < 0 {            var j = second            while j < innerEnd, chars[j] != "[" { j += 1 }            bracket = j < innerEnd ? j : -1        }        guard bracket >= 0,            let bracketEnd = matchingBracket(chars, from: bracket, open: "[", close: "]"),            bracketEnd <= innerEnd + 1        else {            return ToolCallSite(                file: file, line: line, tool: tool, argumentNames: nil, argumentsAreWhole: false            )        }        let keys = topLevelKeys(chars, from: bracket, to: bracketEnd)        // `whole` only when the literal really is the argument: what follows it        // is the wrapper's `)`, a comma to the next argument, or nothing.        var trailing = skipSpace(chars, bracketEnd, end: innerEnd)        while trailing < innerEnd, chars[trailing] == ")" {            trailing = skipSpace(chars, trailing + 1, end: innerEnd)        }        let whole =            startsWithLiteral && (trailing >= innerEnd || chars[trailing] == ",")        return ToolCallSite(            file: file, line: line, tool: tool, argumentNames: keys, argumentsAreWhole: whole        )    }    /// Every call site in one file's text.    static func sites(in text: String, file: String) -> [ToolCallSite] {        let chars = blankingComments(text)        return callOpenings(chars).compactMap { read(chars, at: $0, file: file) }    }}// MARK: - The guardfinal class CatalogueGuardTests: XCTestCase {    private func catalogue() throws -> [String: ToolSchema] {        let text = try SourceSweep.mustRead(            ToolCatalogue.path,            ownedBy: "Rust tools"        )        let schemas = ToolCatalogue.schemas(in: text)        // Rule (a) again, one level down: `mustRead` proves the FILE is there;        // this proves the file still SAYS what the parser reads. A generated        // file that changed shape would otherwise leave every check below        // passing over an empty dictionary.        XCTAssertGreaterThan(            schemas.count,            150,            """            parsed \(schemas.count) tool schemas out of \(ToolCatalogue.path) — \            the catalogue holds ~200 and this reader is looking for lines of the \            form `name: "x",` followed by `input_schema: r#"{…}"#,`. Did the \            generator change shape?            """        )        // No compatibility names (owner decision, 3 Oct 2026): a retired tool        // name is deleted, never kept resolving to its verb, so a screen that        // still calls one fails below as an unknown tool.        XCTAssertFalse(text.contains("TOOL_ALIASES"), "the catalogue keeps no retired tool names")        return schemas    }    private func allSites() throws -> [ToolCallSite] {        try AppSources.all().flatMap { ToolCallSweep.sites(in: $0.text, file: $0.name) }    }    /// The parser reads the catalogue as the crate means it.    func testTheCatalogueReadsBackAsSchemas() throws {        let schemas = try catalogue()        // Three tools whose shape this lane got wrong, spelled out so a parser        // that started answering empty sets goes red here rather than passing        // every call site below.        XCTAssertEqual(Set(schemas["create_project"]?.required ?? []), ["slug", "name"])        XCTAssertEqual(Set(schemas["archive_note"]?.required ?? []), ["id"])        XCTAssertTrue(schemas["memory_archive"]?.properties.contains("reason") == true)        XCTAssertFalse(schemas["memory_archive"]?.properties.contains("decision") == true)        // `update_project` is the one schema written as `r##"…"##`, because its        // description contains `"#`. A reader that only knew `r#"` lost it.        XCTAssertTrue(schemas["update_project"]?.properties.contains("slug") == true)    }    /// **The guard.** Every argument name a screen sends is a property of the    /// tool it names, and every `required` name is sent.    func testEverySwiftToolCallMatchesTheToolsSchema() throws {        let schemas = try catalogue()        var problems: [String] = []        for site in try allSites() {            let canonical = site.tool            guard let schema = schemas[canonical] else {                problems.append(                    "\(site.file):\(site.line) — no tool named `\(site.tool)` in the catalogue"                )                continue            }            guard let names = site.argumentNames else { continue }            for name in names where !schema.properties.contains(name) {                problems.append(                    """                    \(site.file):\(site.line) — `\(site.tool)` has no argument `\(name)`. \                    It takes \(schema.properties.sorted()). Every input_schema is \                    additionalProperties:false, so this is a refusal or a silent wrong act.                    """                )            }            guard site.argumentsAreWhole else { continue }            for name in schema.required where !names.contains(name) {                problems.append(                    """                    \(site.file):\(site.line) — `\(site.tool)` requires `\(name)` and the call \                    does not send it.                    """                )            }        }        XCTAssertTrue(            problems.isEmpty,            "the Swift addresses a tool with names it does not take:\n" + problems.joined(separator: "\n")        )    }    /// Anti-vacuity: a parser that silently matched nothing would make the    /// guard above thirty assertions over an empty list.    // RULE: Retired-surface and fixed call-count pins are deleted under the owner's test policy.    /// The other half of anti-vacuity, and the reason this test can be trusted:    /// the matcher fires on the four ways a call goes wrong. Written against a    /// synthetic source rather than a real screen, so it keeps saying what it    /// says after the ten real call sites are fixed.    func testTheMatcherCatchesEveryWayACallGoesWrong() throws {        let schemas = try catalogue()        let sample = """            // writer.run("complete_todo", ["todoId": .string(id)]) in a comment is not a call            func broken() async {                await writer.run("complete_todo", ["todoId": .string(id)])                await writer.run("archive_page", ["read": .bool(true)])                await writer.run("update_pge", ["id": .string(id)])                await writer.run("memory_archive", args.merging(["restore": .bool(true)]) { $1 })                await writer.run(                    "complete_todo",                    ["id": .string(id)]                )                run("memory_update", ["id": .string(id), "machine": .null], say: nil)                _ = WriteRequest(                    tool: "star_message",                    args: .object(["messageId": .string(m), "starred": .bool(true)])                )                _ = topic.text("brief")                // A local helper that happens to be called `run`. Not a tool                // call, and no lane should have to rename a private function to                // keep this sweep quiet.                out += run(", ", body, ink)                out += run(".", body, ink)            }            """        let sites = ToolCallSweep.sites(in: sample, file: "Sample.swift")        XCTAssertEqual(            sites.count,            7,            """            the comment, `topic.text("brief")` and the two `run(", "…)` \            `AttributedString` helpers are not call sites, and the multi-line \            call, the local `run(_:_:say:)` forwarder and the \            `WriteRequest(tool:args:)` label form all are — read \(sites.map { $0.tool })            """        )        var problems: [String] = []        for site in sites {            let canonical = site.tool            guard let schema = schemas[canonical] else {                problems.append("unknown:\(site.tool)")                continue            }            guard let names = site.argumentNames else { continue }            for name in names where !schema.properties.contains(name) {                problems.append("extra:\(site.tool).\(name)")            }            guard site.argumentsAreWhole else { continue }            for name in schema.required where !names.contains(name) {                problems.append("missing:\(site.tool).\(name)")            }        }        XCTAssertTrue(problems.contains("extra:complete_todo.todoId"), "\(problems)")        XCTAssertTrue(problems.contains("missing:complete_todo.id"), "\(problems)")        XCTAssertTrue(problems.contains("extra:archive_page.read"), "\(problems)")        XCTAssertTrue(problems.contains("missing:archive_page.id"), "\(problems)")        XCTAssertTrue(problems.contains("unknown:update_pge"), "\(problems)")        // A literal merged onto a variable: the names ARE sent, so they are        // checked — but `required` is not, because the variable half may carry it.        XCTAssertTrue(problems.contains("extra:memory_archive.restore"), "\(problems)")        XCTAssertFalse(problems.contains("missing:memory_archive.id"), "\(problems)")        // And the three correct calls — one written across several lines, one        // through the local forwarder, one through the label form — are silent.        XCTAssertFalse(problems.contains("extra:complete_todo.id"), "\(problems)")        XCTAssertFalse(problems.contains(where: { $0.hasPrefix("extra:memory_update") }), "\(problems)")        XCTAssertFalse(problems.contains(where: { $0.hasSuffix("star_message.messageId") }), "\(problems)")        XCTAssertFalse(problems.contains("missing:star_message.starred"), "\(problems)")    }    /// Comment blanking keeps every offset, which is what makes the line number    /// in a failure message the line number in the file.    func testBlankingCommentsKeepsEveryOffset() {        let source = """            let a = 1  // writer.run("complete_todo", [:])            /* a block               comment */            let b = "// not a comment"            """        let blanked = ToolCallSweep.blankingComments(source)        XCTAssertEqual(blanked.count, Array(source).count)        XCTAssertEqual(            blanked.filter { $0 == "\n" }.count,            Array(source).filter { $0 == "\n" }.count        )        let out = String(blanked)        XCTAssertFalse(out.contains("complete_todo"))        XCTAssertFalse(out.contains("block"))        XCTAssertTrue(out.contains("let b = \"// not a comment\""))    }}