// The project page's section table, and the pure sentences its rows are built // from. // // NOT ported, each with its reason: // // * the section table's router cases — `hrefFor` returning a URL string, the // `render: "count"` sweep, and the reserved-literal check that kept a // section key off `/projects/[slug]/code`. There is no router // precedence here: a destination is a `Route` case the compiler already // holds total. The three page sections that are not link groups // (Sessions, Briefing, Brand) are held against the crate's own // `project_page` instead, below. // * `projectMemories` and `newestProjectSessions` — neither is in // `ProjectFacts`. The crate answers `linked.memory` already // in the project's own arrangement, and a project's sessions are the // session log's read, not this page's. // * `projectOrder`'s "parses the instant rather than comparing it as a // string" — `ProjectFacts.order` compares `lastActivity` as TEXT, which is // chronological only because every stamp the crate answers is written in // one UTC form. An offset-bearing stamp would sort wrong, so the case is // left out rather than pinned green; what IS pinned is that an absent // or unreadable instant sinks rather than floats. // * the member title's whole journal-date block — the crate's `title_of` // already resolves a journal page to its own date, and this app re-spells // no title it is handed. A phone deciding a fallback the tool has already // decided is the second opinion the rewrite exists to remove. // * the brand kit's "ignores a member that is not a document" — the // narrowing is the crate's now: `brandAssets` is answered as documents // only, so there is no non-document row for `brandSlots` to refuse. // * `brandSlotsFrom`'s "answers all four slots, always" — `brandSlots` // answers only the FILLED roles, and the always-four is `brandRoles`, which // the screen draws from. Held here as a fact about that list. // * the project templates and every render suite — other files' subjects, and // a view tree that died with the old runtime. // // The slug minting IS below: the create sheet mints the slug itself, because // `create_project` requires one and no read or tool on this phone will answer // it. // // Every fixture is synthetic ([nothing-real-ever-goes-in-cotton-s-public-tree]). import CottonKit import Foundation import XCTest @testable import CottonUI final class ProjectFactsTests: XCTestCase { /// Every group `get_project` can key `linked` and `counts` by, READ OUT OF /// THE CRATE'S OWN FILE — the `group` of each arm of `kind_source`, which /// is an exhaustive `match` over `ProjectLinkKind`, so this is the whole /// set and not a sample of it. /// /// By path rather than by hand for the reason its sibling below is: a /// hand-written copy of a crate list is correct on the day it is written /// and silently stale on every day after. Rule (b) of the by-path guard /// rule: `crates/cotton-tools/**` is the Rust tools /// lane's path. Rule (a) is `mustRead`'s — a move fails loudly with the /// path named, before any regex runs. private func crateGroups() throws -> Set { let kinds = try SourceSweep.mustRead( "crates/cotton-tools/src/mcp/handlers/projects/kinds.rs", ownedBy: "the Rust tools lane (get_project's kind table)" ) // The `match` body only: from the tuple that binds `group` to the // `ProjectKindSource` it is packed into. let start = try XCTUnwrap( kinds.range(of: "let (columns, group)"), "kinds.rs no longer binds (columns, group) — the arms cannot be read" ) let rest = kinds[start.upperBound...] let end = try XCTUnwrap( rest.range(of: "ProjectKindSource"), "kinds.rs no longer packs the arms into a ProjectKindSource" ) let body = String(rest[.. JSONValue { var members: [String: JSONValue] = [ "counts": .object(counts.mapValues { JSONValue.number(Double($0)) }), "linked": .object(linked), ] if let brandAssets { members["brandAssets"] = .array(brandAssets) } return .object(members) } private func isScreen(_ section: ProjectSection) -> Bool { if case .screen = section.render { return true } return false } // ── the table is total over the tool ────────────────────────────────── func testTheTodosSectionCountsWhatIsSTILLOPENAndKeepsEveryTodoAMember() { // The owner, on a project reading "120 todos": a figure counting // finished work is a number nobody can act on. Membership is untouched // — the screen behind the row still reaches the done and dropped ones. let page = answer( counts: ["todos": 12], linked: [ "todos": .object([ "openCount": .number(2), "closedCount": .number(10), "open": .array([ .object(["id": .string("t-1"), "title": .string("Order the tiles")]), .object(["id": .string("t-2"), "title": .string("Book the survey")]), ]), ]) ] ) let todos = ProjectSections.named("todos")! XCTAssertEqual(ProjectSections.count(todos, in: page), 2) XCTAssertEqual(ProjectSections.rows(todos, in: page).compactMap { $0.text("id") }, ["t-1", "t-2"]) } func testASectionDrawsTheRowsTheToolAnsweredForItsGroupInTheOrderItAnsweredThem() { // The tool has already sorted each group by recency; re-sorting here // would be a second opinion about an order the reader already has. let page = answer( counts: ["documents": 2], linked: [ "documents": .array([ .object(["id": .string("d-new")]), .object(["id": .string("d-old")]), ]) ] ) let documents = ProjectSections.named("documents")! XCTAssertEqual( ProjectSections.rows(documents, in: page).compactMap { $0.text("id") }, ["d-new", "d-old"] ) // And a section the answer says nothing about draws nothing rather // than refusing to open. let goals = ProjectSections.named("goals")! XCTAssertEqual(ProjectSections.rows(goals, in: page).count, 0) XCTAssertEqual(ProjectSections.count(goals, in: page), 0) } // ── what a row is called ────────────────────────────────────────────── // ── where a row opens ───────────────────────────────────────────────── // ── the order projects read in ──────────────────────────────────────── func testTheProjectTouchedMostRecentlyReadsFirst() { let ordered = ProjectFacts.order([ .object(["id": .string("old"), "lastActivity": .string("2026-08-01T09:00:00.000Z")]), .object(["id": .string("new"), "lastActivity": .string("2026-08-20T09:00:00.000Z")]), ]) XCTAssertEqual(ordered.compactMap { $0.text("id") }, ["new", "old"]) } func testAProjectWithNoActivitySinksToTheBottomAndReadsAlphabeticallyDownThere() { // An archived project has nothing to read. It must FALL, never float // — which is what a comparison treating "unknown" as the largest value // would give. let ordered = ProjectFacts.order([ .object(["id": .string("z"), "name": .string("Zeta")]), .object(["id": .string("a"), "name": .string("Alpha")]), .object([ "id": .string("live"), "name": .string("Live"), "lastActivity": .string("2026-08-20T09:00:00.000Z"), ]), ]) XCTAssertEqual(ordered.compactMap { $0.text("id") }, ["live", "a", "z"]) } func testATieIsBrokenOnTheNameSoTheOrderIsTotal() { // Equal instants must not fall back to whatever order the read // accumulated them in: the same two projects read the same way twice. let at = "2026-08-20T09:00:00.000Z" let rows: [JSONValue] = [ .object(["id": .string("z"), "name": .string("Zeta"), "lastActivity": .string(at)]), .object(["id": .string("a"), "name": .string("Alpha"), "lastActivity": .string(at)]), ] XCTAssertEqual(ProjectFacts.order(rows).compactMap { $0.text("id") }, ["a", "z"]) XCTAssertEqual(ProjectFacts.order(rows.reversed()).compactMap { $0.text("id") }, ["a", "z"]) } // ── the counts line ─────────────────────────────────────────────────── // // GONE, with its subject. `ProjectFacts.countsLine` had no production // call site and no possible one: its only plausible caller is `/projects`, // which reads `list_projects`, whose per-project shape carries no `counts` // at all. Eight assertions over a shape no caller can receive are eight // green assertions about nothing. The per-section noun it used // (`countLabel`) went with the project page's section rows, its last // reader. // ── the slug a new project is born with ─────────────────────────────── // // The same vectors as `crates/cotton-core/src/rules/ // project_slug_tests.rs`, because `create_project` requires a slug and // NOTHING between this sheet and the tool will mint one. Three minters of // one address is three chances for the phone to name a project something // the Mac would not. private func mint(_ name: String, _ already: [String] = []) -> String { ProjectFacts.mintSlug(name, taken: Set(already)) } func testTheSlugIsTheNameInTheColumnsOwnAlphabet() { XCTAssertEqual(mint("Meri Site"), "meri-site") XCTAssertEqual(mint("Meri — the retrofit!!"), "meri-the-retrofit") // A LEADING dash is what the column's CHECK refuses. XCTAssertEqual(mint(" -Meri- "), "meri") XCTAssertEqual(mint("Budget 2027"), "budget-2027") XCTAssertEqual(mint("UPPER_snake.case"), "upper-snake-case") XCTAssertEqual(mint("a-b--c---d"), "a-b-c-d") } func testANameWithNothingAddressableLeftBecomesTheFallback() { // Never an empty address the column would refuse. XCTAssertEqual(mint(""), "project") XCTAssertEqual(mint(" "), "project") XCTAssertEqual(mint("---"), "project") XCTAssertEqual(mint("मेरी"), "project") XCTAssertEqual(mint("日本語"), "project") } func testAUnicodeNameKeepsOnlyItsLatinPartAndIsNeverFolded() { // No unicode folding, deliberately — `Café Meri` is `caf-meri`, not // `cafe-meri`. It is the TypeScript's behaviour and the crate's, and a // minter that "tidied" it would silently change somebody's address. XCTAssertEqual(mint("Café Meri"), "caf-meri") XCTAssertEqual(mint("ÅNGSTRÖM"), "ngstr-m") XCTAssertEqual(mint("final"), "nal") } func testASecondProjectOfTheSameNameGetsTheNextAddressRatherThanARefusal() { // `UNIQUE (workspace_id, slug)` does not read status, so the caller // hands every slug in the workspace — an ARCHIVED one included. XCTAssertEqual(mint("Meri", ["meri"]), "meri-2") XCTAssertEqual(mint("Meri", ["meri", "meri-2"]), "meri-3") XCTAssertEqual(mint("Meri", ["meri", "meri-2", "meri-3"]), "meri-4") XCTAssertEqual(mint("Meri", ["meri-site", "meri"]), "meri-2") } func testTheSuffixStaysInsideTheColumnsSixtyFourCharacterCap() { let long = String(repeating: "a", count: 64) XCTAssertEqual(mint(long, [long]), String(repeating: "a", count: 62) + "-2") // And it keeps the cap while the suffix grows a digit. let head = String(repeating: "a", count: 62) let taken = [long] + (2...9).map { "\(head)-\($0)" } XCTAssertEqual(mint(long, taken), String(repeating: "a", count: 61) + "-10") } func testTheCutNeverLeavesTheAddressEndingOnADash() { // The trailing-dash trim is OURS, not the column's: `meri-` is a legal // slug and a shabby address. Both cuts can land on a separator — the // 64-char one, and the one that leaves space for a suffix. let sixtyThree = String(repeating: "a", count: 63) XCTAssertEqual(mint("\(sixtyThree) retrofit"), sixtyThree) let sixtyTwo = String(repeating: "a", count: 62) let base = mint("\(sixtyTwo) retrofit") XCTAssertEqual(base, "\(sixtyTwo)-r") let next = mint("\(sixtyTwo) retrofit", [base]) XCTAssertEqual(next, "\(sixtyTwo)-2") XCTAssertEqual(next.count, 64) } // ── the brand kit ───────────────────────────────────────────────────── private func asset(_ id: String, note: String?, role: String? = nil) -> JSONValue { var row: [String: JSONValue] = ["id": .string(id), "title": .string("\(id).png")] if let note { row["note"] = .string(note) } if let role { row["role"] = .string(role) } return .object(row) } private var kit: JSONValue { .object([ "colors": .array([ .object(["name": .string("Ink"), "hex": .string("#101314")]), .object(["name": .string("Field"), "hex": .string("#8fd694")]), .object(["name": .string("Paper"), "hex": .string("#faf7f2")]), ]), "fonts": .array([ .object(["role": .string("display"), "family": .string("Fraunces")]), .object(["role": .string("body"), "family": .string("Inter")]), ]), "voice": .string("Plain."), ]) } // ── feedback ────────────────────────────────────────────────────────── // ── the project's conversation, and the threads under it ────────────── func testTheConversationIsTheOneReadProjectNames() { let answer = JSONValue.object([ "conversation": .object(["id": .string("conv-1"), "state": .string("running")]) ]) XCTAssertEqual(ProjectThreads.conversationId(answer), "conv-1") // A project that has none answers nothing, which is what the page says // in one line rather than drawing an empty transcript. XCTAssertNil(ProjectThreads.conversationId(.object([:]))) XCTAssertNil(ProjectThreads.conversationId(.object(["conversation": .null]))) } /// RULE: a conversation that did not start says so on the project page, with the Mac's own sentence. // Found by the Code tool's simulator walk (todo 2aeabe4c): the row was // `failed` with an `error`, and the page went on showing the first // message as "waiting" with nothing saying the conversation never began. func testAFailedConversationSaysWhyAndWhereAndThatTheNextMessageTriesAgain() { let failed = JSONValue.object([ "conversation": .object([ "id": .string("conv-1"), "state": .string("failed"), "error": .string("this session names no repository"), "machine": .string("loop-mac"), ]) ]) let said = ProjectThreads.conversationFailure(failed) ?? "" XCTAssertTrue(said.contains("loop-mac") && said.contains("this session names no repository"), said) // No Mac recorded and no sentence: still a failure, still said. let bare = JSONValue.object([ "conversation": .object(["id": .string("conv-1"), "state": .string("failed")]) ]) XCTAssertNotNil(ProjectThreads.conversationFailure(bare)) // Every other state — and no conversation at all — says nothing here. for state in ["queued", "starting", "running", "idle", "waiting", "ended"] { let row = JSONValue.object([ "conversation": .object([ "id": .string("conv-1"), "state": .string(state), "error": .string("stale"), ]) ]) XCTAssertNil(ProjectThreads.conversationFailure(row), state) } XCTAssertNil(ProjectThreads.conversationFailure(.object([:]))) XCTAssertNil(ProjectThreads.conversationFailure(.object(["conversation": .null]))) } // ── opening the conversation ────────────────────────────────────────── @MainActor func testTheComposerOpensTheConversationOnceAndReusesIt() async throws { let model = ProjectConversationModel() var opened = 0 let first = try await model.resolve(known: nil) { opened += 1 return "conv-1" } let second = try await model.resolve(known: nil) { opened += 1 return "conv-2" } XCTAssertEqual(first, "conv-1") // THE SAME ROW, and the method is not asked a second time: the second // message rides the id the first one opened. XCTAssertEqual(second, "conv-1") XCTAssertEqual(opened, 1) XCTAssertEqual(model.id, "conv-1") } @MainActor func testTheConversationTheReadAlreadyNamedIsNeverOpenedAgain() async throws { let model = ProjectConversationModel() var opened = 0 let id = try await model.resolve(known: "conv-7") { opened += 1 return "conv-9" } XCTAssertEqual(id, "conv-7") XCTAssertEqual(opened, 0) } // ── the second read the page mounts ─────────────────────────────────── @MainActor func testThePageMountsReadSessionForTheConversationItWasNamed() throws { let answer = JSONValue.object([ "conversation": .object([ "id": .string("conv-1"), "state": .string("idle"), "lastActiveAt": .string("2026-09-24T09:00:00Z"), ]), ]) let plan = try XCTUnwrap(ProjectThreads.conversationRead(answer)) // `read.project` names the conversation and stops there, so the // exchanges come from the conversation's OWN read, by its id. XCTAssertEqual(plan.name, "session") XCTAssertEqual(plan.id, "conv-1") XCTAssertEqual(plan.args, ["id": .string("conv-1")]) // A conversation is a session: it moves when sessions move. XCTAssertEqual(plan.families, [.sessions, .core]) } @MainActor func testAProjectWithNoConversationMountsNoSecondRead() { // Nothing to ask about, and a `read.session` with no id would be a // refusal sentence where the invitation to start one belongs. XCTAssertNil(ProjectThreads.conversationRead(.object([:]))) XCTAssertNil(ProjectThreads.conversationRead(.object(["conversation": .null]))) } @MainActor func testTheProjectPageDrawsTheTailOfALongConversationNotItsHead() { let session = JSONValue.object([ "id": .string("conv-1"), "startedAt": .string("2026-09-24T09:00:00Z"), ]) let turns: [JSONValue] = (1...40).map { seq in .object([ "seq": .number(Double(seq)), "role": .string("user"), "text": .string("turn \(seq)"), "ts": .string(String(format: "2026-09-24T10:%02d:00Z", seq)), ]) } let whole = SessionFacts.chat(session, messages: [], turns: turns) let drawn = SessionFacts.recent(whole, limit: ProjectThreads.conversationLimit) XCTAssertEqual(drawn.count, ProjectThreads.conversationLimit) // THE NEWEST, and the `started` line goes with the truncation: a page // showing thirty of forty turns must not claim to start at the start. XCTAssertEqual(drawn.last?.id, "turn-40") XCTAssertEqual(drawn.first?.id, "turn-11") XCTAssertFalse(drawn.contains { $0.id == "started" }) // A conversation shorter than the bound is drawn whole, `started` and // all. let short = SessionFacts.chat(session, messages: [], turns: Array(turns.prefix(3))) XCTAssertEqual(SessionFacts.recent(short, limit: 30).map(\.id), short.map(\.id)) } // ── the address Home uses ───────────────────────────────────────────── func testTheProjectPageIsReachedAtProjectsSlug() { // Home's caps open `/projects/`, so // the composer, the conversation and the Threads section all hang off // this one address resolving. XCTAssertEqual(Route.parse("/projects/cottondb"), .projectsSlug(slug: "cottondb")) XCTAssertEqual(Route.projectsSlug(slug: "cottondb").path, "/projects/cottondb") } }