Transit

T-2455 scoped comment-fetch review

At a glance

  • Selected captures materialize only the logical owner-ID comment closure.
  • Full revisions and duplicate physical-owner evidence remain complete.
  • Synthetic 5,002→2 materialized rows; median 134.8→31.2 ms.

Verdict

Ready to push

78 targeted macOS tests and lint passed. Four source review areas found no blockers; live deployment and uptime observation remain separate.

Tests

Pass rate: 100% (78 of 78)

New tests: 9

Diff coverage: n/a

Jump to tests →

Three-level explanation

Fetch comments needed by the requested tasks instead of loading every comment.

Push the existing logical owner UUID filter into the saved SwiftData descriptor; retain complete portfolio/orphan coverage.

Preserve canonical logical identity and distinct physical ownership, history fences, saved-only contexts, budgets and physical cleanup. A synchronous fetch may outlive timeout publication.

Important changes — detailed

Filter before comment materialization

Transit/Transit/MCP/Reads/MCPReadCommentFetch.swift

Why it matters. Avoid unrelated comments while preserving logical-ID duplicates.

What to look at. MCPReadCommentFetch.descriptor

Rationale. The predicate matches the existing post-fetch logical owner membership; portfolio evidence remains unrestricted.

Prove frozen records and revisions remain equivalent

Transit/TransitTests/MCPScopedCommentFetchTests.swift

Why it matters. Selected-read output and revision evidence are safety-critical.

What to look at. Nine on-disk regression and performance cases

Takeaway. Count actual fetched rows and compare canonical output rather than asserting unstable timing thresholds.

Tests

Source: local run at 2026-10-14T13:42:53.412645+00:00 · snapshot 430046ce9abac5b2286c00e0a03ca1b88f5b38d3

Baseline: none

Execution: passed · JUnit: 1 file · Coverage: none · Baseline: absent

Coverage scope: as the project configures it

Totals: 78 passed · 0 failed · 0 skipped · 0 errored · 0 flaky

New and removed tests

Derived by declaration name, from the diff (no baseline run).

Blast radius

Files that import a changed file on the left, changed files in the centre, files a changed file imports on the right. Snapshot working-tree against base origin/main.

addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

11 files: 6 code · 5 docs. Click to expand.

Code (6)

Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swift Modified
diff --git a/Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swift b/Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swiftindex 63bd75e4..3dc5253b 100644--- a/Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swift+++ b/Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swift@@ -26,7 +26,7 @@ final class MCPReadCaptureBuilder: MCPReadCaptureSource {     private let metadata: (Date, MCPReadCaptureBoundary) -> ReadCaptureMetadata     private let fetchTasks: (ModelContext) throws -> [TransitTask]     private let fetchMilestones: (ModelContext) throws -> [Milestone]-    private let fetchComments: (ModelContext) throws -> [Comment]+    private let fetchComments: (ModelContext, FetchDescriptor<Comment>) throws -> [Comment]     private let afterProjects: () throws -> Void      init(@@ -42,8 +42,8 @@ final class MCPReadCaptureBuilder: MCPReadCaptureSource {                                          recentImportThresholdMs: 30_000),                 read: ReadExecutionMetadata(policy: .cached, refreshOutcome: .notRequested, budgetMs: 5_000))         },-        fetchComments: @escaping (ModelContext) throws -> [Comment] = {-            try $0.fetch(FetchDescriptor<Comment>())+        fetchComments: @escaping (ModelContext, FetchDescriptor<Comment>) throws -> [Comment] = {+            try $0.fetch($1)         },         afterProjects: @escaping () throws -> Void = {},         fetchTasks: @escaping (ModelContext) throws -> [TransitTask] = {@@ -307,7 +307,8 @@ private extension MCPReadCaptureBuilder {         // the full orphan/comment diagnostic domain, including an empty task domain.         guard request.selection.requiredEntities.0 && needed,               request.completeness == .completePortfolio || !bodyTasks.isEmpty else { return [] }-        return try fetchComments(context)+        let ids = request.completeness == .selectedRead ? Array(Set(bodyTasks.map(\.id))) : nil+        return try fetchComments(context, MCPReadCommentFetch.descriptor(taskIDs: ids))     }      private func key(_ model: some PersistentModel) throws -> LocalRecordKey {
Transit/Transit/MCP/Reads/MCPReadCommentFetch.swift Added
diff --git a/Transit/Transit/MCP/Reads/MCPReadCommentFetch.swift b/Transit/Transit/MCP/Reads/MCPReadCommentFetch.swiftnew file mode 100644index 00000000..40d261c2--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadCommentFetch.swift@@ -0,0 +1,21 @@+#if os(macOS)+import Foundation+import SwiftData++@MainActor+enum MCPReadCommentFetch {+    /// Nil retains complete-portfolio orphan coverage. Selected reads preserve+    /// the existing logical-ID closure, including foreign physical duplicates;+    /// canonical revisions and physical comment ownership are indexed afterward.+    static func descriptor(taskIDs: [UUID]?) -> FetchDescriptor<Comment> {+        var descriptor = FetchDescriptor<Comment>()+        if let ids = taskIDs {+            descriptor.predicate = #Predicate<Comment> { comment in+                comment.task.flatMap { ids.contains($0.id) } ?? false+            }+        }+        descriptor.includePendingChanges = false+        return descriptor+    }+}+#endif
Transit/TransitTests/MCPReadCaptureBuilderTests.swift Modified
diff --git a/Transit/TransitTests/MCPReadCaptureBuilderTests.swift b/Transit/TransitTests/MCPReadCaptureBuilderTests.swiftindex 9ec5f5bf..877b25c1 100644--- a/Transit/TransitTests/MCPReadCaptureBuilderTests.swift+++ b/Transit/TransitTests/MCPReadCaptureBuilderTests.swift@@ -156,7 +156,7 @@ struct MCPReadCaptureBuilderTests {     @Test func requiredCommentFailureIsNotAnEmptySuccess() throws {         let fixture = try TestModelContainer()         let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,-                                            fetchComments: { _ in throw CaptureFixtureError.fetchFailed })+                                            fetchComments: { _, _ in throw CaptureFixtureError.fetchFailed })         #expect(throws: MCPReadCaptureError.storageFailure) { try builder.capture(portfolioRequest()) }         let projects = try builder.capture(ReadCaptureRequest(projectSelectors: nil, selection: .projects,                                                               completeness: .selectedRead, includeComments: true))@@ -173,7 +173,7 @@ struct MCPReadCaptureBuilderTests {         fixture.context.insert(comment)         try fixture.context.save()         let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,-            fetchComments: { context in+            fetchComments: { context, _ in                 let comments = try context.fetch(FetchDescriptor<Transit.Comment>())                 comments.first?.creationDate = Date(timeIntervalSince1970: .infinity)                 return comments
Transit/TransitTests/MCPReadProjectionTests.swift Modified
diff --git a/Transit/TransitTests/MCPReadProjectionTests.swift b/Transit/TransitTests/MCPReadProjectionTests.swiftindex 92caf566..9e49ec39 100644--- a/Transit/TransitTests/MCPReadProjectionTests.swift+++ b/Transit/TransitTests/MCPReadProjectionTests.swift@@ -18,7 +18,7 @@ struct MCPReadProjectionTests {         task.name = "Unsaved task"         project.name = "Unsaved project"         let source = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,-                                          fetchComments: { _ in throw CocoaError(.fileReadUnknown) })+                                          fetchComments: { _, _ in throw CocoaError(.fileReadUnknown) })         let view = try source.capture(request(full: false))         let results = try MCPReadProjection.tasks(view, request: query(), arguments: [:])         #expect(try bytes(results[0]) == bytes(expected))
Transit/TransitTests/MCPReadServiceTests.swift Modified
diff --git a/Transit/TransitTests/MCPReadServiceTests.swift b/Transit/TransitTests/MCPReadServiceTests.swiftindex 028db1d2..da7c05d2 100644--- a/Transit/TransitTests/MCPReadServiceTests.swift+++ b/Transit/TransitTests/MCPReadServiceTests.swift@@ -89,7 +89,7 @@ struct MCPReadServiceTests {         try fixture.context.save()         task.name = "Unsaved"         let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,-                                          fetchComments: { _ in throw CocoaError(.fileReadUnknown) })+                                          fetchComments: { _, _ in throw CocoaError(.fileReadUnknown) })         let view = try builder.capture(ReadCaptureRequest(projectSelectors: nil, selection: .projectCatalog,                                                          completeness: .selectedRead, includeComments: false))         let projects = try MCPReadProjection.projects(view)@@ -188,7 +188,7 @@ struct MCPReadServiceTests {         try fixture.context.save()         var commentsFetched = false         let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,-            fetchComments: { _ in commentsFetched = true; throw CocoaError(.fileReadUnknown) })+            fetchComments: { _, _ in commentsFetched = true; throw CocoaError(.fileReadUnknown) })         let service = MCPReadService(source: Source(fixture, builder: builder), monitor: MCPImportEvidenceMonitor(             syncActive: false, storeIdentifier: nil), snapshots: MCPTaskQuerySnapshotStore())         var arguments: [String: Any] = ["project": "P", "detailLevel": "full", "includeComments": true, "limit": 100]@@ -266,7 +266,7 @@ extension MCPReadServiceTests {         try fixture.context.save()         var commentsFetched = false         let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,-            fetchComments: { _ in commentsFetched = true; throw CocoaError(.fileReadUnknown) })+            fetchComments: { _, _ in commentsFetched = true; throw CocoaError(.fileReadUnknown) })         let request = ReadCaptureRequest(projectSelectors: scoped ? [.id(project.id)] : nil,             selection: .portfolio, completeness: .completePortfolio, includeComments: false)         #expect(throws: MCPReadCaptureError.storageFailure) { try builder.capture(request) }
Transit/TransitTests/MCPScopedCommentFetchTests.swift Added
diff --git a/Transit/TransitTests/MCPScopedCommentFetchTests.swift b/Transit/TransitTests/MCPScopedCommentFetchTests.swiftnew file mode 100644index 00000000..cf12275b--- /dev/null+++ b/Transit/TransitTests/MCPScopedCommentFetchTests.swift@@ -0,0 +1,243 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPScopedCommentFetchTests {+    @Test func singleFullReadMaterializesOnlySelectedCommentsAndPreservesRevision() throws {+        let data = try fixture(unrelatedComments: 1_000)+        var fetched = 0+        let builder = MCPReadCaptureBuilder(container: data.owner.container, fetchComments: { context, descriptor in+            let values = try context.fetch(descriptor)+            fetched += values.count+            return values+        })+        let request = selected([data.tasks[0].id], comments: false)+        let view = try builder.capture(request)+        #expect(fetched == 2) // Regression: the old unscoped descriptor materializes all 1,002 rows.+        #expect(view.comments.count == 2)+        let task = try #require(view.tasks.first { $0.id == data.tasks[0].id })+        #expect(task.revision == (try MCPRecordSnapshot.task(data.tasks[0], in: data.owner.context).revision))+        #expect(task.requestedCommentRecordsJSON == nil)+        #expect(!data.owner.context.hasChanges)+    }++    @Test func batchAndDuplicateLogicalOwnersMatchUnscopedCapture() throws {+        let data = try fixture(unrelatedComments: 6)+        data.tasks[2].id = data.tasks[0].id+        data.comments[2].id = data.comments[0].id+        try data.owner.context.save()+        for include in [false, true] {+            let request = selected([data.tasks[0].id, data.tasks[1].id], comments: include)+            try compareWithUnscoped(request, owner: data.owner)+        }+    }++    @Test func onePhysicalOwnerStillIncludesForeignDuplicateLogicalComments() throws {+        let data = try fixture(unrelatedComments: 6)+        let foreign = Project(name: "Foreign", description: "", gitRepo: nil, colorHex: "red")+        data.owner.context.insert(foreign)+        data.tasks[2].id = data.tasks[0].id+        data.tasks[2].project = foreign+        try data.owner.context.save()+        let request = ReadCaptureRequest(projectSelectors: [.id(data.project.id)],+            selection: .tasks(detail: .fullRecord), completeness: .selectedRead, includeComments: true,+            selectTaskBodies: { values in Set(values.filter { $0.permanentDisplayId == 1 }.map(\.physicalKey)) })+        let view = try MCPReadCaptureBuilder(container: data.owner.container).capture(request)+        let task = try #require(view.tasks.first { $0.permanentDisplayId == 1 })+        #expect(task.commentKeys.count == 2)+        #expect(view.comments.count == 5) // Both physical owners belong to the canonical logical-ID evidence.+        #expect(view.comments.contains { $0.taskKey != task.physicalKey })+        #expect(task.revision == (try MCPRecordSnapshot.task(data.tasks[0], in: data.owner.context).revision))+        try compareWithUnscoped(request, owner: data.owner)+    }++    @Test func fullBulkAndSummaryCommentRequestsKeepEquivalentEvidence() throws {+        let data = try fixture(unrelatedComments: 6)+        let bulk = ReadCaptureRequest(projectSelectors: nil, selection: .tasks(detail: .fullRecord),+                                      completeness: .selectedRead, includeComments: true)+        try compareWithUnscoped(bulk, owner: data.owner)+        let id = data.tasks[0].id+        let summary = ReadCaptureRequest(projectSelectors: nil, selection: .tasks(detail: .summary),+            completeness: .selectedRead, includeComments: true,+            selectTaskBodies: { values in Set(values.filter { $0.id == id }.map(\.physicalKey)) })+        try compareWithUnscoped(summary, owner: data.owner)+        #expect(try MCPReadCaptureBuilder(container: data.owner.container).capture(summary).comments.count == 2)+    }++    @Test func reparentedEditedOrphanAndPendingCommentsKeepSavedSemantics() throws {+        let data = try fixture(unrelatedComments: 6)+        let request = selected([data.tasks[0].id], comments: true)+        let initial = try MCPReadCaptureBuilder(container: data.owner.container).capture(request)+        let oldRevision = initial.tasks.first { $0.id == data.tasks[0].id }?.revision+        data.comments[0].task = data.tasks[1]+        data.comments[1].task = nil+        data.comments[2].task = data.tasks[0]+        data.comments[2].content = "Saved edit"+        try data.owner.context.save()+        let savedRevision = try MCPRecordSnapshot.task(data.tasks[0], in: data.owner.context).revision+        #expect(savedRevision != oldRevision)+        data.comments[2].content = "Pending edit"+        data.comments[3].task = data.tasks[0]+        let view = try MCPReadCaptureBuilder(container: data.owner.container).capture(request)+        #expect(view.tasks.first { $0.id == data.tasks[0].id }?.revision == savedRevision)+        #expect(view.comments.count == 1 && view.comments.first?.content == "Saved edit")+        try compareWithUnscoped(request, owner: data.owner)+        #expect(data.owner.context.hasChanges)+    }++    @Test func completePortfoliosKeepOrphansAndProjectIdentityClosure() throws {+        let data = try fixture(unrelatedComments: 6)+        data.comments[0].task = nil+        try data.owner.context.save()+        for selectors: [ReadProjectSelector]? in [nil, [.id(data.project.id)]] {+            let request = ReadCaptureRequest(projectSelectors: selectors, selection: .portfolio,+                                             completeness: .completePortfolio, includeComments: true)+            var fetched = 0+            let view = try MCPReadCaptureBuilder(container: data.owner.container,+                fetchComments: { context, descriptor in+                    let values = try context.fetch(descriptor)+                    fetched += values.count+                    return values+                }).capture(request)+            #expect(fetched == data.comments.count)+            #expect(view.comments.contains { $0.taskKey == nil })+            try compareWithUnscoped(request, owner: data.owner)+        }+    }++    @Test func emptySelectionAndSummaryWithoutCommentsDoNotFetch() throws {+        let data = try fixture(unrelatedComments: 2)+        var calls = 0+        let builder = MCPReadCaptureBuilder(container: data.owner.container, fetchComments: { _, _ in+            calls += 1+            throw CocoaError(.fileReadUnknown)+        })+        let empty = try builder.capture(selected([UUID()], comments: false))+        #expect(empty.comments.isEmpty)+        let summary = ReadCaptureRequest(projectSelectors: nil, selection: .tasks(detail: .summary),+                                         completeness: .selectedRead, includeComments: false)+        #expect(try builder.capture(summary).comments.isEmpty)+        #expect(calls == 0)+        #expect(throws: MCPReadCaptureError.storageFailure) {+            try builder.capture(selected([data.tasks[0].id], comments: false))+        }+    }++    @Test func savedCommentChangeDuringFetchFailsHistoryFence() throws {+        let data = try fixture(unrelatedComments: 2)+        let builder = MCPReadCaptureBuilder(container: data.owner.container, fetchComments: { context, descriptor in+            let values = try context.fetch(descriptor)+            data.comments[0].content = "Concurrent saved edit"+            try data.owner.context.save()+            return values+        })+        #expect(throws: MCPReadCaptureError.incoherentCapture) {+            try builder.capture(selected([data.tasks[0].id], comments: false))+        }+        try compareWithUnscoped(selected([data.tasks[0].id], comments: false), owner: data.owner)+    }++    @Test func syntheticVolumeComparesScopedAndUnscopedMaterialization() throws {+        let data = try fixture(unrelatedComments: 5_000)+        let request = selected([data.tasks[0].id], comments: false)+        var scopedRows: [Int] = []+        var oldRows: [Int] = []+        let scoped = MCPReadCaptureBuilder(container: data.owner.container, fetchComments: { context, descriptor in+            let values = try context.fetch(descriptor)+            scopedRows.append(values.count)+            return values+        })+        let old = MCPReadCaptureBuilder(container: data.owner.container, fetchComments: { context, _ in+            let values = try context.fetch(FetchDescriptor<Transit.Comment>())+            oldRows.append(values.count)+            return values+        })+        let warm = try scoped.capture(request)+        _ = try old.capture(request)+        var scopedMs: [Double] = []+        var oldMs: [Double] = []+        for round in 0..<4 {+            for useScoped in round.isMultiple(of: 2) ? [true, false] : [false, true] {+                let start = ContinuousClock.now+                let view = try (useScoped ? scoped : old).capture(request)+                let elapsed = MCPReadTiming.seconds(start.duration(to: .now)) * 1_000+                if useScoped { scopedMs.append(elapsed) } else { oldMs.append(elapsed) }+                #expect(view.tasks.map(\.selectedRecordJSON) == warm.tasks.map(\.selectedRecordJSON))+                #expect(view.tasks.map(\.revision) == warm.tasks.map(\.revision))+                #expect(view.comments.map(\.selectedRecordJSON) == warm.comments.map(\.selectedRecordJSON))+            }+        }+        #expect(scopedRows == Array(repeating: 2, count: 5))+        #expect(oldRows == Array(repeating: 5_002, count: 5))+        let metrics: [String: Any] = ["scopedRows": scopedRows, "baselineRows": oldRows,+                                      "scopedMs": scopedMs, "baselineMs": oldMs]+        let encoded = try JSONSerialization.data(withJSONObject: metrics, options: [.sortedKeys])+        let text = try #require(String(data: encoded, encoding: .utf8))+        print("T2455_SCOPED_COST \(text)")+        #expect(!data.owner.context.hasChanges)+    }++    private func selected(_ ids: [UUID], comments: Bool) -> ReadCaptureRequest {+        ReadCaptureRequest(projectSelectors: nil, selection: .tasks(detail: .fullRecord),+            completeness: .selectedRead, includeComments: comments, selectTaskBodies: { values in+                Set(values.filter { ids.contains($0.id) }.map(\.physicalKey))+            })+    }++    private func compareWithUnscoped(_ request: ReadCaptureRequest, owner: TestModelContainer) throws {+        let scoped = try MCPReadCaptureBuilder(container: owner.container).capture(request)+        let old = try MCPReadCaptureBuilder(container: owner.container, fetchComments: { context, _ in+            try context.fetch(FetchDescriptor<Transit.Comment>())+        }).capture(request)+        #expect(scoped.tasks.map(\.physicalKey) == old.tasks.map(\.physicalKey))+        for task in scoped.tasks {+            let previous = try #require(old.tasks.first { $0.physicalKey == task.physicalKey })+            #expect(task.revision == previous.revision)+            #expect(task.selectedRecordJSON == previous.selectedRecordJSON)+            #expect(task.commentKeys == previous.commentKeys)+            #expect(task.requestedCommentRecordsJSON == previous.requestedCommentRecordsJSON)+        }+        #expect(scoped.comments.map(\.physicalKey) == old.comments.map(\.physicalKey))+        #expect(scoped.comments.map(\.selectedRecordJSON) == old.comments.map(\.selectedRecordJSON))+    }++    private struct Fixture {+        let owner: TestModelContainer+        let project: Project+        let tasks: [TransitTask]+        let comments: [Transit.Comment]+    }++    private func fixture(unrelatedComments: Int) throws -> Fixture {+        let schema = Schema([Project.self, TransitTask.self, Transit.Comment.self, Milestone.self,+                             SyncHeartbeat.self, MCPWriteReceipt.self, TaskLinkOccurrence.self,+                             TaskLinkRemovalEvidence.self, TaskConsolidationEvent.self])+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+        let config = ModelConfiguration(schema: schema, url: directory.appendingPathComponent("fixture.store"),+                                        cloudKitDatabase: .none)+        let owner = try TestModelContainer(schema: schema, configurations: [config])+        owner.context.autosaveEnabled = false+        let project = Project(name: "Synthetic", description: "", gitRepo: nil, colorHex: "blue")+        owner.context.insert(project)+        let tasks = (1...3).map { index in+            let task = TransitTask(name: "Task \(index)", type: .feature, project: project,+                                   displayID: .permanent(index))+            owner.context.insert(task)+            return task+        }+        var comments: [Transit.Comment] = []+        for index in 0..<(2 + unrelatedComments) {+            let comment = Transit.Comment(content: "Comment \(index)", authorName: "Fixture", isAgent: true,+                                          task: tasks[index < 2 ? 0 : (index % 2 + 1)])+            owner.context.insert(comment)+            comments.append(comment)+        }+        try owner.context.save()+        return Fixture(owner: owner, project: project, tasks: tasks, comments: comments)+    }+}+#endif

Docs (5)

CHANGELOG.md Modified
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b47dc591..be598564 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -71,6 +71,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - T-1803: `UpdateStatusIntent` now includes a missing requested `displayId` in its `TASK_NOT_FOUND` hint (`No task with displayId N`), while missing UUIDs retain the existing generic lookup hint and malformed identifiers, duplicate IDs, status validation, and atomic mutation behavior remain unchanged. ### Fixed +- T-2455: Scope selected-read comment fetches to selected logical task IDs, preserving full revisions, duplicate physical ownership and complete-portfolio orphan coverage. Avoid materializing unrelated store comments without changing read deadlines. Live long-uptime verification remains pending.+ - T-63: Align detached publication-test producers with their user-initiated semaphore waiters, eliminating observed fixture priority-inversion warnings while preserving publication, cleanup and timing assertions. - T-2380: Reuse validated guard bindings only within synchronous write phases, revalidate after suspension, and discard snapshots on mutation failure. Document safe recovery without deleting uncertain bindings or resetting local scope. - T-2380: Reconcile retry guards in one validated pass, reject incomplete saved outcomes before replay, and preserve exact integer validation. Added malformed-result regressions and corrected MCP safety examples.
docs/mcp-read-contract.md Modified
diff --git a/docs/mcp-read-contract.md b/docs/mcp-read-contract.mdindex 58d144d0..badb1884 100644--- a/docs/mcp-read-contract.md+++ b/docs/mcp-read-contract.md@@ -4,6 +4,8 @@ Covered macOS reads describe a completed capture of **saved local data**. A capt  The server allows five seconds from the read's original admission through complete response preparation. Import observation, store capture, transformation and encoding share that budget. An internal 4,850 ms selection cutoff reserves time for response completion. Client/network delivery time is outside this server budget. Eight unfinished physical reads are admitted per process; listener restart does not reset that count. A timeout ends delivery, while its physical work retains capacity until cleanup. Native saved consolidation history and macOS MCP reads share this app-lifetime capacity and original deadline. Listener stop/restart closes only that listener's admission and delivery; it does not disable native history or release unfinished workers. +Selected reads fetch comment evidence by the selected tasks’ logical UUIDs, including comments owned by duplicate physical tasks with those UUIDs. Full revisions cover all those comments even when `includeComments:false` hides their payload. Complete-portfolio captures retain the full comment domain needed for orphan and ownership diagnostics. Every new capture resolves saved ownership again within the existing history fence.+ ## Policy and import limits  New reads default to `readPolicy: "refresh_if_needed"`. This can observe positively applicable imports already in flight for at most two seconds within the remaining total budget. The current SwiftData integration has no supported force-pull or provable import-to-capture visibility mechanism; it reports `unavailable` refresh and honest `unknown` freshness when applicability cannot be established. Heartbeat writes and notification arrival are not import proof.
specs/bugfixes/scoped-comment-fetch/implementation.md Added
diff --git a/specs/bugfixes/scoped-comment-fetch/implementation.md b/specs/bugfixes/scoped-comment-fetch/implementation.mdnew file mode 100644index 00000000..efe092dc--- /dev/null+++ b/specs/bugfixes/scoped-comment-fetch/implementation.md@@ -0,0 +1,17 @@+# Scoped comment-fetch implementation++## Beginner++Reading one task previously loaded comments for every task and discarded unrelated ones. The capture now asks storage for comments whose owners share the selected task IDs. It still loads all comments needed to calculate the selected tasks' revisions, even when comment text is hidden from the response.++## Intermediate++`MCPReadCaptureBuilder.commentEvidence` resolves body tasks inside the existing saved capture boundary. Selected reads pass their unique logical UUIDs to `MCPReadCommentFetch.descriptor`; complete portfolios pass nil and retain the unrestricted fetch. The descriptor filters the optional owner relationship before SwiftData materializes comments. The existing post-filter/indexing and record/revision creation remain in place. The injection seam receives the descriptor so fixtures can count fetched rows and compare with the former unrestricted query.++## Expert++The predicate intentionally uses logical UUIDs rather than physical task IDs: canonical revision inputs group by logical owner, while physical comment keys remain indexed separately. A foreign duplicate owner must remain included even when its physical task is outside the selected body/project. Orphan evidence remains available to complete-portfolio diagnostics. New contexts, disabled autosave, explicit saved-only descriptor, persistent-history before/after checks, selected body resolution, frozen replay, failure categories, budget and physical cleanup remain unchanged. A synchronous fetch may continue after timeout selection; this patch reduces unnecessary materialization rather than promising preemption.++## Completeness assessment++The implementation removes unrelated comment materialization for selected captures and preserves the old query's retained evidence in the isolated fixtures. It does not optimize whole-store task identity/graph capture or the independent empty-originals task refetch. It does not prove that CloudKit overlap or process uptime caused the observed incident. Deployed long-uptime verification remains a separate user-controlled step.
specs/bugfixes/scoped-comment-fetch/report.md Added
diff --git a/specs/bugfixes/scoped-comment-fetch/report.md b/specs/bugfixes/scoped-comment-fetch/report.mdnew file mode 100644index 00000000..fade8130--- /dev/null+++ b/specs/bugfixes/scoped-comment-fetch/report.md@@ -0,0 +1,48 @@+# T-2455: Scope selected-read comment fetches++## Problem and evidence++Full selected task reads currently fetch every store comment before filtering to selected logical task IDs. A live read timed out on 2026-10-14 after a healthy one-hour baseline; captured stacks later showed the MainActor capture inside this whole-store SwiftData/CoreData comment materialization. This identifies a concrete unnecessary-work path, not proof of an uptime leak, CloudKit causation, or a complete explanation of every historical timeout.++The user explicitly approved implementing this scoped fetch after the read-only investigation. The installed app is not changed by this branch. Existing ticket T-2455 remains the tracking item; no duplicate ticket is needed.++## Scope and invariants++- Move the existing selected-read logical-owner-ID filter into the comment store fetch. Preserve every physical comment owned by any task with a selected logical ID, including duplicate task UUIDs and duplicate comment UUIDs.+- Complete-portfolio reads retain the broad comment domain, including orphan diagnostics and scoped portfolio identity closure.+- includeComments controls output bodies only. Full revisions still require complete selected-task comment state.+- Preserve saved-only reads, persistent history fences, fresh captures after edits/reparenting, revision computation, snapshot identity, frozen replay, typed storage failures, physical worker cleanup and existing deadlines.+- Do not change stores/schema, sync settings, timeouts, permit counts or installed app lifecycle. No live store copies or cloud experiments.++## Investigation checkpoint++The comment-fetch injection now receives its FetchDescriptor so isolated tests can observe actual materialized rows. Before optimization it still receives the original unrestricted descriptor. Existing failure-injection tests are mechanically adapted to the descriptor seam.++Regression fixtures use temporary on-disk stores with all nine entities, CloudKit disabled and production history fencing. The primary regression requires exactly two selected comment rows despite 1,000 unrelated comments. Additional parity checks cover batches, duplicate logical owners/comment IDs, edited/reparented/orphan/pending comments, portfolio coverage, empty/summary reads and concurrent saved changes.++## Resolution and validation++Red checkpoint: six initial regression tests executed; five passed and the selected-row assertion failed as expected (1,002 fetched versus two required). The expanded duplicate-owner, bulk/summary and performance fixtures then passed against the scoped predicate. No long-uptime resolution is claimed from synthetic tests.+++### Final implementation++Selected reads construct a store predicate over unique selected logical task IDs through `MCPReadCommentFetch`. Complete portfolios retain the unrestricted descriptor. Both use saved-only fetching. Existing logical scope filtering, canonical/physical comment indexing, selected record/revision construction and history boundary checks are unchanged. The descriptor seam supports observing real fetched rows; existing injected failure/serialization tests ignore the new descriptor argument intentionally.++### Validation++- Red: one expected materialization assertion failed among six initial tests (1,002 rows fetched instead of two); the other five passed.+- Green: all nine new tests and 69 surrounding targeted macOS tests passed, zero failures/skips (78 total). Includes capture, selected/portfolio scope, ownership, projection, history fences, consolidation, snapshot/replay and coordinator cleanup.+- Lint: zero violations across 751 Swift files and host validation guards. No broad UI rerun or full-suite claim. The product path and new tests are macOS-only; no iOS behavior changes are introduced.+- Four targeted source review areas found no blockers. A review-requested test selects one physical duplicate owner across projects and preserves both owners' logical canonical evidence.+- Exact Swift source bytes in the isolated test mirror were compared with the feature worktree after final verification.++### Isolated performance comparison++Three synthetic tasks, 5,002 saved comments, one selected task with two comments; temporary on-disk nine-entity store, CloudKit disabled, production history fences. One unmeasured warm-up per path followed by four rotated scoped/unrestricted captures. Debug build; setup excluded. Every capture produced identical task record bytes/revisions and retained comment evidence. Materialized rows were exactly two versus 5,002 on every iteration.++Median total capture: unrestricted134.845ms, scoped31.208ms (approximately76.9% reduction in this fixture). Timings are supporting measurements, not assertions or live performance guarantees. This does not explain all prior timeout causes, prove an uptime leak, or prove sufficient performance after deployment under live CloudKit load.++### Remaining validation and tracking++User-controlled deployment and observation with the existing content-free diagnostics remain necessary. No restart, deployment, live store/settings changes, live probes or ticket mutations were performed during implementation. T-2455 remains the sole tracking ticket; live updates are excluded by this turn's scope. The separate empty-originals task-refetch optimization is not included.
specs/bugfixes/scoped-comment-fetch/tasks.md Added
diff --git a/specs/bugfixes/scoped-comment-fetch/tasks.md b/specs/bugfixes/scoped-comment-fetch/tasks.mdnew file mode 100644index 00000000..17e16618--- /dev/null+++ b/specs/bugfixes/scoped-comment-fetch/tasks.md@@ -0,0 +1,14 @@+# T-2455 scoped comment-fetch tasks++- [x] Preserve live failure journal and stack evidence without restarting Transit.+- [x] Record selected logical-ID, physical ownership, saved revision and portfolio/orphan invariants.+- [x] Establish a red materialization regression: 1,002 rows fetched instead of two.+- [x] Apply a selected-read comment predicate without changing budgets or capture fences.+- [x] Add isolated duplicate-owner, bulk/summary, edited/reparented/orphan/pending-change and history-fence fixtures.+- [x] Compare scoped and former whole-store capture output and deterministic materialization work.+- [x] Complete four targeted source review areas; no blockers found.+- [x] Record final verification (78 targeted tests, zero failures/skips; lint clean).+- [ ] Publish a feature PR.+- [ ] User-controlled deployment and long-uptime observation; no resolution claim from fixtures alone.++Ticket updates are intentionally omitted in this implementation turn because its authorisation excludes live data mutation. Existing T-2455 remains the tracking item.