// The writer's chips: wait until there is a record, then link it, and give up // eventually. // // The two decision maps (`CaptureLinks.swift`) are used FOR REAL: which table a // kind can be written to is the decision this file exists to carry out, so // stubbing it would test nothing. What IS doubled is the three things the host // answers and the two things the boundary writes, promoted here to two // protocols for the reason `PendingLinks.swift`'s header gives. // // The cases with no twin in the previous app are named as such where they sit, // and each exists because this one had to decide something that one did not: a // project the app cannot name, a routed kind this build does not know, the // missing `cotton_links` tool, the key-shape guard, the two tools that write a // project link where there was one service, and the refusal an ACTIVE-only // `project` argument introduced. // // One case is INVERTED rather than carried across — `testTouchesNoKeyButItsOwn`, // which was "removes the retired tag intent key on the first drain". Its own // comment says why. import Foundation import XCTest @testable import CottonKit // MARK: - The doubles /// The intent list, in memory. Every write is logged so a test can assert that a /// drain which settled nothing touched nothing. final class MemoryLinkStore: PendingLinkStore, @unchecked Sendable { private let lock = NSLock() private var map: [String: Data] = [:] private var log: [String] = [] func data(_ key: String) -> Data? { lock.lock() defer { lock.unlock() } return map[key] } func set(_ key: String, _ value: Data?) { lock.lock() defer { lock.unlock() } if let value { map[key] = value log.append("set:\(key)") } else { map.removeValue(forKey: key) log.append("remove:\(key)") } } // ── What a test asks it ─────────────────────────────────────────────── func has(_ key: String) -> Bool { data(key) != nil } func text(_ key: String) -> String? { data(key).map { String(decoding: $0, as: UTF8.self) } } func put(_ key: String, raw text: String) { set(key, Data(text.utf8)) } func intents(_ key: String) -> [PendingLinkIntent] { guard let raw = data(key) else { return [] } return (try? JSONDecoder().decode([PendingLinkIntent].self, from: raw)) ?? [] } func logged() -> [String] { lock.lock() defer { lock.unlock() } return log } func clearLog() { lock.lock() defer { lock.unlock() } log = [] } } /// What the host answers: what a capture filed, whose a person note is, and what /// a project is called. actor ScriptedLinkSource: PendingLinkSource { /// The answer for every capture, unless one is named below. var filedForAll: FiledCapture? var filedByItem: [String: FiledCapture] = [:] var ownPersonAnswer: OwnPerson = .known("per-1") /// `nil` means "answer every id with itself", which keeps a test's assertions /// reading in project IDS the way the TypeScript's did. var slugs: [String: String]? /// Set by `holdsTheNextAnswer`: the next `filed` waits until `release`, so a /// test can start a second drain while the first is truly still running. private var holdNext = false private var held: CheckedContinuation? private var heldArrived = false private var waitingForHold: CheckedContinuation? func filed(_ inboxItemId: String) async -> FiledCapture? { if holdNext { holdNext = false heldArrived = true waitingForHold?.resume() waitingForHold = nil await withCheckedContinuation { held = $0 } } return filedByItem[inboxItemId] ?? filedForAll } func holdsTheNextAnswer() { holdNext = true } /// Returns once a drain is parked inside the held `filed`. func untilHeld() async { if heldArrived { return } await withCheckedContinuation { waitingForHold = $0 } } func release() { held?.resume() held = nil } func ownPerson(ofPersonNote recordId: String) async -> OwnPerson { ownPersonAnswer } func projectSlug(_ projectId: String) async -> String? { guard let slugs else { return projectId } return slugs[projectId] } func routed(_ records: [RoutedRecord]) { filedForAll = FiledCapture(routedRecords: records) } func filedByHand(kind: String, id: String) { filedForAll = FiledCapture(routedRecords: [], routedKind: kind, routedId: id) } func says(_ answer: FiledCapture?) { filedForAll = answer } func ownPersonIs(_ answer: OwnPerson) { ownPersonAnswer = answer } func namesNoProjects() { slugs = [:] } } /// The two link writes, recorded — and refusable. actor RecordingLinkWriter: PendingLinkWriting { struct ProjectCall: Hashable, Sendable { let projectSlug: String let kind: String let id: String } struct PersonCall: Hashable, Sendable { let fromKind: String let fromId: String let toPersonId: String } /// Every project write, in order, WHICHEVER tool made it — the ledger the /// rules-level cases read, because the rule ("the thought keeps its own /// membership") is about the row that lands, not about the verb. private(set) var projectCalls: [ProjectCall] = [] /// Only the ones that went through `update_thought`. Kept apart so a case /// can assert WHICH tool wrote the thought's membership — the whole reason /// there are two methods (`applied_by: "user"` versus `"agent"`). private(set) var thoughtCalls: [ProjectCall] = [] private(set) var personCalls: [PersonCall] = [] /// Consumed left to right; `false` throws. Anything past the end lands. var projectAnswers: [Bool] = [] var personAnswers: [Bool] = [] var projectAlwaysThrows = false var personAlwaysThrows = false /// Throw what the CORE throws when it has deliberated and said no — the /// archived-project case. A different failure from a dead transport, and /// the drain answers the two differently. var projectRefusedByCore = false /// Run at the moment a project write is in flight — how a test sees what /// storage held before the claim. var whileWriting: (@Sendable () -> Void)? enum Refused: Error { case write } func linkProject(projectSlug: String, record: LinkRef) async throws { projectCalls.append( ProjectCall(projectSlug: projectSlug, kind: record.kind.rawValue, id: record.id) ) whileWriting?() if projectRefusedByCore { throw CottonCallError( code: "tool_failed", message: "unknown project \"pr-1\" — projects are: other" ) } if projectAlwaysThrows { throw Refused.write } let index = projectCalls.count - 1 if index < projectAnswers.count && !projectAnswers[index] { throw Refused.write } } func linkThoughtProject(projectSlug: String, thoughtId: String) async throws { thoughtCalls.append( ProjectCall(projectSlug: projectSlug, kind: "thought", id: thoughtId) ) // The same ledger and the same scripted answers as `linkProject`: from // the drain's point of view these are one write, and the cases that // script a refusal per call should not have to know which tool made it. try await linkProject( projectSlug: projectSlug, record: LinkRef(kind: .thought, id: thoughtId) ) } func linkPerson(from: LinkRef, toPersonId: String) async throws { personCalls.append( PersonCall(fromKind: from.kind.rawValue, fromId: from.id, toPersonId: toPersonId) ) if personAlwaysThrows { throw Refused.write } let index = personCalls.count - 1 if index < personAnswers.count && !personAnswers[index] { throw Refused.write } } func answersProject(_ answers: [Bool]) { projectAnswers = answers } func answersPerson(_ answers: [Bool]) { personAnswers = answers } func throwsEveryProjectWrite() { projectAlwaysThrows = true } func coreRefusesEveryProjectWrite() { projectRefusedByCore = true } func throwsEveryPersonWrite() { personAlwaysThrows = true } func observe(_ block: (@Sendable () -> Void)?) { whileWriting = block } func projectSlugsAsked() -> [String] { projectCalls.map(\.projectSlug) } } /// Everything the drain reported rather than swallowed. final class TroubleLog: @unchecked Sendable { private let lock = NSLock() private var all: [PendingLinkTrouble] = [] func note(_ trouble: PendingLinkTrouble) { lock.lock() defer { lock.unlock() } all.append(trouble) } func read() -> [PendingLinkTrouble] { lock.lock() defer { lock.unlock() } return all } } /// A clock a test moves, because the repo's rule is dates through a seam and /// never the wall clock — a fixed-`NOW` test over a subject that reads /// `Date()` is a time bomb with a computable detonation date. final class MovableClock: @unchecked Sendable { private let lock = NSLock() private var value: Date init(_ value: Date) { self.value = value } func set(_ next: Date) { lock.lock() defer { lock.unlock() } value = next } func read() -> Date { lock.lock() defer { lock.unlock() } return value } } // MARK: - The tests final class PendingLinksTests: XCTestCase { private let key = "@cotton:pendingLinks:v1:u1:ws-1" private let retiredKey = "@cotton:pendingTags:v1" /// 2026-08-01T00:00:00Z, the instant the TypeScript's expiry cases pin. private static let august1 = Date(timeIntervalSince1970: 1_785_542_400) private static let august2 = Date(timeIntervalSince1970: 1_785_628_800) private static let august6 = Date(timeIntervalSince1970: 1_785_974_400) private static let august9 = Date(timeIntervalSince1970: 1_786_233_600) private struct Kit { let store: MemoryLinkStore let source: ScriptedLinkSource let writer: RecordingLinkWriter let troubles: TroubleLog let clock: MovableClock let links: PendingLinks } private func makeKit(user: String = "u1", workspace: String = "ws-1") -> Kit { makeKit(user: user, workspace: workspace, store: MemoryLinkStore()) } private func makeKit(user: String, workspace: String, store: MemoryLinkStore) -> Kit { let source = ScriptedLinkSource() let writer = RecordingLinkWriter() let troubles = TroubleLog() let clock = MovableClock(PendingLinksTests.august1) let links = PendingLinks( userId: user, workspaceId: workspace, store: store, source: source, writer: writer, now: { clock.read() }, report: { troubles.note($0) } ) return Kit( store: store, source: source, writer: writer, troubles: troubles, clock: clock, links: links ) } // MARK: rememberPendingLinks func testWritesNothingWhenThereIsNothingToRemember() async { let kit = makeKit() await kit.links.remember(inboxItemId: "i1", projectIds: [], personIds: []) XCTAssertFalse(kit.store.has(key)) } func testKeepsTheProjectsAndThePeopleApart() async { let kit = makeKit() await kit.links.remember( inboxItemId: "i1", projectIds: ["pr-1"], personIds: ["per-1", "per-2"] ) let stored = kit.store.intents(key) XCTAssertEqual(stored.count, 1) XCTAssertEqual(stored.first?.inboxItemId, "i1") XCTAssertEqual(stored.first?.projectIds, ["pr-1"]) XCTAssertEqual(stored.first?.personIds, ["per-1", "per-2"]) } /// No TypeScript twin — the key was a constant there and is derived here, so /// the shape is worth holding. One list PER IDENTITY: a shared list would /// let a drain running as somebody else apply that person's chip inside a /// workspace it was never meant for. func testTheKeyIsIdentityScopedByteForByte() { XCTAssertEqual( pendingLinksStorageKey(userId: "u1", workspaceId: "ws-1"), "@cotton:pendingLinks:v1:u1:ws-1" ) XCTAssertEqual( pendingLinksStorageKey(userId: "u2", workspaceId: "ws-2"), "@cotton:pendingLinks:v1:u2:ws-2" ) } // MARK: drainPendingLinks func testWaitsWhileTheCaptureIsUnroutedAndKeepsTheIntent() async { let kit = makeKit() await kit.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) let settled = await kit.links.drain() XCTAssertEqual(settled, 0) XCTAssertEqual(kit.store.intents(key).map(\.inboxItemId), ["i1"]) } func testWritesTheRecordsProjectLinkAndTheThoughtsOwn() async { // Schema v29: a thought keeps its own membership whatever it became, so // the chip the person set files BOTH — otherwise a project's Thoughts row // would be empty for exactly the captures they took the trouble to name. let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await kit.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) let settled = await kit.links.drain() XCTAssertEqual(settled, 1) let calls = await kit.writer.projectCalls XCTAssertEqual(calls.count, 2) XCTAssertTrue( calls.contains( RecordingLinkWriter.ProjectCall(projectSlug: "pr-1", kind: "thought", id: "i1") ) ) XCTAssertTrue( calls.contains( RecordingLinkWriter.ProjectCall(projectSlug: "pr-1", kind: "todo", id: "todo-1") ) ) } func testStillFilesTheThoughtsMembershipWhenTheRecordItselfCanWearNone() async { // A person_note's membership goes to the PERSON, and when its own row // cannot be read there is no person to hang it on — but the thought is // still the thought, and the chip the owner set must not vanish with it. let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "person_note", id: "pn-1")]) await kit.source.ownPersonIs(.unreadable) await kit.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) _ = await kit.links.drain() let calls = await kit.writer.projectCalls XCTAssertTrue( calls.contains( RecordingLinkWriter.ProjectCall(projectSlug: "pr-1", kind: "thought", id: "i1") ) ) } func testWritesTheThoughtsOwnMembershipThroughTheThoughtsOwnVerb() async { // NO TypeScript original: there the drain called one service // (`projectsService.linkRecord`) for every membership. Here the two are // two tools, and WHICH one writes the thought decides whose hand the row // claims — `update_thought` stamps `applied_by: "user"` // (`cotton-tools/src/mcp/handlers/thoughts.rs:433`), `link_to_project` // writes the literal `"agent"` (`handlers/projects/write.rs:558`). A `#` // chip is a person's thumb. let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await kit.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) _ = await kit.links.drain() let thoughts = await kit.writer.thoughtCalls XCTAssertEqual( thoughts, [RecordingLinkWriter.ProjectCall(projectSlug: "pr-1", kind: "thought", id: "i1")] ) // And the RECORD's own membership does not: that one is // `link_to_project`, which is what the routed record's link still is. let all = await kit.writer.projectCalls XCTAssertTrue( all.contains( RecordingLinkWriter.ProjectCall(projectSlug: "pr-1", kind: "todo", id: "todo-1") ) ) } func testSendsUpdateThoughtWithTheSlugAndNothingElse() async throws { // The wire shape, at the boundary writer — the level at which a renamed // key would show. `dismissed` is deliberately absent: `update_thought` // refuses a call that changes nothing, `project` alone IS a change, and // sending the other field would be the drain deciding something about // the thought nobody asked it to decide (the same reasoning as R38's // omitted `note`). let core = ScriptedCore([CottonMethod.write: .ok("{}")]) let writer = CorePendingLinkWriter(core: core) try await writer.linkThoughtProject(projectSlug: "pr-1", thoughtId: "i1") let sent = await core.calls.first?.requestJSON ?? "" XCTAssertTrue(sent.contains("\"tool\":\"update_thought\"")) XCTAssertTrue(sent.contains("\"id\":\"i1\"")) XCTAssertTrue(sent.contains("\"project\":\"pr-1\"")) XCTAssertFalse(sent.contains("dismissed")) XCTAssertFalse(sent.contains("link_to_project")) } // MARK: - A refusal the core will repeat is DROPPED, not retried // // The case that actually happens: a project archived between the capture and // the drain. Both writers resolve their `project` argument to an ACTIVE // project only — `project_by_slug` (`handlers/projects/mod.rs:97-119`) and // `resolve_project` (`handlers/common.rs:751-768`) — and both throw for an // archived one. The previous app had no such refusal: it wrote by project // id with no status check at all, so the chip landed. func testDropsAnIntentTheCoreRefusesRatherThanRetryingItForAWeek() async { let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await kit.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) await kit.writer.coreRefusesEveryProjectWrite() let settled = await kit.links.drain() XCTAssertEqual(settled, 1, "a decision is a settlement, not a failure") XCTAssertEqual( kit.store.intents(key), [], "the archive is a decision only the person can undo — retrying it re-states, " + "every fold for seven days, a link they may have taken off" ) // Never silently: the chip is gone and the app says so. XCTAssertTrue( kit.troubles.read().contains { $0.what.contains("refused") }, "a dropped chip must be reported" ) } func testKeepsAnIntentWhenTheWriteFailedForAnyOtherReason() async { // The other half of the same decision. A dead transport is not the core // saying no — it is the core not answering — and it can come out // differently on the next fold, so the chip waits. let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await kit.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) await kit.writer.throwsEveryProjectWrite() let settled = await kit.links.drain() XCTAssertEqual(settled, 0) XCTAssertEqual(kit.store.intents(key).map(\.inboxItemId), ["i1"]) } func testCarriesNoNoteSoANoteTheOwnerTypedSurvivesTheDrain() async throws { // Ruling R38: an omitted `note` means "keep the note you found". The drain // has no opinion about the annotation — it is linking a record, not // annotating one — and the link id is derived, so the row it writes is the // SAME row the owner may already have written a sentence on. Sending a // null note would erase that sentence under their eyes. // // Asserted on the ARGUMENTS the boundary writer encodes, because that is // where the key would appear: the seam above it never had a note to drop. let core = ScriptedCore([CottonMethod.write: .ok("{}")]) let writer = CorePendingLinkWriter(core: core) try await writer.linkProject( projectSlug: "pr-1", record: LinkRef(kind: .todo, id: "todo-1") ) let sent = await core.calls.first?.requestJSON ?? "" XCTAssertTrue(sent.contains("\"tool\":\"link_to_project\"")) XCTAssertTrue(sent.contains("\"project\":\"pr-1\"")) XCTAssertTrue(sent.contains("\"kind\":\"todo\"")) XCTAssertFalse(sent.contains("note")) } func testWritesNoRecordProjectLinkForAPersonNoteWhosePersonCannotBeRead() async { // Better a missing link than an INSERT that fails the table's own CHECK. // The THOUGHT's own row still lands — asserted in its own case above, and // the reason this filters by kind rather than saying "not called at all". let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "person_note", id: "pn-1")]) await kit.source.ownPersonIs(.unreadable) await kit.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) _ = await kit.links.drain() let calls = await kit.writer.projectCalls XCTAssertEqual(calls.filter { $0.kind != "thought" }, []) } func testTwoOverlappingDrainsWriteOneEdgeNotTwo() async { // The host drains on appearance AND on every fold that touches the inbox, // so two really do overlap. Both link tables derive their ids now, so a // second pass would be an upsert rather than a duplicate — collapsing the // overlap saves the writes and keeps one answer. let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await kit.links.remember(inboxItemId: "i1", projectIds: [], personIds: ["per-1"]) // The first drain is parked inside its read until the second has been // started, so they overlap for real. Without the hold the first could // finish before the second reached the actor (swift-main 17425 on a loaded // Mac: a = 1, b = 0), and one edge would prove nothing. await kit.source.holdsTheNextAnswer() async let first = kit.links.drain() await kit.source.untilHeld() async let second = kit.links.drain() try? await Task.sleep(nanoseconds: 200_000_000) await kit.source.release() let (a, b) = await (first, second) let calls = await kit.writer.personCalls XCTAssertEqual(calls.count, 1) XCTAssertEqual(a, 1) // The second caller awaited the first and saw its answer; the only other // right answer is 0, when it reached the actor after the first had already // settled everything. Running its own drain over the same intent is the // bug, and that writes a second edge above. XCTAssertTrue(b == a || b == 0, "the second drain answered \(b)") } func testClaimsASettlingIntentAfterTheWriteLandsNotBefore() async { // The flip. Claim-first was right while `cotton_links` ids were minted: a // drain killed between the write and the claim would have re-run and left // a DUPLICATE person edge nothing removes. Both tables derive their ids // now, so a re-run is an upsert — and the failure claim-first traded for is // real: a kill between the claim and the write loses the chip silently, // forever. let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await kit.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) let store = kit.store let seen = TroubleLog() let storageKey = key await kit.writer.observe { if let text = store.text(storageKey) { seen.note(PendingLinkTrouble(route: "duringWrite", what: text)) } } _ = await kit.links.drain() // Still in storage while the write was in flight… XCTAssertTrue(seen.read().first?.what.contains("i1") ?? false) // …and gone once it landed. XCTAssertEqual(kit.store.intents(key), []) } func testKeepsAnIntentWhenTheDrainIsKilledMidWriteAndReAppliesIt() async { let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await kit.writer.answersProject([false]) await kit.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) // A dead network must not take the capture's chip with it: the drain // reports nothing settled and does NOT throw — the caller is a fold, and a // rejection there would take the re-read with it. let first = await kit.links.drain() XCTAssertEqual(first, 0) XCTAssertEqual(kit.store.intents(key).count, 1) let second = await kit.links.drain() XCTAssertEqual(second, 1) // Four calls, not two: each pass writes the thought's own membership and // the record's, and the first pass's first call is the one that threw. let calls = await kit.writer.projectCalls XCTAssertEqual(calls.count, 4) XCTAssertEqual(kit.store.intents(key).count, 0) } func testARerunAfterAKilledDrainRewritesTheSameRowNotASibling() async { // The whole point of flipping to claim-after-write: an intent that was NOT // claimed runs again, and running again must be an upsert of the row that // is already there. Draining twice over EMPTY storage proves nothing, so // the first pass must fail. let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await kit.writer.answersPerson([false]) await kit.links.remember(inboxItemId: "i1", projectIds: [], personIds: ["per-1"]) _ = await kit.links.drain() XCTAssertEqual(kit.store.intents(key).count, 1) _ = await kit.links.drain() let calls = await kit.writer.personCalls XCTAssertGreaterThan(calls.count, 1) // it really did run twice XCTAssertEqual(Set(calls).count, 1) // at the SAME derived row XCTAssertEqual(kit.store.intents(key).count, 0) } func testKeepsOnlyTheIntentThatFailedItsNeighboursStillSettle() async { let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) // The first intent's write refuses; the second's lands. await kit.writer.answersProject([false]) await kit.links.remember(inboxItemId: "i-bad", projectIds: ["pr-1"], personIds: []) await kit.links.remember(inboxItemId: "i-good", projectIds: ["pr-2"], personIds: []) let settled = await kit.links.drain() XCTAssertEqual(settled, 1) XCTAssertEqual(kit.store.intents(key).map(\.inboxItemId), ["i-bad"]) } func testADrainWhereNothingSettledDoesNotTouchStorage() async { // The write-back is for what CHANGED. When every settling intent failed, // the list going back is the list that came out, and the records were never // persisted — so re-writing it is one round trip per failed drain buying // nothing, on a path that runs on every fold. let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await kit.writer.throwsEveryProjectWrite() await kit.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) kit.store.clearLog() let settled = await kit.links.drain() XCTAssertEqual(settled, 0) XCTAssertFalse(kit.store.logged().contains("set:\(key)")) } func testSettlesAnIntentWhosePersonNoteCouldNotBeRead() async { // A written refusal is not a failure: `personEdgeNeedsOwnPerson` refuses // this record's edges by rule, and a rule is not a transient failure — // keeping the intent would retry a decision that can only ever come out the // same way, for a week. let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "person_note", id: "pn-1")]) await kit.source.ownPersonIs(.unreadable) await kit.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: ["per-2"]) let settled = await kit.links.drain() XCTAssertEqual(settled, 1) XCTAssertEqual(kit.store.intents(key), []) } func testDoesNotWriteTheSameLinkTwiceOnASecondDrain() async { // The drain runs on every fold that touches the inbox, which is often. let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await kit.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) _ = await kit.links.drain() _ = await kit.links.drain() // One pass only: the thought's row and the to-do's, and nothing on the // second drain because the intent was settled and dropped. let calls = await kit.writer.projectCalls XCTAssertEqual(calls.count, 2) } func testDropsAnIntentThatHasWaitedLongerThanTheExpiry() async { let kit = makeKit() await kit.links.remember(inboxItemId: "i-old", projectIds: ["pr-1"], personIds: ["per-1"]) // Eight days later the capture is still unrouted: nothing will ever come. kit.clock.set(PendingLinksTests.august9) let settled = await kit.links.drain() XCTAssertEqual(settled, 0) let calls = await kit.writer.projectCalls XCTAssertEqual(calls, []) XCTAssertEqual(kit.store.intents(key), []) } func testKeepsAnIntentThatIsStillInsideTheExpiry() async { let kit = makeKit() await kit.links.remember(inboxItemId: "i-young", projectIds: ["pr-1"], personIds: []) kit.clock.set(PendingLinksTests.august6) _ = await kit.links.drain() XCTAssertEqual(kit.store.intents(key).map(\.inboxItemId), ["i-young"]) } /// "Removes the retired tag intent key on the first drain", INVERTED — and /// the inversion is the finding. /// /// The previous app swept `@cotton:pendingTags:v1` on every drain, out of /// its own key-value store. The sweep was carried across into the app /// group's `UserDefaults` suite, which is a different store in a different /// container and which no build has ever written that key into — so the /// cleanup could never fire and the test proved only that a key the test /// itself had just planted could be removed. /// /// The sweep is gone rather than corrected, because there is nothing left /// to sweep: that key-value store went with the previous app and no reader /// remains that a stale tag intent could reach. What this pins is that the /// drain does not touch a key that is not its own. func testTouchesNoKeyButItsOwn() async { let kit = makeKit() kit.store.put(retiredKey, raw: "[{\"inboxItemId\":\"old\",\"tagIds\":[\"t\"]}]") await kit.links.remember(inboxItemId: "i-1", projectIds: ["pr-1"], personIds: []) _ = await kit.links.drain() XCTAssertTrue( kit.store.has(retiredKey), "the drain reached into a key that is not its own" ) } func testSurvivesACorruptIntentListRatherThanFailingACapture() async { let kit = makeKit() kit.store.put(key, raw: "{not json") let settled = await kit.links.drain() XCTAssertEqual(settled, 0) // …and SAYS so. Every chip this device was holding just went, and a silent // empty list is the fallback the repo bans. XCTAssertTrue(kit.troubles.read().contains { $0.route == "cotton.pendingLinks.read" }) } func testSettlesACaptureTheOwnerFiledByHand() async { // Filing by hand writes `routed_kind` + `routed_id`, never // `routed_records` — so a drain that read only the list watched the chip // wait out its week and be deleted. The server has read both shapes since // the plan era; so does this. let kit = makeKit() await kit.source.filedByHand(kind: "todo", id: "todo-9") await kit.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) let settled = await kit.links.drain() XCTAssertEqual(settled, 1) let calls = await kit.writer.projectCalls XCTAssertTrue( calls.contains( RecordingLinkWriter.ProjectCall(projectSlug: "pr-1", kind: "todo", id: "todo-9") ) ) XCTAssertEqual(kit.store.intents(key), []) } func testDropsAnIntentWhoseWriteHasBeenRefusingSinceBeforeTheExpiry() async { // The expiry used to guard only the not-yet-routed branch, so an intent // whose write kept refusing was retried on every fold forever — and each // retry re-stated a link the person may have removed in between. let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await kit.writer.throwsEveryProjectWrite() await kit.links.remember(inboxItemId: "i-stuck", projectIds: ["pr-1"], personIds: []) kit.clock.set(PendingLinksTests.august2) _ = await kit.links.drain() XCTAssertEqual(kit.store.intents(key).map(\.inboxItemId), ["i-stuck"]) kit.clock.set(PendingLinksTests.august9) _ = await kit.links.drain() XCTAssertEqual(kit.store.intents(key), []) } // MARK: syncPendingLinkProjects // // R57 — the plan the person re-sends is the truth for the drain too. The // intent was written when the capture was made, out of the chips the dock held // then. A chip taken off in the plan editor before the re-commit must not come // back when the drain finally finds the records. // MARK: the drain refuses to guess func testWritesNoPersonEdgeForANoteWhoseOwnPersonCannotBeRead() async { // `isSelfPersonEdge` is false for every person when the own person is // unknown, so a failed read would let the SELF edge through — the one // duplicate the whole rule exists to prevent. Not knowing means not // writing. let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "person_note", id: "pn-1")]) await kit.source.ownPersonIs(.unreadable) await kit.links.remember( inboxItemId: "i1", projectIds: [], personIds: ["per-1", "per-2"] ) _ = await kit.links.drain() let calls = await kit.writer.personCalls XCTAssertEqual(calls, []) } func testStillWritesTheOtherRecordsEdgesOneUnreadableNoteIsNotAStall() async { let kit = makeKit() await kit.source.routed([ RoutedRecord(kind: "person_note", id: "pn-1"), RoutedRecord(kind: "todo", id: "todo-1"), ]) await kit.source.ownPersonIs(.unreadable) await kit.links.remember(inboxItemId: "i1", projectIds: [], personIds: ["per-1"]) _ = await kit.links.drain() let calls = await kit.writer.personCalls XCTAssertEqual( calls, [ RecordingLinkWriter.PersonCall( fromKind: "todo", fromId: "todo-1", toPersonId: "per-1" ) ] ) } // MARK: the in-flight guard is per identity func testKeepsEachIdentitysIntentsInItsOwnList() async { // Two identities are two different files. One person's `#Meri` chip must // never be applied inside somebody else's workspace, and the list is the // only thing standing between them — which is structural here, because an // instance IS an identity and each one derives its own key. let store = MemoryLinkStore() let one = makeKit(user: "u1", workspace: "ws-1", store: store) let two = makeKit(user: "u2", workspace: "ws-2", store: store) await one.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await two.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await one.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) _ = await two.links.drain() let otherCalls = await two.writer.projectCalls XCTAssertEqual(otherCalls, []) _ = await one.links.drain() let ownCalls = await one.writer.projectCalls XCTAssertTrue(ownCalls.contains { $0.projectSlug == "pr-1" }) } func testDoesNotHandASecondIdentitysDrainTheFirstOnesPromise() async { let store = MemoryLinkStore() let one = makeKit(user: "u1", workspace: "ws-1", store: store) let two = makeKit(user: "u2", workspace: "ws-2", store: store) await one.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await two.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await one.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) await two.links.remember(inboxItemId: "i2", projectIds: ["pr-2"], personIds: []) async let first = one.links.drain() async let second = two.links.drain() _ = await (first, second) let oneCalls = await one.writer.projectCalls let twoCalls = await two.writer.projectCalls XCTAssertTrue(oneCalls.allSatisfy { $0.projectSlug == "pr-1" }) XCTAssertTrue(twoCalls.allSatisfy { $0.projectSlug == "pr-2" }) XCTAssertFalse(oneCalls.isEmpty) XCTAssertFalse(twoCalls.isEmpty) } func testStillCollapsesTwoDrainsOfTheSameIdentityIntoOne() async { let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await kit.links.remember(inboxItemId: "i1", projectIds: [], personIds: ["per-1"]) async let first = kit.links.drain() async let second = kit.links.drain() _ = await (first, second) let calls = await kit.writer.personCalls XCTAssertEqual(calls.count, 1) } // MARK: what this port added func testAProjectTheAppCannotNameKeepsTheIntentRatherThanDroppingTheChip() async { // No TypeScript twin: `link_to_project` resolves its `project` argument // through the SLUG column alone, and a `#` chip carries the project's id. // A name the app has not loaded is a fact it does not have YET, not a // decision — so the write is reported and the intent waits. let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "todo", id: "todo-1")]) await kit.source.namesNoProjects() await kit.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) let settled = await kit.links.drain() XCTAssertEqual(settled, 0) XCTAssertEqual(kit.store.intents(key).map(\.inboxItemId), ["i1"]) XCTAssertTrue(kit.troubles.read().contains { $0.what.contains("pr-1") }) let calls = await kit.writer.projectCalls XCTAssertEqual(calls, []) } func testARoutedKindThisBuildDoesNotKnowIsReportedAndSteppedOver() async { // No TypeScript twin: the union was total at compile time there and the // kind arrives as a wire string here. A build cannot learn a kind by // trying again, so this is a written refusal and NOT a failure — the // intent settles rather than looping for a week. let kit = makeKit() await kit.source.routed([RoutedRecord(kind: "hologram", id: "x-1")]) await kit.links.remember(inboxItemId: "i1", projectIds: ["pr-1"], personIds: []) let settled = await kit.links.drain() XCTAssertEqual(settled, 1) XCTAssertTrue(kit.troubles.read().contains { $0.what.contains("hologram") }) // The thought's own membership still landed: it does not depend on the // record, which is the whole reason it is written outside `applyOne`. let calls = await kit.writer.projectCalls XCTAssertEqual( calls, [RecordingLinkWriter.ProjectCall(projectSlug: "pr-1", kind: "thought", id: "i1")] ) } func testAPersonChipIsKeptWhileNoToolCanWriteAPersonEdge() async { // No TypeScript twin, and the finding this port has to carry: nothing in // `cotton-tools`' catalogue writes `cotton_links`, so the shipping writer // refuses. The refusal KEEPS the intent — the chip waits in storage until // the tool exists or the expiry takes it, rather than being dropped // silently, which is the one outcome this file exists to prevent. let core = ScriptedCore([CottonMethod.write: .ok("{}")]) let writer = CorePendingLinkWriter(core: core) do { try await writer.linkPerson( from: LinkRef(kind: .todo, id: "todo-1"), toPersonId: "per-1" ) XCTFail("a person edge cannot be written yet and must say so") } catch { XCTAssertEqual(error as? PendingLinkGap, .noPersonEdgeWriter) } let asked = await core.methodsCalled() XCTAssertEqual(asked, [], "no tool name is invented for a verb the catalogue lacks") } // MARK: filedRecords, on its own // MARK: the two decisions, held total }