// A project's sections, and the pure sentences its pages are built from.//// Ported from `apps/cotton/src/tools/projects/lib/{projectSections,projectBands,// memberTitle,brandKit,feedbackFacts}.ts` and//// **The section table is TOTAL over what `get_project` answers**, and that is// the whole point of writing it out. The tool groups a project's members into// twenty-five named buckets (`linked.people`, `linked.threads`,// `linked.emailThreads`, …) and counts each one; a bucket this table forgot// would be a section the page silently never draws, which is the failure the// crate's own `PROJECT_LINK_KINDS` totality rule exists to prevent. So the// table names all twenty-five, `ProjectFactsTests` holds it against the tool's// own list, and a bucket added there without a row here fails loudly.//// The section KEY in the route is the Expo screen's own word, not the tool's// group name — `/projects/x/chats`, not `/projects/x/threads`. The two differ// for five sections and the mapping is written down once, here, because a URL// is a contract with notifications and anything the owner bookmarked,// and renaming one to match an internal JSON key would break those for nothing.// Four of the five were named before the tool's JSON keys existed. The fifth,// `passwords` over the group `secrets`, is a decision rather than an// inheritance: the SCREEN is Passwords, the way Apple's is, and the RECORD KIND// is `secret` — so the URL a person sees says the screen's word and the JSON// says the kind's, deliberately (the vault design, §Language).importCottonKitimportSwiftUI/// One section of a project's page.publicstructProjectSection: Identifiable, Sendable {/// The word in the route: `/projects/[slug]/[key]`.publiclet key: String/// The key `get_project` answers this group's rows and count under.publiclet group: String/// The heading, as the Expo page wrote it.publiclet label: String/// The SF Symbol on the row's mark.publiclet symbol: String/// How the section opens.publiclet render: Renderpublicvar id: String { key }/// Whether the section holds ONE thing rather than a list — the briefing/// and the brand kit. The page draws it as its heading and one line saying/// what it holds, with no count, and the heading opens the thing itself./// The crate's own answer/// is `project_page::PageSection::holds_one`, and the read says so by/// sending no `count` for it.publicvar holdsOne: Bool { key == "briefing" || key == "brand" }publicenumRender: Sendable {/// A list of this project's members, on `/projects/[slug]/[key]`.case rows/// A screen of its own — the section row links to it.case screen }}publicenumProjectSections {/// Every group `get_project` can answer, with the Expo page's own words.////// **The order IS the page's order, and it is the CRATE's** —/// `ProjectSectionKey` in `crates/cotton-core/src//// constants.rs`, which is itself the port of/// `packages/core/src/engine/projectSections.ts`. It is editorial, not/// derived: Thoughts sits immediately before Notes because a thought is/// what a note is made of, and Memory sits above Notes because it is what/// the person opens the page to CHECK. `ProjectFactsTests` reads that file/// by path and holds this array against it AS AN ORDERED LIST, so a/// re-shuffle here fails rather than quietly re-ranking somebody's page.publicstaticvar all: [ProjectSection] { [ProjectSection(key: "people", group: "people", label: ShellLines.line("projects", "section.people"), symbol: "person.2", render: .rows),ProjectSection(key: "chats", group: "threads", label: ShellLines.line("projects", "section.chats"), symbol: "bubble.left", render: .rows),ProjectSection(key: "email", group: "emailThreads", label: ShellLines.line("projects", "section.email"), symbol: "envelope", render: .rows),ProjectSection(key: "documents", group: "documents", label: ShellLines.line("projects", "section.documents"), symbol: "doc.text", render: .rows),ProjectSection(key: "todos", group: "todos", label: ShellLines.line("projects", "section.todos"), symbol: "checkmark.circle", render: .screen),ProjectSection(key: "thoughts", group: "thoughts", label: ShellLines.line("projects", "section.thoughts"), symbol: "tray", render: .rows),ProjectSection(key: "memory", group: "memory", label: ShellLines.line("projects", "section.memory"), symbol: "brain", render: .screen),ProjectSection(key: "notes", group: "notes", label: ShellLines.line("projects", "section.notes"), symbol: "note.text", render: .rows),ProjectSection(key: "journal", group: "journal", label: ShellLines.line("projects", "section.journal"), symbol: "book", render: .rows),ProjectSection(key: "meetings", group: "meetings", label: ShellLines.line("projects", "section.meetings"), symbol: "waveform", render: .rows),ProjectSection(key: "events", group: "events", label: ShellLines.line("projects", "section.events"), symbol: "calendar", render: .rows),ProjectSection(key: "reader", group: "pages", label: ShellLines.line("projects", "section.reader"), symbol: "text.book.closed", render: .rows),ProjectSection(key: "locations", group: "locations", label: ShellLines.line("projects", "section.locations"), symbol: "mappin.and.ellipse", render: .rows),ProjectSection(key: "money", group: "transactions", label: ShellLines.line("projects", "section.money"), symbol: "wallet.pass", render: .rows),ProjectSection(key: "goals", group: "goals", label: ShellLines.line("projects", "section.goals"), symbol: "target", render: .rows),// CODE (v19). A repository is a LINKED KIND now rather than a field on// the project — `ProjectLinkKind::Repository`, `ProjectSectionKey::Code`// — so it takes a section, between Goals and Feedback where the// crate puts it.//// **An ordinary list section since the page became all sections**// its newest repositories as paper rows, each opening// `/repos/[id]`, and the heading opening the list of all of them. The// footer row per repository went — a repository was on the page twice,// in two forms — and the project's SESSIONS are a section of their own// (`pageOnly`), which is what `/projects/[slug]/code` has always shown.ProjectSection(key: "code", group: "repositories", label: ShellLines.line("projects", "section.code"), symbol: "chevron.left.forwardslash.chevron.right", render: .rows),// DECISIONS (v42), right after Code: what an agent decided while// building and why — the decision log, which is never briefed and is// read here, beside the code it shaped. A decision has no page of its// own; the row is the sentence.ProjectSection(key: "decisions", group: "decisions", label: ShellLines.line("projects", "section.decisions"), symbol: "signpost.right", render: .rows),ProjectSection(key: "feedback", group: "feedback", label: ShellLines.line("projects", "section.feedback"), symbol: "exclamationmark.bubble", render: .screen),ProjectSection(key: "photos", group: "photos", label: ShellLines.line("projects", "section.photos"), symbol: "photo", render: .rows),ProjectSection(key: "videos", group: "videos", label: ShellLines.line("projects", "section.videos"), symbol: "video", render: .rows),ProjectSection(key: "albums", group: "albums", label: ShellLines.line("projects", "section.albums"), symbol: "photo.stack", render: .rows),ProjectSection(key: "calls", group: "calls", label: ShellLines.line("projects", "section.calls"), symbol: "phone", render: .rows),ProjectSection(key: "passwords", group: "secrets", label: ShellLines.line("projects", "section.passwords"), symbol: "key", render: .rows), ] }/// The four sections of a project's page that are not link groups:/// its coding SESSIONS (a list, bound by `project_id`), its PROCEDURES/// (a list, the notes `get_project` groups out because their first line/// names a trigger), its BRIEFING and its BRAND kit (one thing each). None/// of them is a `kind_source` group, which is why they are not in `all` —/// that table is held total over the tool's kind groups, both ways.////// **Their ORDER is not this table's, and neither is `all`'s any more.**/// The page draws the order `read.project` answers as `sections` — the/// crate's `project_page::arrange` over the owner's own order — so there/// is no second copy of the page's order on this side to drift.publicstaticvar pageOnly: [ProjectSection] { [ProjectSection(key: "sessions", group: "sessions", label: ShellLines.line("projects", "section.sessions"), symbol: "terminal", render: .screen),ProjectSection(key: "procedures", group: "procedures", label: ShellLines.line("projects", "section.procedures"), symbol: "list.number", render: .screen),ProjectSection(key: "briefing", group: "briefing", label: ShellLines.line("projects", "section.briefing"), symbol: "doc.plaintext", render: .screen),ProjectSection(key: "brand", group: "brand", label: ShellLines.line("projects", "section.brand"), symbol: "paintpalette", render: .screen), ] }/// Every section a project's page can draw.publicstaticvar every: [ProjectSection] { all + pageOnly }/// The word the Code section's list is addressed by —/// `/projects/[slug]/repositories`.////// Not `code`, and that is the one place a section's address is not its/// key: `/projects/[slug]/code` is the project's SESSIONS page, a route/// string older than this section, and route strings are wire protocol/// that do not move (`crates/cotton-ffi/src/phone/routes.rs`). The Sessions/// section opens that page; the repositories take the member list at this/// word, which `named` reads back as the Code section.publicstaticlet codeListWord = "repositories"publicstaticfunc named(_ key: String) -> ProjectSection? {if key == codeListWord { return all.first { $0.key == "code" } }return every.first { $0.key == key } }/// How many members a section has, from the tool's own `counts`.////// `todos` is the one group the tool shapes differently — it answers/// `{openCount, closedCount, open}` because the project page counts what is/// still OPEN, and a section reading "12 todos" over eleven finished ones/// would be a number nobody can act on.publicstaticfunc count(_ section: ProjectSection, in answer: JSONValue) -> Int {if section.key == "todos" {return answer["linked"]?["todos"]?["openCount"]?.int ?? 0 }return answer["counts"]?[section.group]?.int ?? 0 }/// The rows a section draws, in the order the tool answered them.publicstaticfunc rows(_ section: ProjectSection, in answer: JSONValue) -> [JSONValue] {if section.key == "todos" {return answer["linked"]?["todos"]?["open"]?.array ?? [] }return answer["linked"]?[section.group]?.array ?? [] }/// The sections a project actually has — a section with no members is/// absent from the page entirely, never drawn as a zero.publicstaticfunc present(in answer: JSONValue) -> [ProjectSection] { all.filter { count($0, in: answer) > 0 } }/// `4 people` — the meta line on a section row.publicstaticfunc countLabel(_ section: ProjectSection, _ count: Int) -> String { countLabel(key: section.key, count) }/// The same, by key — the project page's own runs row counts without/// holding a `ProjectSection`.////// TOTAL over `ProjectSections.all` by construction: the default arm names/// the section rather than inventing a noun, and `ProjectFactsTests` proves/// no section reaches it.staticfunc countLabel(key: String, _ n: Int) -> String {switch key {case"people": return plural(n, one: ShellLines.line("projects", "count.person.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.person.many", ["n": "\(n)"]))case"chats": return plural(n, one: ShellLines.line("projects", "count.chat.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.chat.many", ["n": "\(n)"]))case"email": return plural(n, one: ShellLines.line("projects", "count.email_thread.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.email_thread.many", ["n": "\(n)"]))case"documents": return plural(n, one: ShellLines.line("projects", "count.document.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.document.many", ["n": "\(n)"]))case"todos": return plural(n, one: ShellLines.line("projects", "count.todo.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.todo.many", ["n": "\(n)"]))case"notes": return plural(n, one: ShellLines.line("projects", "count.note.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.note.many", ["n": "\(n)"]))case"journal":return plural(n, one: ShellLines.line("projects", "count.journal_entry.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.journal_entry.many", ["n": "\(n)"]))case"meetings": return plural(n, one: ShellLines.line("projects", "count.meeting.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.meeting.many", ["n": "\(n)"]))case"events": return plural(n, one: ShellLines.line("projects", "count.event.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.event.many", ["n": "\(n)"]))case"reader": return plural(n, one: ShellLines.line("projects", "count.page.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.page.many", ["n": "\(n)"]))case"locations": return plural(n, one: ShellLines.line("projects", "count.place.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.place.many", ["n": "\(n)"]))case"money": return plural(n, one: ShellLines.line("projects", "count.transaction.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.transaction.many", ["n": "\(n)"]))case"goals": return plural(n, one: ShellLines.line("projects", "count.goal.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.goal.many", ["n": "\(n)"]))case"thoughts": return plural(n, one: ShellLines.line("projects", "count.thought.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.thought.many", ["n": "\(n)"]))case"photos": return plural(n, one: ShellLines.line("projects", "count.photo.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.photo.many", ["n": "\(n)"]))case"videos": return plural(n, one: ShellLines.line("projects", "count.video.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.video.many", ["n": "\(n)"]))case"albums": return plural(n, one: ShellLines.line("projects", "count.album.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.album.many", ["n": "\(n)"]))case"calls": return plural(n, one: ShellLines.line("projects", "count.call.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.call.many", ["n": "\(n)"]))case"passwords": return plural(n, one: ShellLines.line("projects", "count.password.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.password.many", ["n": "\(n)"]))case"memory":return plural(n, one: ShellLines.line("projects", "count.memory.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.memory.many", ["n": "\(n)"]))case"feedback": return plural(n, one: ShellLines.line("projects", "count.report.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.report.many", ["n": "\(n)"]))case"code": return plural(n, one: ShellLines.line("projects", "count.repository.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.repository.many", ["n": "\(n)"]))case"decisions": return plural(n, one: ShellLines.line("projects", "count.decision.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.decision.many", ["n": "\(n)"]))case"sessions": return plural(n, one: ShellLines.line("projects", "count.session.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.session.many", ["n": "\(n)"]))case"procedures": return plural(n, one: ShellLines.line("projects", "count.procedure.one", ["n": "\(n)"]), many: ShellLines.line("projects", "count.procedure.many", ["n": "\(n)"]))default: return"\(n) \(key)" } }/// Where a SECTION opens — the page's own heading tap. Three link groups/// have screens of their own; the rest are a member list; Sessions,/// Procedures, Briefing and Brand open what they are. ONE function, so/// Home's tile and the page cannot come to disagree about where "Todos"/// goes.publicstaticfunc route(_ section: ProjectSection, slug: String) -> Route {switch section.key {case"todos": return .projectsTodos(slug: slug)case"memory": return .projectsMemory(slug: slug)case"feedback": return .projectsFeedback(slug: slug)// Every repository the project names, as a member list.case"code": return .projectsSlugSection(slug: slug, section: codeListWord)// The project's sessions — the `/code` list, cut to this project.case"sessions": return .projectsCode(slug: slug)// The project's procedures, each with the sentence that says when it// applies — the project_item list, at the section's own word.case"procedures": return .projectsSlugSection(slug: slug, section: section.key)// What an assistant reads for this project, locked to it.case"briefing": return .briefing(project: slug)case"brand": return .projectsBrand(slug: slug)default: return .projectsSlugSection(slug: slug, section: section.key) } }/// Where one member of this section opens.////// `nil` for the rows that do not leave the section screen: feedback opens/// a verdict sheet in place, a password has no page of its own in this/// build (the vault's screens are a later lane's, and the row already/// carries the name, the site and the four-character hint — which is all/// anything but the vault screen may show), and a section this app has not/// drawn yet answers nothing rather than a route that draws a blank page.publicstaticfunc destination(_ section: ProjectSection, id: String) -> Route? {switch section.key {case"people": return .peoplePerson(id: id)case"chats": return .messagesThread(thread: id)case"email": return .emailId(id: id)case"documents": return .documentsDocument(id: id)case"todos": return .todosTodo(id: id)// A procedure IS a note — the one whose first line names its trigger —// so it opens on the note's own page; a journal page's id opens the// journal's page, headed by its day (`NoteRoute` reads which).case"notes", "journal", "procedures": return .notesNote(id: id)case"meetings": return .meetingsMeeting(id: id)case"events": return .calendarEvent(id: id, date: nil, at: nil)case"reader": return .readerPage(id: id)case"locations": return .locationsLocation(id: id)case"money": return .moneyTransaction(id: id)case"goals": return .goalsGoal(id: id)case"thoughts": return .thoughtsThought(id: id)case"photos": return .photosPhoto(id: id)case"videos": return .videosVideo(id: id)case"albums": return .photosAlbum(id: id)case"calls": return .callsCall(id: id)case"memory": return .memory(id: id)// A password's page IS the vault's own screen, against this device's// own key — `/passwords/[id]`, where the reveal happens behind a// presence prompt. The row that led nowhere while that screen did not// exist now leads to it.case"passwords": return .passwordsSecret(id: id)// The verdict is decided on the feedback screen itself; a report has// no page of its own.case"feedback": returnnil// A decision is read in its row; it has no page of its own.case"decisions": returnnil// A repository has no page since its tables were retired (TABLE DROP 1).case"code": returnnil// One session's page — where every card on `/code` goes.case"sessions": return .sessionsId(id: id)default: returnnil } }}// MARK: - what a row is calledpublicenumProjectFacts {/// Last activity descending, name ascending — and an unknown or unreadable/// instant sorts LAST rather than first, which is what a bare string/// comparison over `nil` would give.////// **`read.projects` does not carry `lastActivity` today, so this list/// reads alphabetically.** That read is the bare `list_projects`, whose/// `project_out` answers `{slug, name, description?, summaryBy?,/// summaryUpdatedAt?, repos, status, brand?}` and no instant at all — so/// every row compares equal here and the name tiebreak decides the whole/// order. It is stated rather than hidden: the comparator is right, its/// input is missing.////// The instant EXISTS on the phone already — `read.home`'s projects band/// stamps it (`project_overviews` / `projects_band` in/// `crates/cotton-ffi/src/phone/reads.rs`, the port of/// `packages/core/src/engine/projectActivity.ts`) — so the fix is for/// `read.projects` to become a composite that stamps the same key, and/// this comparator then needs no change. Until it does, the/// most-recently-worked-first order is owed back.////// The instant is compared as TEXT, and that is only chronological because/// every stamp the crate answers is the same UTC form (`…Z`, fixed width)./// A stamp carrying an offset would sort by its digits rather than by its/// moment. Parsing each one per comparison is the wrong trade for a list/// this size, so the assumption is written here instead: if a column ever/// starts answering a local-offset stamp, this is the line that goes wrong/// quietly.publicstaticfunc order(_ projects: [JSONValue]) -> [JSONValue] { projects.sorted { left, right inlet a = left.text("lastActivity") ?? ""let b = right.text("lastActivity") ?? ""if a != b { return a > b }return (left.text("name") ?? "") < (right.text("name") ?? "") } }// ── the slug a new project is born with ───────────────────────────────/// The column's own ceiling (`length(slug) BETWEEN 1 AND 64`).privatestaticlet slugMaxLength = 64/// What a name with nothing addressable left in it becomes.privatestaticlet slugFallback = "project"/// Mint the slug for a NEW project, from its name, once.////// `create_project` requires `slug`, and nothing between here and it will/// mint one: `cotton_core::transforms::project_slug::mint_project_slug` exists/// in the crate but no `read.*` and no tool exposes it to Swift, so the/// sheet mints it exactly as the Expo sheet did/// (`apps/cotton/src/app/(app)/projects/index.tsx`, `mintProjectSlug` from/// `packages/core/src/engine/projectSlug.ts`).////// The shape the COLUMN enforces: 1–64 characters of lowercase `a-z0-9`/// and `-`, first character `a-z0-9`. Anything else becomes a separator;/// a name that leaves nothing behind falls back to `project` rather than/// minting an address the CHECK would refuse. **The trailing-dash trim is/// ours, not the column's** — `meri-` is a legal slug and a shabby/// address.////// `taken` is not optional: `UNIQUE (workspace_id, slug)` does not read/// status, so a second "Meri" is born `meri-2` rather than as a constraint/// refusal the person can do nothing about. The suffix stays inside the/// cap by shortening the head, and the head is re-trimmed after the cut/// because the cut can land on a separator.////// No reserved list: `RESERVED_PROJECT_SLUGS` is EMPTY in the crate (the/// `global` page went with schema v34), and a second copy of an empty list/// would be a second place to forget to update.publicstaticfunc mintSlug(_ name: String, taken: Set<String>) -> String {let normalized = slugNormalize(name)let base = trimTrailingDashes(String(normalized.prefix(slugMaxLength)))let head = base.isEmpty ? slugFallback : baseif !taken.contains(head) { return head }var n = 2whiletrue {let suffix = "-\(n)"let cut = trimTrailingDashes(String(head.prefix(slugMaxLength - suffix.count)))let candidate = (cut.isEmpty ? slugFallback : cut) + suffixif !taken.contains(candidate) { return candidate } n += 1 } }/// Name → the column's alphabet, with both edges clean.////// No unicode folding, deliberately: `Café Meri` becomes `caf-meri`, not/// `cafe-meri`. That is what the TypeScript does, and two slug minters/// disagreeing about one name is a silent change of address.privatestaticfunc slugNormalize(_ name: String) -> String {var out = ""var pendingSeparator = falsefor character in name.lowercased() {if character.isASCII && (character.isLetter || character.isNumber) {if pendingSeparator && !out.isEmpty { out.append("-") } pendingSeparator = false out.append(character) } else { pendingSeparator = true } }return out }privatestaticfunc trimTrailingDashes(_ text: String) -> String {var out = textwhile out.hasSuffix("-") { out.removeLast() }return out }// ── the brand kit ─────────────────────────────────────────────────────/// The four slots a brand kit has, always all four and always in this/// order — an empty slot is a fact the page states, not a row it hides.publicstaticlet brandRoles = ["logo", "logo-dark", "wordmark", "icon"]/// The Brand row's meta line on the project page.publicstaticfunc brandCountLine(_ brand: JSONValue, assets: [String: JSONValue]) -> String { brandCountLine(BrandFacts( colours: brand.list("colors").count, fonts: brand.list("fonts").count, voice: brand.text("voice") != nil, tagline: brand.text("tagline") != nil, links: !brand.list("links").isEmpty, files: Array(assets.keys) ) ) }/// What a brand kit holds, as figures — all the Brand line needs.publicstructBrandFacts: Equatable, Sendable {publiclet colours: Intpubliclet fonts: Intpubliclet voice: Boolpubliclet tagline: Boolpubliclet links: Bool/// The brand roles a linked logo file fills, each once.publiclet files: [String]publicinit(colours: Int, fonts: Int, voice: Bool, tagline: Bool, links: Bool, files: [String]) {self.colours = coloursself.fonts = fontsself.voice = voiceself.tagline = taglineself.links = linksself.files = files } }/// The Brand line from the kit's figures — the ONE wording, which the page/// reaches through the kit's JSON.publicstaticfunc brandCountLine(_ kit: BrandFacts) -> String {var parts: [String] = []let colours = kit.colourslet fonts = kit.fontsif colours > 0 { parts.append(plural(colours, one: "\(colours) colour", many: "\(colours) colours")) }if fonts > 0 { parts.append(plural(fonts, one: "\(fonts) font", many: "\(fonts) fonts")) }if parts.isEmpty {if kit.voice { parts.append("voice") }if kit.tagline { parts.append("tagline") }if kit.links { parts.append("links") } }if kit.files.count == 1, let role = kit.files.first { parts.append(CottonStrings.brandRoleLabel(role).lowercased()) } elseif kit.files.count > 1 { parts.append(plural(kit.files.count, one: "\(kit.files.count) file", many: "\(kit.files.count) files")) }return parts.isEmpty ? ShellLines.line("projects", "colours_fonts_voice_and") : parts.joined(separator: " · ") }// ── feedback ──────────────────────────────────────────────────────────}// MARK: - the project's conversation, and the threads under it/// A project has ONE standing conversation, and the sessions it opens are/// THREADS under it (Cotton note "The project conversation — one standing thread per project").////// PURE: the page's words for its conversation and the read it mounts for/// it. The threads are the session table's — `/projects/[slug]/code` lists/// them.enumProjectThreads {/// The one way in for a project with no conversation yet: opens it on/// its own page, where the first message is typed. Nothing has gone/// wrong: nobody has said anything.staticvar startConversation: String { ShellLines.line("projects", "start_the_conversation") }/// The conversation `read.project` names, or nothing.staticfunc conversationId(_ answer: JSONValue) -> String? { (answer["conversation"] ?? .null).text("id") }/// What a conversation that did not start says, or nothing.////// **A FAILURE IS SAID ON THE PAGE, in the sentence the Mac wrote.** The/// row is `failed` with `error` (why) and `machine` (where) on it — the/// same facts a thread's card already draws — and without this line the/// page went on showing the owner's message as waiting for ever. The last/// clause is the verb: there is no button, because the next message IS/// the retry (the server restarts a failed conversation for a message/// newer than its failure).staticfunc conversationFailure(_ answer: JSONValue) -> String? {let row = answer["conversation"] ?? .nullguard row.text("state") == "failed"else { returnnil }let why = row.text("error").flatMap { $0.isEmpty ? nil : $0 } ?? didNotStart// The Mac's sentence rarely ends in a full stop; the page's does.let sentence = why.hasSuffix(".") ? why : why + "."iflet machine = row.text("machine"), !machine.isEmpty {returnShellLines.line("projects", "conversation_failed.on", ["machine": machine, "why": sentence]) }returnShellLines.line("projects", "conversation_failed.here", ["why": sentence]) }/// The failure's own words when the Mac wrote none.staticvar didNotStart: String { ShellLines.line("projects", "conversation_failed.did_not_start") }/// The verb on a failed conversation — the composer above it.staticvar nextMessageRetries: String { ShellLines.line("projects", "conversation_failed.retry") }/// How many of a conversation's exchanges the PROJECT page draws.////// A standing conversation has no end, so the page would otherwise grow/// without one. Thirty is a session's worth of back-and-forth — enough to/// see what was asked this morning and what came back — and the whole of/// it is one tap away on the conversation's own page.staticlet conversationLimit = 30/// The link under a bounded transcript.staticvar openConversation: String { ShellLines.line("projects", "open_the_conversation") }/// The SECOND read a project page mounts: the conversation's own, by id.////// `read.project` names the conversation (`{id, state, lastActiveAt}`) and/// stops there — the exchanges are `read.session`'s, which already answers/// the turns, the messages addressed to the session and its task list. So/// the page asks that read for the id it was given, and draws the answer/// with the session page's own transcript.////// `nil` for a project with no conversation: there is nothing to ask/// about, and a read with no id is a refusal the person would have to/// read.staticfunc conversationRead(_ answer: JSONValue) -> ConversationRead? {guardlet id = conversationId(answer) else { returnnil }returnConversationRead(id: id) }/// What `conversationRead` names — the read, its argument and the families/// it claims, so a test holds the page to all three.structConversationRead: Equatable {/// `read.session`.let name = "session"/// The conversation's row id.let id: Stringvar args: [String: JSONValue] { ["id": .string(id)] }/// A conversation is a session: it moves when sessions move.var families: Set<ScreenFamily> { [.sessions, .core] } }}/// The project page's one conversation, opened ONCE and kept.////// `project.conversation` is idempotent — it answers the existing row or opens/// one — so a second call would land on the same row and cost a round trip per/// message. The screen holds this for as long as it is on screen; the id it/// keeps is a derived one, so a reload cannot hand it a different row.@MainActor@ObservablefinalclassProjectConversationModel {/// The conversation this page is talking to, once anything has asked.private(set) var id: String?/// The id to send to, opening the conversation only if nothing has.////// `known` is what the read already answered (`read.project`'s own/// `conversation`), which is the cheapest of the three answers: a project/// whose conversation exists never calls the method at all.func resolve(known: String?, open: () asyncthrows -> String) asyncrethrows -> String {iflet id { return id }iflet known { id = knownreturn known }let opened = tryawaitopen() id = openedreturn opened }}