Transit branch T-2382/final-verification revision b32612427ed5 files 33

Pre-push review: T-2382 remaining tests and caller contract

Reconciled onto squash-merged T2383/T63 main; no duplicate foundation/runtime replay.

At a glance

  • Reconciled against merged T2383/T63 main 747983a7009d. Remaining changes are tests/docs and unused scaffold removal.
  • Fresh Xcode27 focused result:149 declarations /221 expanded bodies passed; zero native/runtime issues or NIO misuse; normaldrain. Exact qualified union:2277declarations /2581bodies, not a new full-suite run. Build warnings match82baseline entries/41signatures; lint zero546files.
  • No generated JUnit or coverage: generic ecosystem runner not detected for this Xcode project. Native evidence reported separately.
  • Destination pushes, external Claude review and overnight merge explicitly approved; no live writes, settings, CloudKit action, deployment or activation.

Verdict

Ready for PR Pilot

All must-fix review findings resolved. Fresh guarded Xcode27 native acceptance is described in integration-acceptance.md; prior 2,277-declaration/2,581-body exact union remains qualified common-source reuse, not a new full-suite run. Zero lint violations. Actual installed-client validation remains deferred to the user’s MacBook after merge.

Review findings

3 raised · 2 fixed · 1 skipped

Jump to findings →

Tests

Pass rate: n/a

New tests: 88

Diff coverage: n/a

Jump to tests →

Commits

Three-level explanation


### What Changed

`query_project_summaries` reports the recorded workload for the whole portfolio or one selected project. It returns every status bucket, separate idea/workflow/in-progress/nonterminal counts, milestone breakdowns, recent current-record completions, and the newest recorded activity evidence. Empty projects remain visible. Counts describe saved records; they do not claim release readiness or that every workflow task is actively being worked on.

### Why It Matters

An agent can inspect compact summaries without downloading task descriptions or comment bodies. A returned snapshot can then answer task queries against exactly the same saved view, even if live records change. Its original capture time, freshness evidence and five-minute expiry stay fixed across pages and replay.

### Key Concepts

A capture is a consistent copy of saved local records. A snapshot is a temporary retained capture, not a live query. Freshness describes available local import evidence, not CloudKit-wide completeness. Completion windows include their start and exclude their end; they count tasks currently done or abandoned, not historical transitions.


### Changes Overview

`PortfolioSummaryService` aggregates immutable T63 capture values. It attributes records by physical keys, validates the relevant UUID identity closure, and produces deterministic compact counts/activity/diagnostics. The portfolio request parser and snapshot task parser provide strict initial/replay/continuation modes. Snapshot queries support project UUID and effective status filters, summary/full detail and captured canonical revisions, while rejecting comment bodies or scope expansion.

### Implementation Approach

The shared T63 coordinator admits physical reads, evaluates freshness, captures saved values and arbitrates the original request deadline. Portfolio work and encoding operate on detached values. Reusable views use a separate eight-root/16-MiB logical encoded-data budget and immutable index candidates. Successful response encoding and publication are selected together under the shared publication domain; rejection releases reservations and returns typed failure without unreachable IDs.

Prepared modern result fragments are retained by identity. Replay changes JSON-RPC correlation while reusing the exact prepared fragment and original metadata. Read pins validate root identity, original expiry and lifecycle at the completion gate. Seeded router tests compare snapshot task IDs/status counts and completion windows against independently captured records, then mutate saved data and verify frozen replay without another capture.

### Trade-offs

A separate reusable-view store preserves ordinary pagination behavior and budgets. Encoded charges bound logical retention, not total heap use. Scoped capture carries sufficient identity closure to reject attribution ambiguity without broadening reusable query scope. Diagnostics retain exact affected counts with at most ten deterministic samples. Unsupported options fail explicitly instead of reading live data.


### Technical Deep Dive

Aggregation keeps all eight effective status buckets and reconciles each project's valid milestone, unassigned and invalid-association partitions. Unknown raw task status maps to effective idea; ordinary queries preserve their existing stored-status behavior. Milestone raw/effective status remains independent of task completion. Activity selects the maximum recorded task/milestone creation/status or comment-creation evidence, with deterministic kind, public identity and physical-key tie-breaking. Window parsing restricts accepted precision and emits canonical UTC milliseconds.

Retention construction, page-owner validation, byte comparisons and retirement preparation occur outside the sole completion lock. Per-store changes coalesce into one immutable candidate/version/reservation; all selected stores validate before any swap. Original-operation checkpoints bound cooperative work, while independent deadline arbitration handles noncooperative capture/encoding and retains timed-out physical admission until actual completion. A read pin is not permission to publish after expiry or lifecycle invalidation.

### Architecture Impact

T2382 owns aggregation, reusable-view modules and explicit snapshot query semantics. T63 supplies saved capture, freshness, read budgets, common registration and publication. T2383 supplies latest-only single-object transport and modern provider preparation. Production JSON-RPC arrays are rejected; internal aggregate tests cover atomic publication and protected write receipts without claiming wire batching or a read deadline for mutation calls.

### Potential Issues

The five-second checks measure encoded response availability in the tested runtime, not hard real-time OS scheduling. CloudKit convergence and live signed-store import correlation remain unproved; unknown/unavailable evidence is binding. Corruption-heavy diagnostics and large prepared-owner sets have optional scaling improvements, but no measured deadline failure was established. Installed-client compatibility is explicitly deferred to the user's MacBook after merge.

Important changes — detailed

Regression fixtures complete approved portfolio semantics

Transit/TransitTests/MCPPortfolioReconciliationTests.swift

Why it matters. Independently captured records reconcile summaries and frozen pages after mutation.

What to look at. Seeded reconciliation and verifyPublishedPages

Takeaway. Use throwing progress guards so failure paths terminate.
Rationale. Approved reconciliation criteria and local review fix.

Read foundation harness verifies bounded cleanup

Transit/TransitTests/MCPPortfolioFoundationHarness.swift

Why it matters. Physical work remains charged until it actually drains.

What to look at. Off-MainActor capture/encoding seams

Takeaway. Verify eventual physical cleanup independently of logical timeout.
Rationale. Approved bounded read contract.

Caller contract explains frozen query evidence

docs/mcp-portfolio-contract.md

Why it matters. Agents can distinguish recorded counts, freshness and completion windows.

What to look at. Initial, replay and continuation modes

Takeaway. Preserve original metadata rather than presenting a later page as a fresh capture.
Rationale. Approved original freshness requirement.

Review findings

SeverityAreaFindingResolution
mediumreconciliation fixture cursor loopNonfatal duplicate-cursor assertion can loop indefinitely on a regression.Replaced with throwing #require in a60e12af; affected native suites rerun.
minorcurrent approval statusTwo current delivery paragraphs still describe the resolved disclosure gate.Current status updated; historical approval records retained.
minortest result decoderSome dictionary payload decoding could reuse MCPHTTPTestHelpers.Optional consolidation deferred; no assertion churn or production defect.

Tests

Source: local run at 2026-10-04T21:53:58.067687+00:00 · snapshot b32612427ed50ff6d7cbf80f126a4716b4b5a111

Baseline: none

Execution: not run · JUnit: none · Coverage: none · Baseline: absent

Coverage scope: as the project configures it

No test results

The test runner could not be detected.

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 747983a7009d0015280f6e88ec811d933f4ef449.

Dependents none found Changed Dependencies none found Transit/Transit/Services Transit/TransitTests Transit/Transit/Services/PortfolioSummaryService.swift…PortfolioSummaryService.swift Transit/TransitTests/MCPPortfolioFoundationHarness.swift…tfolioFoundationHarness.swift Transit/TransitTests/MCPPortfolioHandlerTests.swift…CPPortfolioHandlerTests.swift Transit/TransitTests/MCPPortfolioIntegrationTests.swift…rtfolioIntegrationTests.swift Transit/TransitTests/MCPPortfolioInterfaceTests.swift…PortfolioInterfaceTests.swift Transit/TransitTests/MCPPortfolioModernAcceptanceTests.swift…ioModernAcceptanceTests.swift Transit/TransitTests/MCPPortfolioProjectionTests.swift…ortfolioProjectionTests.swift Transit/TransitTests/MCPPortfolioReadFoundationTests.swift…olioReadFoundationTests.swift Transit/TransitTests/MCPPortfolioReconciliationTests.swift…olioReconciliationTests.swift Transit/TransitTests/MCPPortfolioScopedCaptureTests.swift…folioScopedCaptureTests.swift Transit/TransitTests/MCPPortfolioSnapshotRequestTests.swift…lioSnapshotRequestTests.swift Transit/TransitTests/MCPReusableSnapshotLookupRaceTests.swift…SnapshotLookupRaceTests.swift Transit/TransitTests/MCPReusableSnapshotPublicationTests.swift…napshotPublicationTests.swift Transit/TransitTests/MCPReusableSnapshotReadPinTests.swift…bleSnapshotReadPinTests.swift Transit/TransitTests/PortfolioSummaryPropertyTests.swift…lioSummaryPropertyTests.swift Transit/TransitTests/PortfolioSummaryServiceTests.swift…olioSummaryServiceTests.swift Transit/TransitTests/PortfolioSummaryTestValues.swift…tfolioSummaryTestValues.swift
addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

33 files: 17 code · 16 docs. Click to expand.

Code (17)

Transit/Transit/Services/PortfolioSummaryService.swift Modified
diff --git a/Transit/Transit/Services/PortfolioSummaryService.swift b/Transit/Transit/Services/PortfolioSummaryService.swiftindex 7a8a312c..70405cc5 100644--- a/Transit/Transit/Services/PortfolioSummaryService.swift+++ b/Transit/Transit/Services/PortfolioSummaryService.swift@@ -1,10 +1,6 @@ #if os(macOS) import Foundation -nonisolated enum MCPPortfolioScaffoldError: Error {-    case notImplemented-}- /// Pure saved-value aggregation. Identity closure validates attribution but never expands scope. nonisolated enum PortfolioSummaryService {     private static let taskStatuses = [
Transit/TransitTests/MCPPortfolioFoundationHarness.swift Added
diff --git a/Transit/TransitTests/MCPPortfolioFoundationHarness.swift b/Transit/TransitTests/MCPPortfolioFoundationHarness.swiftnew file mode 100644index 00000000..d30dcdaf--- /dev/null+++ b/Transit/TransitTests/MCPPortfolioFoundationHarness.swift@@ -0,0 +1,158 @@+#if os(macOS)+import Foundation+import Hummingbird+import HTTPTypes+import Logging+import NIOConcurrencyHelpers+import NIOCore+import NIOEmbedded+import NIOFoundationCompat+import Testing+@testable import Transit++/// Minimal synthetic read adapter, not final MCP dispatch or summary aggregation.+nonisolated enum MCPPortfolioFoundationHarness {+    static let timeout = Data("{\"error\":\"READ_TIMEOUT\"}".utf8)+    static let busy = Data("{\"error\":\"READ_BUSY\"}".utf8)+    static let capacity = Data("{\"error\":\"QUERY_CAPACITY_EXCEEDED\"}".utf8)++    static func prepareCapture(_ view: CapturedReadView) throws -> PreparedReadResult {+        guard case .completePortfolio = view.completeness else { throw MCPReadCaptureError.incoherentCapture }+        guard view.captureScope != .selectedQuery else { throw MCPReadCaptureError.incoherentCapture }+        let selectedProjects: Set<LocalRecordKey>?+        switch view.captureScope {+        case .wholePortfolio: selectedProjects = nil+        case .projects(let keys): selectedProjects = Set(keys)+        case .selectedQuery: throw MCPReadCaptureError.incoherentCapture+        }+        let commentKeys = Set(view.comments.map(\.physicalKey))+        var records: [Data] = []+        var evidence: [PortfolioFoundationTaskEvidence] = []+        for task in view.tasks {+            let selected = selectedProjects.map { projects in+                task.projectKey.map { projects.contains($0) } ?? false+            } ?? true+            if selected {+                guard let record = task.fullRecordWithoutCommentsJSON, let revision = task.revision,+                      revision.hasPrefix("r1:"), Set(task.commentKeys).isSubset(of: commentKeys) else {+                    throw MCPReadCaptureError.incoherentCapture+                }+                records.append(record)+            }+            // Preserve the original identity closure; full records/counts use only+            // declared physical scope. This is fixture encoding, not production validation.+            evidence.append(PortfolioFoundationTaskEvidence(+                id: task.id, physicalKey: task.physicalKey.encodedIdentifier,+                projectKey: task.projectKey?.encodedIdentifier, milestoneKey: task.milestoneKey?.encodedIdentifier,+                commentKeys: task.commentKeys.map(\.encodedIdentifier), rawStatus: task.rawStatus,+                effectiveStatus: task.effectiveStatus, revision: task.revision))+        }+        let envelope = PortfolioFoundationCaptureEnvelope(+            asOf: view.metadata.asOf, snapshotId: view.metadata.snapshotId, metadata: view.metadata,+            taskCount: records.count, records: records, taskEvidence: evidence,+            projects: view.projects.map(\.selectedRecordJSON), milestones: view.milestones.map(\.selectedRecordJSON),+            comments: view.comments.map {+                PortfolioFoundationCommentEvidence(id: $0.id, physicalKey: $0.physicalKey.encodedIdentifier,+                    taskKey: $0.taskKey?.encodedIdentifier, storedTaskID: $0.storedTaskID,+                    creationDate: $0.creationDate)+            })+        let encoded = try JSONEncoder().encode(envelope)+        return result(encoded.count <= 16 * 1_024 * 1_024 ? encoded : capacity)+    }++    static func result(_ bytes: Data, publications: [any MCPPreparedPublication] = []) -> PreparedReadResult {+        PreparedReadResult(encodedResponse: bytes, publications: publications,+            publicationErrors: PreencodedPublicationErrors(busy: busy, expired: timeout, capacity: busy))+    }++    @concurrent static func route(+        _ response: @escaping @Sendable () async -> Response+    ) async throws -> Data {+        let router = Router(context: MCPRequestContext.self)+        router.post("/portfolio-fixture") { _, _ in await response() }+        let loop = NIOAsyncTestingEventLoop()+        var ownedChannel: NIOAsyncTestingChannel?+        do {+            let channel = try await NIOAsyncTestingChannel(loop: loop) { _ in }+            ownedChannel = channel+            let context = MCPRequestContext(source: ApplicationRequestContextSource(+                channel: channel, logger: Logger(label: "portfolio-foundation")))+            let request = Request(head: HTTPRequest(method: .post, scheme: "http", authority: "localhost",+                                                   path: "/portfolio-fixture"),+                                  body: RequestBody(buffer: ByteBuffer()))+            let output = try await router.buildResponder().respond(to: request, context: context)+            let writer = PortfolioFoundationResponseWriter()+            try await output.body.write(writer)+            let bytes = Data(buffer: writer.bytes.withLockedValue { $0 })+            let leftovers = try await channel.finish(acceptAlreadyClosed: true)+            #expect(leftovers.isClean)+            await loop.shutdownGracefully()+            return bytes+        } catch {+            if let channel = ownedChannel {+                do {+                    let leftovers = try await channel.finish(acceptAlreadyClosed: true)+                    #expect(leftovers.isClean)+                } catch { Issue.record("Foundation test channel cleanup failed: \(error)") }+            }+            await loop.shutdownGracefully()+            throw error+        }+    }+}++private nonisolated struct PortfolioFoundationCaptureEnvelope: Encodable {+    let asOf: String+    let snapshotId: String+    let metadata: ReadCaptureMetadata+    let taskCount: Int+    let records: [Data]+    let taskEvidence: [PortfolioFoundationTaskEvidence]+    let projects: [Data]+    let milestones: [Data]+    let comments: [PortfolioFoundationCommentEvidence]+}++private nonisolated struct PortfolioFoundationTaskEvidence: Encodable {+    let id: UUID+    let physicalKey: Data+    let projectKey: Data?+    let milestoneKey: Data?+    let commentKeys: [Data]+    let rawStatus: String+    let effectiveStatus: String+    let revision: String?+}++private nonisolated struct PortfolioFoundationCommentEvidence: Encodable {+    let id: UUID+    let physicalKey: Data+    let taskKey: Data?+    let storedTaskID: UUID?+    let creationDate: Date+}++actor PortfolioFoundationCompletion {+    private var completed = false+    func finish() { completed = true }+    var isFinished: Bool { completed }+}++private nonisolated final class PortfolioFoundationResponseWriter: ResponseBodyWriter {+    let bytes = NIOLockedValueBox(ByteBuffer())+    func write(_ buffer: ByteBuffer) async throws { _ = bytes.withLockedValue { $0.writeImmutableBuffer(buffer) } }+    func finish(_: HTTPFields?) async throws {}+}++nonisolated final class PortfolioFoundationPublication: MCPPreparedPublication, @unchecked Sendable {+    let publicationStoreID = MCPPublicationStoreID(rawValue: UUID())+    let domain: MCPReadPublicationDomain+    private var committed = false+    private var discarded = false+    init(domain: MCPReadPublicationDomain) { self.domain = domain }+    func validateLocked(in domain: MCPReadPublicationDomain) -> PublicationRejection? { nil }+    func commitLocked(in domain: MCPReadPublicationDomain) { if !discarded { committed = true } }+    func discardLocked(in domain: MCPReadPublicationDomain) { if !committed { discarded = true } }+    var counts: [Bool] { domain.withLock { [committed, discarded] } }+}+#endif
Transit/TransitTests/MCPPortfolioHandlerTests.swift Added
diff --git a/Transit/TransitTests/MCPPortfolioHandlerTests.swift b/Transit/TransitTests/MCPPortfolioHandlerTests.swiftnew file mode 100644index 00000000..a85cf809--- /dev/null+++ b/Transit/TransitTests/MCPPortfolioHandlerTests.swift@@ -0,0 +1,666 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing++// swiftlint:disable file_length+@testable import Transit++/// Public-dispatch preparation: these tests intentionally require the shared registry and handler wiring.+/// They do not bypass the tools/call boundary or invent a capture/preparation injection interface.+@MainActor @Suite(.serialized)+struct MCPPortfolioHandlerTests {+    @Test func advertisedToolContainsStrictSummaryBranchesAndSemanticDescription() async throws {+        let env = try makeEnvironment()+        let response = try await listResponse(env)+        let wire = try envelope(response)+        let result = try #require(wire["result"] as? [String: Any])+        let tools = try #require(result["tools"] as? [[String: Any]])+        let tool = try #require(tools.first { $0["name"] as? String == "query_project_summaries" })+        #expect(tools.filter { $0["name"] as? String == "query_project_summaries" }.count == 1)+        let schema = try #require(tool["inputSchema"] as? [String: Any])+        let branches = try #require(schema["oneOf"] as? [[String: Any]])+        #expect(branches.count == 5)+        #expect(branches.allSatisfy { $0["additionalProperties"] as? Bool == false })+        let required = branches.compactMap { $0["required"] as? [String] }.map(Set.init)+        #expect(required.contains(Set(["start", "end", "limit"])))+        #expect(required.contains(Set(["start", "end", "limit", "projectId"])))+        #expect(required.contains(Set(["start", "end", "limit", "project"])))+        #expect(required.contains(Set(["snapshotId"])) && required.contains(Set(["cursor"])))+        for branch in branches where (branch["required"] as? [String] ?? []).contains("start") {+            let properties = try #require(branch["properties"] as? [String: Any])+            try expectBoundedLimit(properties)+            let policy = try #require(properties["readPolicy"] as? [String: Any])+            #expect(policy["default"] as? String == "refresh_if_needed")+        }+        let cursorBranch = try #require(branches.first { ($0["required"] as? [String]) == ["cursor"] })+        let cursorProperties = try #require(cursorBranch["properties"] as? [String: Any])+        #expect((cursorProperties["readPolicy"] as? [String: Any])?["default"] == nil)+        let description = try #require(tool["description"] as? String)+        let normalizedDescription = description.split(whereSeparator: \.isWhitespace).joined(separator: " ")+        for fragment in [+            "activeTaskCount", "nonterminal", "[start,end)", "historical", "sampleComplete",+            "five seconds", "five minutes", "Each HTTP POST accepts one JSON-RPC object",+            "JSON-RPC batch arrays are rejected",+            "mutate_tasks can carry multiple application-level operations within one tools/call",+            "READ_TIMEOUT", "storage_failure",+            "incoherent_capture", "serialization_failure", "remote"+        ] {+            #expect(normalizedDescription.contains(fragment), "Missing advertised semantics: \(fragment)")+        }+    }++    @Test func advertisedSnapshotTaskBranchPreservesOrdinaryQuerySchema() async throws {+        let env = try makeEnvironment()+        let response = try await listResponse(env)+        let tools = try #require(+            (try envelope(response)["result"] as? [String: Any])?["tools"] as? [[String: Any]])+        let tool = try #require(tools.first { $0["name"] as? String == "query_tasks" })+        let schema = try #require(tool["inputSchema"] as? [String: Any])+        let branches = try #require(schema["oneOf"] as? [[String: Any]])+        let snapshot = try #require(+            branches.first {+                Set($0["required"] as? [String] ?? [])+                    == Set(["snapshotId", "detailLevel", "includeComments", "limit"])+            })+        #expect(snapshot["additionalProperties"] as? Bool == false)+        let properties = try #require(snapshot["properties"] as? [String: Any])+        #expect(+            Set(properties.keys)+                == Set(["snapshotId", "detailLevel", "includeComments", "limit", "projectId", "status"]))+        try expectBoundedLimit(properties)+        #expect((properties["includeComments"] as? [String: Any])?["const"] as? Bool == false)+        #expect(branches.contains { ($0["properties"] as? [String: Any])?["taskIds"] != nil })+        let description = try #require(tool["description"] as? String)+        for fragment in ["stored-status", "effective", "comment", "revision", "scope", "empty"] {+            #expect(description.contains(fragment))+        }+    }++    @Test func summaryRejectsMalformedScalarsSelectorsWindowsAndUnknownFields() async throws {+        let env = try makeEnvironment()+        let invalid: [[String: Any]] = [+            [:], ["start": 12], ["end": NSNull()], ["limit": true], ["limit": 1.5],+            ["limit": "1"], ["limit": 0], ["limit": 101], ["projectId": "bad-uuid"],+            ["project": " \n "], ["project": 1], ["readPolicy": "fresh"], ["extra": "ignored"],+            ["projectId": projectID.uuidString, "project": "Alpha"],+            ["start": "2026-10-03"], ["end": "2026-10-03T01:00:00"],+            ["start": "2026-02-30T00:00:00Z"], ["start": "2026-10-03T00:00:00.1234Z"],+            ["end": "2026-10-03T00:00:00Z"]+        ]+        for replacement in invalid {+            let arguments =+                replacement.isEmpty ? [:] : initialArguments.merging(replacement) { _, new in new }+            let response = try await call(env, tool: "query_project_summaries", arguments: arguments)+            try expectError(response, code: "INVALID_INPUT")+        }+        for endpoint in ["start", "end", "limit"] {+            var arguments = initialArguments+            arguments.removeValue(forKey: endpoint)+            try expectError(+                try await call(env, tool: "query_project_summaries", arguments: arguments),+                code: "INVALID_INPUT")+        }+    }++    @Test func replayAndContinuationAreExclusiveAndDoNotSilentlyBecomeInitialReads() async throws {+        let env = try makeEnvironment()+        let invalid: [(arguments: [String: Any], code: String)] = [+            (["snapshotId": "bad"], "INVALID_SNAPSHOT"),+            (["snapshotId": projectID.uuidString, "limit": 1], "INVALID_INPUT"),+            (["snapshotId": projectID.uuidString, "readPolicy": "cached"], "INVALID_INPUT"),+            (["cursor": "bad"], "INVALID_CURSOR"),+            (["cursor": reusableCursor, "start": initialArguments["start"]!], "INVALID_INPUT"),+            (["cursor": reusableCursor, "readPolicy": "fresh"], "INVALID_INPUT")+        ]+        for entry in invalid {+            try expectError(+                try await call(env, tool: "query_project_summaries", arguments: entry.arguments),+                code: entry.code)+        }+        try expectError(+            try await call(+                env, tool: "query_project_summaries",+                arguments: ["snapshotId": UUID().uuidString]), code: "INVALID_SNAPSHOT")+        try expectError(+            try await call(+                env, tool: "query_project_summaries",+                arguments: ["cursor": reusableCursor]), code: "INVALID_CURSOR")+    }++    @Test func snapshotTaskModeValidatesOptionsBeforeOrdinaryParsing() async throws {+        let env = try makeEnvironment()+        let baseline: [String: Any] = [+            "snapshotId": projectID.uuidString, "detailLevel": "full",+            "includeComments": false, "limit": 10+        ]+        let cases: [(patch: [String: Any], code: String)] = [+            (["includeComments": true], "SNAPSHOT_INCOMPATIBLE"),+            (["project": "Alpha"], "SNAPSHOT_INCOMPATIBLE"),+            (["readPolicy": "cached"], "SNAPSHOT_INCOMPATIBLE"),+            (["search": "Task"], "SNAPSHOT_INCOMPATIBLE"),+            (["type": "feature"], "SNAPSHOT_INCOMPATIBLE"),+            (["priority": "high"], "SNAPSHOT_INCOMPATIBLE"),+            (["detailLevel": "expanded"], "INVALID_INPUT"),+            (["includeComments": "false"], "INVALID_INPUT"),+            (["limit": true], "INVALID_INPUT"),+            (["status": ["unknown"]], "INVALID_INPUT"),+            (["projectId": "bad"], "INVALID_INPUT")+        ]+        for entry in cases {+            try expectError(+                try await call(+                    env, tool: "query_tasks",+                    arguments: baseline.merging(entry.patch) { _, new in new }), code: entry.code)+        }+        for required in ["detailLevel", "includeComments", "limit"] {+            var arguments = baseline+            arguments.removeValue(forKey: required)+            try expectError(+                try await call(env, tool: "query_tasks", arguments: arguments), code: "INVALID_INPUT")+        }+    }++    @Test func normalizedNameResolutionAndMissingSelectorsHaveExplicitOutcomes() async throws {+        let env = try makeEnvironment()+        let selected = try await summary(env, patch: ["project": "  aLPHa \n"])+        let projects = try #require(selected.payload["projects"] as? [[String: Any]])+        #expect(projects.count == 1 && projects.first?["projectId"] as? String == projectID.uuidString)+        try expectError(+            try await call(+                env, tool: "query_project_summaries",+                arguments: initialArguments.merging(["projectId": UUID().uuidString]) { _, new in new }),+            code: "PROJECT_NOT_FOUND")+        let collision = MCPTestHelpers.makeProject(in: env.context, name: " ALPHA ")+        collision.id = UUID()+        try env.context.save()+        try expectError(+            try await call(+                env, tool: "query_project_summaries",+                arguments: initialArguments.merging(["project": "alpha"]) { _, new in new }),+            code: "AMBIGUOUS_PROJECT")+    }++    @Test func populatedSummaryHasCompactCountsWindowAndExternalCaptureMetadata() async throws {+        let env = try makeEnvironment()+        let result = try await summary(env)+        let projects = try #require(result.payload["projects"] as? [[String: Any]])+        let project = try #require(projects.first { $0["projectId"] as? String == projectID.uuidString })+        let buckets = try #require(project["countsByStatus"] as? [String: Int])+        #expect(+            buckets == [+                "idea": 2, "planning": 1, "spec": 1, "ready-for-implementation": 1,+                "in-progress": 1, "ready-for-review": 1, "done": 1, "abandoned": 1+            ])+        #expect(project["totalTaskCount"] as? Int == 9 && project["nonterminalTaskCount"] as? Int == 7)+        let window = try #require(result.payload["completionWindow"] as? [String: String])+        #expect(window == ["start": "2026-10-03T00:00:00.000Z", "end": "2026-10-03T01:00:00.000Z"])+        #expect(result.payload["_meta"] == nil && result.payload["snapshotId"] == nil)+        #expect(result.metadata["snapshotId"] is String && result.metadata["asOf"] is String)+        #expect(result.metadata["freshness"] is [String: Any] && result.metadata["read"] is [String: Any])+        let text = String(+            data: try JSONSerialization.data(withJSONObject: result.payload), encoding: .utf8)!+        #expect(+            !text.contains("Secret description") && !text.contains("Secret comment")+                && !text.contains("Secret metadata"))+    }++    @Test func emptyPortfolioAndEmptyScopedProjectStillCarryReadEvidence() async throws {+        let empty = try makeEnvironment(taskCount: 0, projectCount: 0)+        let portfolio = try await summary(empty)+        #expect((portfolio.payload["projects"] as? [[String: Any]])?.isEmpty == true)+        #expect(portfolio.metadata["snapshotId"] is String && portfolio.metadata["asOf"] is String)+        let env = try makeEnvironment(taskCount: 0)+        let scoped = try await summary(env, patch: ["projectId": projectID.uuidString])+        let projects = try #require(scoped.payload["projects"] as? [[String: Any]])+        #expect(projects.count == 1 && projects.first?["totalTaskCount"] as? Int == 0)+        #expect(projects.first?["lastRecordedActivity"] is NSNull)+        #expect(scoped.metadata["freshness"] is [String: Any] && scoped.metadata["read"] is [String: Any])+    }+}++extension MCPPortfolioHandlerTests {+    @Test func summaryReplayAndContinuationPreserveOriginalPayloadAndEvidenceAfterSavedChanges()+        async throws {+        let env = try makeEnvironment()+        let first = try await summary(env, patch: ["limit": 1])+        let snapshot = try #require(first.metadata["snapshotId"] as? String)+        let cursor = try #require(first.payload["nextCursor"] as? String)+        #expect(MCPCursorFamily.classify(cursor) == .reusable)+        let project = try #require(+            try env.context.fetch(FetchDescriptor<Project>()).first { $0.id == projectID })+        project.name = "Changed after capture"+        for task in try env.context.fetch(FetchDescriptor<TransitTask>()) { env.context.delete(task) }+        try env.context.save()+        let replay = try decode(+            try await call(env, tool: "query_project_summaries", arguments: ["snapshotId": snapshot]))+        #expect(equalJSON(replay.payload, first.payload) && equalJSON(replay.metadata, first.metadata))+        let next = try decode(+            try await call(env, tool: "query_project_summaries", arguments: ["cursor": cursor]))+        #expect(equalJSON(next.metadata, first.metadata))+        #expect(equalJSON(next.payload["completionWindow"], first.payload["completionWindow"]))+        #expect(next.payload["expiresAt"] as? String == first.payload["expiresAt"] as? String)+        #expect((next.payload["projects"] as? [[String: Any]])?.first?["name"] as? String == "Beta")+        try expectError(+            try await call(+                env, tool: "query_project_summaries",+                arguments: ["cursor": cursor, "readPolicy": "refresh_if_needed"]),+            code: "SNAPSHOT_INCOMPATIBLE")+    }++    @Test func snapshotTaskDetailsReconcileAndRetainCapturedRevisionAcrossLiveDeletion() async throws {+        let env = try makeEnvironment()+        let original = try await summary(env)+        let snapshot = try #require(original.metadata["snapshotId"] as? String)+        let source = try #require(+            try env.context.fetch(FetchDescriptor<TransitTask>()).first { $0.permanentDisplayId == 9 })+        let revision = try MCPRecordSnapshot.task(source, in: env.context).revision+        let query: [String: Any] = [+            "snapshotId": snapshot, "detailLevel": "full", "includeComments": false,+            "limit": 1, "projectId": projectID.uuidString, "status": ["idea", "idea"]+        ]+        let first = try decode(try await call(env, tool: "query_tasks", arguments: query))+        var rows = try #require(first.payload["results"] as? [[String: Any]])+        let cursor = try #require(first.payload["nextCursor"] as? String)+        #expect(+            MCPCursorFamily.classify(cursor) == .reusable && equalJSON(first.metadata, original.metadata))+        env.context.delete(source)+        try env.context.save()+        let continuation = try decode(+            try await call(env, tool: "query_tasks", arguments: ["cursor": cursor]))+        rows += try #require(continuation.payload["results"] as? [[String: Any]])+        #expect(rows.count == 2 && rows.allSatisfy { $0["status"] as? String == "idea" })+        let legacy = try #require(rows.first { $0["storedStatus"] as? String == "legacy-status" })+        #expect(legacy["revision"] as? String == revision)+        #expect(legacy["description"] as? String == "Secret description 8")+        #expect((legacy["metadata"] as? [String: String])?["fixture"] == "Secret metadata 8")+        #expect(rows.allSatisfy { $0["comments"] == nil })+        #expect(equalJSON(continuation.metadata, original.metadata))+        #expect(continuation.payload["expiresAt"] as? String == first.payload["expiresAt"] as? String)+    }++    @Test func scopedSnapshotsCannotExpandToForeignProjects() async throws {+        let env = try makeEnvironment()+        let original = try await summary(env, patch: ["projectId": projectID.uuidString])+        let snapshot = try #require(original.metadata["snapshotId"] as? String)+        let foreign = try #require(+            try env.context.fetch(FetchDescriptor<Project>()).first { $0.id != projectID })+        try expectError(+            try await call(+                env, tool: "query_tasks",+                arguments: [+                    "snapshotId": snapshot, "detailLevel": "summary", "includeComments": false,+                    "limit": 10, "projectId": foreign.id.uuidString+                ]), code: "SNAPSHOT_INCOMPATIBLE")+    }++    @Test func missingReusableCursorAndOrdinaryCursorFamiliesRemainDistinct() async throws {+        let env = try makeEnvironment()+        try expectError(+            try await call(env, tool: "query_tasks", arguments: ["cursor": reusableCursor]),+            code: "INVALID_CURSOR")+        let ordinary = try decode(try await call(env, tool: "query_tasks", arguments: ordinaryArguments(["limit": 1])))+        let cursor = try #require(ordinary.payload["nextCursor"] as? String)+        #expect(MCPCursorFamily.classify(cursor) == .ordinary)+        let next = try decode(try await call(env, tool: "query_tasks", arguments: ["cursor": cursor]))+        #expect((next.payload["results"] as? [[String: Any]])?.count == 1)+        #expect(equalJSON(next.metadata, ordinary.metadata))+    }++    @Test(arguments: ["storage_failure", "serialization_failure", "incoherent_capture"])+    func admittedCaptureSourceFailuresKeepTheirCategoryWithoutInventingSnapshot(category: String)+        async throws {+        let failure: MCPReadCaptureError+        switch category {+        case "storage_failure": failure = .storageFailure+        case "serialization_failure": failure = .serializationFailure+        default: failure = .incoherentCapture+        }+        let env = try makeEnvironment(captureFailure: failure)+        for tool in ["query_tasks", "query_project_summaries"] {+            let arguments: [String: Any] = tool == "query_tasks" ? ordinaryArguments() : initialArguments+            let bytes = try await call(env, tool: tool, arguments: arguments)+            let wire = try envelope(bytes)+            #expect(wire["error"] == nil)+            let result = try #require(wire["result"] as? [String: Any])+            #expect(result["isError"] as? Bool == true)+            let read = try #require(+                (result["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any])+            #expect(read["category"] as? String == category)+            let requestID = try #require(read["requestId"] as? String)+            #expect(UUID(uuidString: requestID) != nil)+            #expect(read["snapshotId"] == nil && read["asOf"] == nil && read["freshness"] == nil)+            let execution = try #require(read["read"] as? [String: Any])+            #expect(execution["policy"] as? String == "cached" && execution["budgetMs"] as? Int == 5_000)+            // This observes a real typed producer failure inside the admitted worker, not outer encode fallback.+            let content = try #require(result["content"] as? [[String: Any]])+            let text = try #require(content.first?["text"] as? String)+            #expect(!text.isEmpty)+            // Non-query failures use plain text; their typed category lives in external metadata.+        }+    }++    @Test func ninthTinyCapturedSummaryNormalizesPreGateCapacityWithoutEvictingRoots() async throws {+        let env = try makeEnvironment(taskCount: 0, projectCount: 0)+        let store = try env.handler.reusableSnapshots.get()+        var roots: [RetainedView] = []+        for _ in 0..<8 { roots.append(try seedEmptyReusableRoot(env, store: store)) }+        let before = try store.domain.accounting(for: store.publicationStoreID)+        #expect(before.visibleEntries == 8 && before.pendingEntries == 0)+        let response = try await call(env, tool: "query_project_summaries", arguments: initialArguments)+        try expectError(response, code: "QUERY_CAPACITY_EXCEEDED")+        let after = try store.domain.accounting(for: store.publicationStoreID)+        #expect(after.visibleEntries == 8 && after.visibleBytes == before.visibleBytes)+        #expect(after.pendingEntries == 0 && after.pendingBytes == 0)+        for root in roots {+            #expect(try store.retainedView(for: root.capture.metadata.snapshotId, now: .now)+                .capture.metadata.snapshotId == root.capture.metadata.snapshotId)+        }+    }++    @Test(arguments: ["summary_replay", "summary_cursor", "task_snapshot", "task_cursor"])+    func preGateExpiredReusableLookupsKeepTheirFamilyError(mode: String) async throws {+        let env = try makeEnvironment(taskCount: 0, projectCount: 0)+        let store = try env.handler.reusableSnapshots.get()+        let root = try seedEmptyReusableRoot(env, store: store, cursor: reusableCursor)+        let before = try store.domain.accounting(for: store.publicationStoreID)+        store.domain.setTestingInstant(root.capture.retentionDeadline + .milliseconds(1))+        let tool = mode.hasPrefix("summary_") ? "query_project_summaries" : "query_tasks"+        let arguments: [String: Any]+        switch mode {+        case "summary_replay": arguments = ["snapshotId": root.capture.metadata.snapshotId]+        case "task_snapshot":+            arguments = ["snapshotId": root.capture.metadata.snapshotId, "detailLevel": "summary",+                         "includeComments": false, "limit": 1]+        default: arguments = ["cursor": reusableCursor]+        }+        let code = mode.hasSuffix("cursor") ? "INVALID_CURSOR" : "INVALID_SNAPSHOT"+        try expectError(try await call(env, tool: tool, arguments: arguments), code: code)+        let accounting = try store.domain.accounting(for: store.publicationStoreID)+        #expect(accounting.visibleEntries <= before.visibleEntries && accounting.visibleBytes <= before.visibleBytes)+        #expect(accounting.pendingEntries == 0 && accounting.pendingBytes == 0)+    }++    @Test func cachedAndDefaultPolicyAreAdvertisedInExecutionMetadata() async throws {+        let env = try makeEnvironment(taskCount: 0)+        let cached = try await summary(env)+        let cachedRead = try #require(cached.metadata["read"] as? [String: Any])+        #expect(+            cachedRead["policy"] as? String == "cached"+                && cachedRead["refreshOutcome"] as? String == "not_requested")+        var arguments = initialArguments+        arguments.removeValue(forKey: "readPolicy")+        let automatic = try decode(+            try await call(env, tool: "query_project_summaries", arguments: arguments))+        let read = try #require(automatic.metadata["read"] as? [String: Any])+        #expect(read["policy"] as? String == "refresh_if_needed" && read["budgetMs"] as? Int == 5_000)+    }++    @Test func fallbackStorageAllowsSummaryReadAndReportsLocalEvidence() async throws {+        let env = try makeEnvironment(persistence: FallbackOutcomeFixture.degraded)+        let result = try await summary(env)+        #expect((result.payload["projects"] as? [[String: Any]])?.count == 2)+        #expect(result.metadata["snapshotId"] is String)+    }++    @Test func ordinaryQueriesRetainRawStatusOrderingFieldsAndLegacyNonterminalCount() async throws {+        let env = try makeEnvironment()+        let ideas = try queryResults(+            try await call(env, tool: "query_tasks", arguments: ordinaryArguments(["status": ["idea"]])))+        #expect(ideas.count == 1 && ideas.first?["displayId"] as? Int == 1)+        let all = try queryResults(+            try await call(env, tool: "query_tasks", arguments: ordinaryArguments()))+        #expect(+            all.count == 9+                && all.contains { $0["status"] as? String == "legacy-status" && $0["displayId"] as? Int == 9 })+        #expect(+            all.allSatisfy { $0["revision"] == nil && $0["description"] == nil && $0["comments"] == nil })+        let ids = all.compactMap { $0["taskId"] as? String }+        #expect(ids == ids.sorted())+        let projects = try arrayResult(+            try await call(env, tool: "get_projects", arguments: [:]))+        #expect(+            projects.first { $0["projectId"] as? String == projectID.uuidString }?["activeTaskCount"]+                as? Int+                == 7)+    }+}++extension MCPPortfolioHandlerTests {+    private var projectID: UUID { MCPPortfolioFixture.populatedProjectID }+    private var reusableCursor: String { "00000000-0000-8000-8000-000000000099" }+    private var initialArguments: [String: Any] {+        [+            "start": "2026-10-03T00:00:00Z", "end": "2026-10-03T01:00:00Z", "limit": 100,+            "readPolicy": "cached"+        ]+    }++    private func ordinaryArguments(_ patch: [String: Any] = [:]) -> [String: Any] {+        var arguments: [String: Any] = [+            "detailLevel": "summary", "includeComments": false, "limit": 100,+            "readPolicy": "cached"+        ]+        arguments.merge(patch) { _, replacement in replacement }+        return arguments+    }++    @MainActor private final class FailingCaptureSource: MCPReadCaptureSource {+        let error: MCPReadCaptureError+        init(error: MCPReadCaptureError) { self.error = error }+        func capture(_ request: ReadCaptureRequest) throws -> CapturedReadView { throw error }+    }++    // swiftlint:disable:next function_body_length+    private func makeEnvironment(+        taskCount: Int = 9, projectCount: Int = 2, persistence: PersistenceAvailability? = nil,+        captureFailure: MCPReadCaptureError? = nil+    ) throws -> MCPTestEnv {+        // makeEnv owns the in-memory, CloudKit-none TestModelContainer centrally.+        let availability = persistence ?? FallbackOutcomeFixture.makeHealthy()+        let base = try MCPTestHelpers.makeEnv(persistence: availability)+        let domain = MCPReadPublicationDomain()+        let snapshots = MCPTaskQuerySnapshotStore(domain: domain)+        let coordinator = MCPReadCoordinator(domain: domain)+        let monitor = MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil)+        let builder = MCPReadCaptureBuilder(+            container: base.context.container, fence: .actorOnlyTestFixture,+            fetchTasks: { context in+                if let captureFailure { throw captureFailure }+                return try context.fetch(FetchDescriptor<TransitTask>())+            }+        )+        let source: any MCPReadCaptureSource = captureFailure == .serializationFailure+            ? FailingCaptureSource(error: .serializationFailure) : builder+        let readService = MCPReadService(source: source, monitor: monitor, snapshots: snapshots,+            pagePreparer: { try MCPModernProviderBinding.prepareReadPages($0, tool: $1, operation: $2) })+        let handler = MCPToolHandler(+            taskService: base.taskService, projectService: base.projectService,+            commentService: base.commentService, milestoneService: base.milestoneService,+            maintenanceService: base.maintenanceService, settings: base.mcpSettings,+            persistence: availability, taskQuerySnapshots: snapshots,+            writeCoordinator: base.writeCoordinator,+            readService: readService, readCoordinator: coordinator+        )+        // The delivered initializer registers its default reusable store in this same publication domain.+        // Portfolio owner helpers remain explicit task-12 scaffolds; no alternate store injection is needed.+        let env = MCPTestEnv(+            handler: handler, taskService: base.taskService, projectService: base.projectService,+            commentService: base.commentService, milestoneService: base.milestoneService,+            maintenanceService: base.maintenanceService, mcpSettings: base.mcpSettings,+            context: base.context, writeCoordinator: base.writeCoordinator,+            sidecarDirectory: base.sidecarDirectory+        )+        env.context.autosaveEnabled = false+        guard projectCount > 0 else { return env }+        let project = MCPTestHelpers.makeProject(in: env.context, name: "Alpha")+        project.id = projectID+        if projectCount > 1 {+            let empty = MCPTestHelpers.makeProject(in: env.context, name: "Beta")+            empty.id = MCPPortfolioFixture.emptyProjectID+        }+        let statuses = MCPSnapshotTaskQueryRequest.supportedStatuses + ["legacy-status"]+        for index in 0..<taskCount {+            let task = TransitTask(+                name: "Task \(index)", type: .feature, project: project, displayID: .permanent(index + 1))+            task.id = UUID(uuidString: String(format: "00000000-0000-4001-8000-%012d", index + 1))!+            task.statusRawValue = statuses[index % statuses.count]+            task.creationDate = MCPPortfolioFixture.window.start.addingTimeInterval(-60)+            task.lastStatusChangeDate = task.creationDate+            task.taskDescription = "Secret description \(index)"+            task.metadata = ["fixture": "Secret metadata \(index)"]+            if task.statusRawValue == "done" { task.completionDate = MCPPortfolioFixture.window.start }+            if task.statusRawValue == "abandoned" { task.completionDate = MCPPortfolioFixture.window.end }+            env.context.insert(task)+            let comment = Comment(+                content: "Secret comment \(index)", authorName: "Test", isAgent: false, task: task)+            comment.creationDate = task.creationDate+            env.context.insert(comment)+        }+        try env.context.save()+        return env+    }++    /// Seed a truthful empty saved capture through the already-implemented store, not scaffold handlers.+    private func seedEmptyReusableRoot(+        _ env: MCPTestEnv, store: MCPReusableSnapshotStore, cursor: String? = nil+    ) throws -> RetainedView {+        let capture = try MCPReadCaptureBuilder(container: env.context.container, fence: .actorOnlyTestFixture)+            .capture(ReadCaptureRequest(projectSelectors: nil, selection: .portfolio,+                                        completeness: .completePortfolio, includeComments: false))+        #expect(capture.projects.isEmpty && capture.tasks.isEmpty && capture.milestones.isEmpty)+        let metadata = try JSONEncoder().encode(capture.metadata)+        let counts = Dictionary(uniqueKeysWithValues: MCPSnapshotTaskQueryRequest.supportedStatuses.map { ($0, 0) })+        let empty: [String: Any] = ["countsByStatus": counts, "totalTaskCount": 0,+            "recentCompletions": ["done": 0, "abandoned": 0, "missingCompletionDateCount": 0]]+        let formatter = ISO8601DateFormatter()+        formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+        let asOf = try #require(formatter.date(from: capture.metadata.asOf))+        let duration = capture.createdAt.duration(to: capture.retentionDeadline).components+        let retainedSeconds = Double(duration.seconds) + Double(duration.attoseconds) / 1e18+        let expiry = MCPRecordSnapshot.timestamp(asOf.addingTimeInterval(retainedSeconds))+        let payload: [String: Any] = ["projects": [], "unresolvedProjects": empty, "diagnostics": [],+            "completionWindow": ["start": "2026-10-03T00:00:00.000Z", "end": "2026-10-03T01:00:00.000Z"],+            "nextCursor": cursor as Any? ?? NSNull(), "expiresAt": expiry]+        let root = RetainedView(capture: capture, frozenMetadataBytes: metadata,+            window: MCPPortfolioFixture.window, initialRequest: try MCPPortfolioSummaryRequest.parse(initialArguments),+            firstPage: try JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]))+        let pages = try cursor.map { _ in [try JSONSerialization.data(withJSONObject: [+            "projects": [], "unresolvedProjects": empty, "diagnostics": [],+            "completionWindow": payload["completionWindow"]!, "nextCursor": NSNull(), "expiresAt": expiry+        ], options: [.sortedKeys])] } ?? []+        let bundle = EncodedViewBundle(root: root, pages: pages, cursors: cursor.map { [$0] } ?? [],+                                       encodedCaptureByteCount: metadata.count)+        let reservation = try store.reserveCreate(bundle: bundle, publicationDeadline: capture.retentionDeadline)+        let publication = try store.prepare(reservation: reservation)+        try store.domain.withLock {+            if let rejection = publication.validateLocked(in: store.domain) { throw rejection }+            publication.commitLocked(in: store.domain)+        }+        return root+    }++    private func call(_ env: MCPTestEnv, tool: String, arguments: [String: Any]) async throws -> Data {+        let rpc = MCPTestHelpers.toolCallRequest(tool: tool, arguments: arguments, id: 2382)+        let bytes: Data+        if ["query_project_summaries", "query_tasks", "get_projects"].contains(tool) {+            // Classifier registration is part of task 10; never fabricate an admitted portfolio request.+            let classified = try #require(+                MCPBoundedReadDispatcher.classify(rpc),+                "Covered read must be registered with the authoritative bounded dispatcher: \(tool)")+            bytes = try await MCPBoundedReadDispatcher.response(+                for: classified, rpc: rpc, handler: env.handler,+                coordinator: env.handler.readCoordinator, admittedAt: .now+            )+        } else {+            let response = try #require(await env.handler.handle(rpc))+            bytes = try JSONEncoder().encode(response)+        }+        #expect(try envelope(bytes)["id"] as? Int == 2382)+        return bytes+    }++    private func listResponse(_ env: MCPTestEnv) async throws -> Data {+        let response = try #require(+            await env.handler.handle(MCPTestHelpers.request(method: "tools/list")))+        return try JSONEncoder().encode(response)+    }++    private func summary(_ env: MCPTestEnv, patch: [String: Any] = [:]) async throws -> WireResult {+        try decode(+            try await call(+                env, tool: "query_project_summaries",+                arguments: initialArguments.merging(patch) { _, new in new }))+    }++    private struct WireResult {+        let payload: [String: Any]+        let metadata: [String: Any]+    }++    private func decode(_ response: Data) throws -> WireResult {+        #expect(try envelope(response)["error"] == nil)+        let result = try #require(try envelope(response)["result"] as? [String: Any])+        #expect(result["isError"] as? Bool != true)+        let payload = try self.payload(response)+        let metadata = try #require(+            (result["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any])+        return WireResult(payload: payload, metadata: metadata)+    }++    private func envelope(_ response: Data) throws -> [String: Any] {+        try #require(+            try JSONSerialization.jsonObject(with: response) as? [String: Any])+    }++    private func expectBoundedLimit(_ properties: [String: Any]) throws {+        let limit = try #require(properties["limit"] as? [String: Any])+        #expect(limit["minimum"] as? Int == 1 && limit["maximum"] as? Int == 100)+    }++    private func contentValue(_ response: Data) throws -> Any {+        let result = try #require(try envelope(response)["result"] as? [String: Any])+        let content = try #require(result["content"] as? [[String: Any]])+        let text = try #require(content.first?["text"] as? String)+        return try JSONSerialization.jsonObject(with: Data(text.utf8))+    }++    private func payload(_ response: Data) throws -> [String: Any] {+        try #require(try contentValue(response) as? [String: Any])+    }++    private func queryResults(_ response: Data) throws -> [[String: Any]] {+        try #require(try payload(response)["results"] as? [[String: Any]])+    }++    private func arrayResult(_ response: Data) throws -> [[String: Any]] {+        try #require(try contentValue(response) as? [[String: Any]])+    }++    private func isError(_ response: Data) throws -> Bool {+        (try envelope(response)["result"] as? [String: Any])?["isError"] as? Bool == true+    }++    private func expectError(_ response: Data, code: String) throws {+        #expect(try envelope(response)["error"] == nil)+        #expect(try isError(response))+        let payload = try self.payload(response)+        let error = try #require(payload["error"] as? [String: Any])+        #expect(error["code"] as? String == code)+        #expect(payload["projects"] == nil && payload["results"] == nil && payload["nextCursor"] == nil)+        if let read = ((try envelope(response)["result"] as? [String: Any])?["_meta"] as? [String: Any])?[+            "me.nore.ig.transit/read"] as? [String: Any] {+            #expect(read["snapshotId"] == nil && read["asOf"] == nil)+            if ["QUERY_CAPACITY_EXCEEDED", "INVALID_SNAPSHOT", "INVALID_CURSOR", "SNAPSHOT_INCOMPATIBLE"]+                .contains(code) {+                #expect(read["category"] as? String != "storage_failure")+            }+        }+    }++    private func equalJSON(_ first: Any?, _ second: Any?) -> Bool {+        guard let first, let second else { return first == nil && second == nil }+        return NSDictionary(dictionary: ["value": first]).isEqual(to: ["value": second])+    }+}+#endif
Transit/TransitTests/MCPPortfolioIntegrationTests.swift Modified
diff --git a/Transit/TransitTests/MCPPortfolioIntegrationTests.swift b/Transit/TransitTests/MCPPortfolioIntegrationTests.swiftindex 9499d81a..a4701f9d 100644--- a/Transit/TransitTests/MCPPortfolioIntegrationTests.swift+++ b/Transit/TransitTests/MCPPortfolioIntegrationTests.swift@@ -55,6 +55,44 @@ struct MCPPortfolioIntegrationTests {         }     } +    @Test(arguments: [UInt64(0x2382), UInt64(0x63), UInt64(0x17)])+    func seededSavedRouterPagesReconcileAndRemainFrozenAfterMutation(seed: UInt64) async throws {+        let env = try Environment(taskCount: 48, commentOnEveryTask: true)+        try await withDrainedEnvironment(env) {+            let capture = try seedSavedRecords(env, seed: seed)+            let summary = try success(try await request(env, tool: "query_project_summaries", arguments: initial))+            let snapshot = try #require(summary.metadata["snapshotId"] as? String)+            let original = try #require(try await taskPages(+                env, snapshot: snapshot, metadata: summary.metadata, limit: 7))+            try reconcile(summary, rows: original, expected: capture)+            try reconcileGeneratedCompletions(summary, expected: capture)+            for status in MCPSnapshotTaskQueryRequest.supportedStatuses {+                var arguments = taskArguments(snapshot, limit: 100)+                arguments["status"] = [status]+                let filtered = try success(try await request(env, tool: "query_tasks", arguments: arguments))+                let rows = try #require(filtered.payload["results"] as? [[String: Any]])+                #expect(rows.count == capture.tasks.filter { $0.effectiveStatus == status }.count)+                #expect(Set(rows.compactMap { $0["taskId"] as? String })+                        == Set(capture.tasks.filter { $0.effectiveStatus == status }.map { $0.id.uuidString }))+                #expect(try canonical(filtered.metadata) == canonical(summary.metadata))+                #expect(filtered.payload["nextCursor"] is NSNull)+            }+            env.fixture.tasks[0].statusRawValue = "done"+            env.fixture.tasks[0].taskDescription = "Changed after seeded capture"+            env.fixture.comment.content = "Changed seeded comment evidence"+            try env.fixture.owner.context.save()+            let replay = try success(try await request(+                env, tool: "query_project_summaries", arguments: ["snapshotId": snapshot]))+            #expect(try canonical(replay.payload) == canonical(summary.payload))+            #expect(try canonical(replay.metadata) == canonical(summary.metadata))+            let frozen = try #require(try await taskPages(+                env, snapshot: snapshot, metadata: summary.metadata, limit: 7))+            #expect(try canonical(frozen) == canonical(original))+            try reconcile(replay, rows: frozen, expected: capture)+            #expect(env.fetchCount.value == 1)+        }+    }+     @Test func admissionLifecycleInvalidatesPublishedRootAndCursorWithoutAppendPublication() async throws {         let env = try Environment()         try await withDrainedEnvironment(env) {@@ -106,10 +144,13 @@ private extension MCPPortfolioIntegrationTests {     @MainActor struct Environment {         let fixture: MCPPortfolioSavedFixture         let handler: MCPToolHandler+        let fetchCount: CaptureCounter          init(taskCount: Int = 9, commentOnEveryTask: Bool = false) throws {             fixture = try MCPPortfolioSavedFixture(taskCount: taskCount, commentOnEveryTask: commentOnEveryTask)             let context = fixture.owner.context+            let counter = CaptureCounter()+            fetchCount = counter             let taskAllocator = DisplayIDAllocator(store: InMemoryCounterStore())             let milestoneAllocator = DisplayIDAllocator(store: InMemoryCounterStore())             let tasks = TaskService(modelContext: context, displayIDAllocator: taskAllocator)@@ -121,7 +162,10 @@ private extension MCPPortfolioIntegrationTests {             let domain = MCPReadPublicationDomain()             let snapshots = MCPTaskQuerySnapshotStore(domain: domain)             let service = MCPReadService(source: MCPReadCaptureBuilder(container: fixture.owner.container,-                fence: .actorOnlyTestFixture),+                fence: .actorOnlyTestFixture, fetchTasks: { context in+                    counter.value += 1+                    return try context.fetch(FetchDescriptor<TransitTask>())+                }),                 monitor: MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil),                 snapshots: snapshots, pagePreparer: {                     try MCPModernProviderBinding.prepareReadPages($0, tool: $1, operation: $2)@@ -133,6 +177,44 @@ private extension MCPPortfolioIntegrationTests {         }     } +    @MainActor final class CaptureCounter { var value = 0 }++    func seedSavedRecords(_ env: Environment, seed: UInt64) throws -> CapturedReadView {+        var state = seed+        let statuses = MCPSnapshotTaskQueryRequest.supportedStatuses + ["unknown"]+        let offsets: [TimeInterval?] = [-1, 0, 3_599, 3_600, nil]+        for (index, task) in env.fixture.tasks.enumerated() {+            state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407+            task.statusRawValue = statuses[Int(state % UInt64(statuses.count))]+            task.taskDescription = "Seed \(seed), record \(index), value \(state)"+            task.metadata = ["seed": "\(seed)", "generated": "\(state)"]+            state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407+            task.completionDate = offsets[Int(state % UInt64(offsets.count))].map {+                MCPPortfolioFixture.window.start.addingTimeInterval($0)+            }+        }+        try env.fixture.owner.context.save()+        return try env.fixture.capture()+    }++    func reconcileGeneratedCompletions(_ summary: Result, expected: CapturedReadView) throws {+        let projects = try #require(summary.payload["projects"] as? [[String: Any]])+        let project = try #require(projects.first {+            $0["projectId"] as? String == MCPPortfolioFixture.populatedProjectID.uuidString+        })+        let recent = try #require(project["recentCompletions"] as? [String: Int])+        let terminal = expected.tasks.filter { ["done", "abandoned"].contains($0.effectiveStatus) }+        #expect(recent["missingCompletionDateCount"] == terminal.filter { $0.completionDate == nil }.count)+        for status in ["done", "abandoned"] {+            let inside = terminal.filter {+                guard let date = $0.completionDate else { return false }+                return $0.effectiveStatus == status && date >= MCPPortfolioFixture.window.start+                    && date < MCPPortfolioFixture.window.end+            }+            #expect(recent[status] == inside.count)+        }+    }+     struct Result {         let payload: [String: Any]         let metadata: [String: Any]
Transit/TransitTests/MCPPortfolioInterfaceTests.swift Added
diff --git a/Transit/TransitTests/MCPPortfolioInterfaceTests.swift b/Transit/TransitTests/MCPPortfolioInterfaceTests.swiftnew file mode 100644index 00000000..59402c58--- /dev/null+++ b/Transit/TransitTests/MCPPortfolioInterfaceTests.swift@@ -0,0 +1,23 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPPortfolioInterfaceTests {+    @Test func realFixtureBindsSharedDTOsAndCanonicalCommentCoveredRevision() throws {+        let fixture = try MCPPortfolioSavedFixture()+        let captured = try fixture.capture()+        #expect(captured.tasks.count == MCPPortfolioFixture.expectedTaskCount)+        #expect(captured.projects.count == 2 && captured.milestones.count == 2)+        #expect(captured.captureScope == .wholePortfolio)+        let model = fixture.tasks[6]+        let record = try #require(captured.tasks.first { $0.id == model.id })+        #expect(record.revision == (try MCPRecordSnapshot.task(model, in: fixture.owner.context).revision))+        #expect(record.commentKeys == captured.comments.map(\.physicalKey))+        #expect(record.requestedCommentRecordsJSON == nil)+        #expect(record.fullRecordWithoutCommentsJSON != nil)+    }++}+#endif
Transit/TransitTests/MCPPortfolioModernAcceptanceTests.swift Modified
diff --git a/Transit/TransitTests/MCPPortfolioModernAcceptanceTests.swift b/Transit/TransitTests/MCPPortfolioModernAcceptanceTests.swiftindex 67c89160..344092c9 100644--- a/Transit/TransitTests/MCPPortfolioModernAcceptanceTests.swift+++ b/Transit/TransitTests/MCPPortfolioModernAcceptanceTests.swift@@ -129,6 +129,9 @@ struct MCPPortfolioModernAcceptanceTests {             let replayResponse = try await send(                 env, tool: "query_project_summaries", arguments: ["snapshotId": snapshot], id: 2383)             let replay = try checkedSource(replayResponse, id: 2383)+            let sealed = try #require(root.preparedResultPage)+            let expected = try MCPResultEncoder.encode(fragment: sealed.fragment, id: .integer(2383))+            #expect(replayResponse.body == expected)             #expect(replay.text == summary.text && replay.value == summary.value)             try exactMetadata(replayResponse, bytes: root.frozenMetadataBytes)             #expect(env.fetchCount.value == 1)
Transit/TransitTests/MCPPortfolioProjectionTests.swift Added
diff --git a/Transit/TransitTests/MCPPortfolioProjectionTests.swift b/Transit/TransitTests/MCPPortfolioProjectionTests.swiftnew file mode 100644index 00000000..16b8d4c8--- /dev/null+++ b/Transit/TransitTests/MCPPortfolioProjectionTests.swift@@ -0,0 +1,99 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPPortfolioProjectionTests {+    @Test func fullDetailPreservesEveryCapturedFieldAndCommentCoveredRevision() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let task = try #require(capture.tasks.first { !$0.commentKeys.isEmpty })+        let canonical = try object(#require(task.fullRecordWithoutCommentsJSON))+        let output = try object(MCPPortfolioProjection.task(record: task, detail: .full).json)+        for (key, value) in canonical where key != "status" {+            #expect(NSDictionary(dictionary: [key: value]).isEqual(to: [key: output[key] as Any]))+        }+        #expect(output["revision"] as? String == task.revision)+        #expect(task.revision?.hasPrefix("r1:") == true)+        #expect(output["description"] as? String == task.taskDescription)+        #expect(output["metadata"] as? [String: String] == task.metadata)+        #expect(output["comments"] == nil && output["commentKeys"] == nil)+        let rendered = try #require(String(data: JSONSerialization.data(withJSONObject: output), encoding: .utf8))+        #expect(!rendered.contains("Canonical comment coverage"))+    }++    @Test func summaryHasOrdinarySummaryFieldsWithoutFullBodies() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let task = try #require(capture.tasks.first { $0.rawStatus == "done" })+        let canonical = try object(#require(task.fullRecordWithoutCommentsJSON))+        let output = try object(MCPPortfolioProjection.task(record: task, detail: .summary).json)+        let expectedKeys: Set<String> = [+            "taskId", "name", "status", "type", "priority", "lastStatusChangeDate",+            "displayId", "projectId", "projectName", "completionDate", "milestone"+        ]+        #expect(Set(output.keys) == Set(canonical.keys).intersection(expectedKeys))+        for key in expectedKeys where canonical[key] != nil {+            #expect(NSDictionary(dictionary: [key: canonical[key] as Any]).isEqual(to: [key: output[key] as Any]))+        }+        #expect(output["description"] == nil && output["metadata"] == nil && output["comments"] == nil)+    }++    @Test(arguments: ["summary", "full"])+    func unknownStoredStatusFallsBackWithoutChangingCanonicalRevision(detail: String) throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let task = try #require(capture.tasks.first { $0.rawStatus == "unknown" })+        let output = try object(MCPPortfolioProjection.task(+            record: task, detail: detail == "full" ? .full : .summary).json)+        #expect(output["status"] as? String == "idea" && output["storedStatus"] as? String == "unknown")+        if detail == "full" { #expect(output["revision"] as? String == task.revision) }+        let original = try object(#require(task.fullRecordWithoutCommentsJSON))+        #expect(original["status"] as? String == "unknown")+    }++    @Test func knownStatusDoesNotInventStoredStatusField() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let task = try #require(capture.tasks.first { $0.rawStatus == "planning" })+        for detail in [SnapshotTaskDetail.summary, .full] {+            let output = try object(MCPPortfolioProjection.task(record: task, detail: detail).json)+            #expect(output["status"] as? String == "planning" && output["storedStatus"] == nil)+        }+    }++    @Test func frozenMetadataBytesAreRetainedExactlyRatherThanReencoded() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let helper = MCPReusableSnapshotStoreTests()+        let initial = try helper.bundle(capture)+        // Valid metadata with intentional wire whitespace proves byte preservation.+        let frozen = Data(" \n".utf8) + initial.root.frozenMetadataBytes + Data("\n ".utf8)+        let root = RetainedView(capture: initial.root.capture, frozenMetadataBytes: frozen,+                                window: initial.root.window, initialRequest: initial.root.initialRequest,+                                firstPage: initial.root.firstPage)+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let bundle = EncodedViewBundle(root: root, pages: [], cursors: [], encodedCaptureByteCount: 100)+        try helper.commit(helper.stage(bundle, store: store), in: domain)+        let retained = try store.retainedView(for: root.capture.metadata.snapshotId, now: capture.createdAt)+        #expect(retained.frozenMetadataBytes == frozen)+        let plan = try MCPPortfolioProjection.query(root: retained, request: query(retained))+        #expect(plan.frozenMetadataBytes == frozen)+    }++    func object(_ data: Data) throws -> [String: Any] {+        try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])+    }++    func query(_ root: RetainedView, detail: SnapshotTaskDetail = .summary, limit: Int = 2,+               projectId: UUID? = nil, statuses: [String] = []) -> MCPSnapshotTaskQueryRequest {+        .initial(snapshotId: root.capture.metadata.snapshotId, detail: detail, limit: limit,+                 projectId: projectId, statuses: statuses)+    }++    func rows(_ plan: EncodedSnapshotTaskPages) throws -> [[String: Any]] {+        try ([plan.firstPage] + plan.pages).flatMap { try #require(object($0)["results"] as? [[String: Any]]) }+    }++    func args() -> [String: Any] {+        ["snapshotId": UUID().uuidString, "detailLevel": "summary", "includeComments": false, "limit": 2]+    }+}+#endif
Transit/TransitTests/MCPPortfolioReadFoundationTests.swift Added
diff --git a/Transit/TransitTests/MCPPortfolioReadFoundationTests.swift b/Transit/TransitTests/MCPPortfolioReadFoundationTests.swiftnew file mode 100644index 00000000..69610a36--- /dev/null+++ b/Transit/TransitTests/MCPPortfolioReadFoundationTests.swift@@ -0,0 +1,233 @@+#if os(macOS)+import Foundation+import Hummingbird+import NIOCore+import NIOConcurrencyHelpers+import NIOFoundationCompat+import SwiftData+import Testing+@testable import Transit++@Suite(.serialized)+nonisolated struct MCPPortfolioReadFoundationTests {+    @Test @MainActor func reusableCaptureAdapterEncodesAllEvidenceAndPreservesPendingEdits() throws {+        let fixture = try MCPPortfolioSavedFixture()+        let original = try fixture.capture()+        fixture.project.name = "Unsaved project"+        fixture.tasks[6].taskDescription = "Unsaved description"+        fixture.comment.content = "Unsaved body"+        let saved = try fixture.capture()+        #expect(saved.projects.first { $0.id == fixture.project.id }?.name == "Populated")+        #expect(saved.tasks.first { $0.id == fixture.tasks[6].id }?.revision+                == original.tasks.first { $0.id == fixture.tasks[6].id }?.revision)+        #expect(saved.comments.first?.content == "Canonical comment coverage")+        #expect(fixture.owner.context.hasChanges)+        let result = try MCPPortfolioFoundationHarness.prepareCapture(saved)+        let envelope = try #require(try JSONSerialization.jsonObject(with: result.encodedResponse) as? [String: Any])+        #expect(envelope["taskCount"] as? Int == 9)+        #expect((envelope["records"] as? [String])?.count == 9)+        #expect(envelope["snapshotId"] as? String == saved.metadata.snapshotId)+        #expect(envelope["asOf"] as? String == saved.metadata.asOf)+        #expect(result.publications.isEmpty)+    }++    // swiftlint:disable:next function_body_length+    @Test @concurrent func actualRouterBoundsComplete2375TaskCaptureAndRevisionEncoding() async throws {+        let setupStart = ContinuousClock.now+        let fixture = try await MainActor.run {+            try MCPPortfolioSavedFixture(taskCount: 2_375, commentOnEveryTask: true)+        }+        print("PORTFOLIO_VOLUME fixture_setup_elapsed=\(setupStart.duration(to: .now))")+        let coordinator = MCPReadCoordinator()+        let completion = PortfolioFoundationCompletion()+        let start = ContinuousClock.now+        let bytes = try await MCPPortfolioFoundationHarness.route {+            await MCPReadTransportAdapter.response(coordinator: coordinator,+                timeout: MCPPortfolioFoundationHarness.timeout, busy: MCPPortfolioFoundationHarness.busy) { _ in+                let physicalStart = ContinuousClock.now+                let result: PreparedReadResult+                do {+                    let view = try await MainActor.run { try fixture.capture() }+                    print("PORTFOLIO_VOLUME saved_capture_elapsed=\(physicalStart.duration(to: .now))")+                    #expect(view.tasks.count == 2_375 && view.comments.count == 2_376)+                    #expect(view.captureScope == .wholePortfolio)+                    #expect(view.tasks.allSatisfy {+                        $0.revision?.hasPrefix("r1:") == true && $0.fullRecordWithoutCommentsJSON != nil+                            && !$0.commentKeys.isEmpty && $0.requestedCommentRecordsJSON == nil+                    })+                    result = try MCPPortfolioFoundationHarness.prepareCapture(view)+                    print("PORTFOLIO_VOLUME encoded_full_envelope_bytes=\(result.encodedResponse.count) "+                          + "canonical_records=\(view.tasks.count) comment_evidence=\(view.comments.count)")+                } catch {+                    Issue.record("Portfolio capture/adapter failed: \(error)")+                    result = MCPPortfolioFoundationHarness.result(MCPPortfolioFoundationHarness.busy)+                }+                print("PORTFOLIO_VOLUME capture_and_encode_physical_elapsed=\(physicalStart.duration(to: .now))")+                await completion.finish()+                return result+            }+        }+        let elapsed = start.duration(to: .now)+        print("PORTFOLIO_VOLUME router_and_body_elapsed=\(elapsed) tasks=2375 bytes=\(bytes.count)")+        #expect(elapsed <= .seconds(5))+        if bytes != MCPPortfolioFoundationHarness.timeout && bytes != MCPPortfolioFoundationHarness.capacity {+            let envelope = try #require(try JSONSerialization.jsonObject(with: bytes) as? [String: Any])+            #expect(envelope["taskCount"] as? Int == 2_375)+            #expect((envelope["records"] as? [String])?.count == 2_375)+            #expect((envelope["taskEvidence"] as? [[String: Any]])?.count == 2_375)+            #expect((envelope["comments"] as? [[String: Any]])?.count == 2_376)+        }+        // Await physical completion before releasing the shared test slot or owning fixture.+        // A timed-out physical capture remains admitted. Cleanup is a diagnostic limit,+        // not a relaxed response budget or early permit release.+        for _ in 0..<1_200 where !(await completion.isFinished) {+            try await Task.sleep(for: .milliseconds(100))+        }+        #expect(await completion.isFinished)+        for _ in 0..<100 where coordinator.unfinishedCount != 0 {+            try await Task.sleep(for: .milliseconds(10))+        }+        #expect(coordinator.unfinishedCount == 0)+        await MainActor.run { withExtendedLifetime(fixture) {} }+    }++    @Test @MainActor func mixedFixtureWaitsForProtectedWriteAndPreservesSavedReceipt() async throws {+        let env = try MCPTestHelpers.makeEnv()+        let handler = env.handler+        let coordinator = MCPReadCoordinator()+        let key = "portfolio-foundation-mixed-write"+        let started = ContinuousClock.now+        let bytes = try await MCPPortfolioFoundationHarness.route {+            let read = await coordinator.execute(timeout: MCPPortfolioFoundationHarness.timeout,+                                                busy: MCPPortfolioFoundationHarness.busy) { _ in+                MCPPortfolioFoundationHarness.result(Data("{\"read\":\"complete\"}".utf8))+            }+            // Synthetic mixed adapter waits for a protected write, never wraps the+            // combined response in a read-only deadline or rewrites its saved result.+            let write = await Task { @MainActor in+                try? await Task.sleep(for: .seconds(6))+                let response = await handler.handle(MCPTestHelpers.toolCallRequest(+                    tool: "create_project", arguments: ["name": "Mixed saved", "colorHex": "#112233",+                                                       "idempotencyKey": key]))+                return (try? JSONEncoder().encode(response)) ?? Data()+            }.value+            let batch = MCPReadBatchEncoding.array([read, write]) ?? Data()+            return Response(status: .ok, body: .init(byteBuffer: ByteBuffer(data: batch)))+        }+        #expect(started.duration(to: .now) >= .seconds(6))+        let frames = try #require(try JSONSerialization.jsonObject(with: bytes) as? [[String: Any]])+        #expect(frames.first?["read"] as? String == "complete")+        let receipt = try #require(try env.context.fetch(FetchDescriptor<MCPWriteReceipt>()).first { $0.key == key })+        #expect(receipt.stateRawValue == "committed")+        let content = try #require((frames.last?["result"] as? [String: Any])?["content"] as? [[String: Any]])+        #expect(content.first?["text"] as? String == receipt.resultJSON)+        #expect(coordinator.unfinishedCount == 0)+    }++    @Test @concurrent func blockedMainActorCannotDelayRouterTimeoutOrPublishLate() async throws {+        let coordinator = MCPReadCoordinator()+        let publication = PortfolioFoundationPublication(domain: coordinator.domain)+        let started = DispatchSemaphore(value: 0)+        let blockerFinished = NIOLockedValueBox(false)+        let blocker = Task { @MainActor in+            defer { blockerFinished.withLockedValue { $0 = true } }+            guard !Task.isCancelled else { return }+            Self.blockMainActor(started)+        }+        let didStart = Self.waitForStart(started)+        if !didStart {+            blocker.cancel()+            let drainDeadline = ContinuousClock.now + .seconds(8)+            while !blockerFinished.withLockedValue({ $0 }) && .now < drainDeadline {+                // Cleanup remains bounded even when the test task is cancelled.+                await Task.detached { try? await Task.sleep(for: .milliseconds(10)) }.value+            }+            #expect(blockerFinished.withLockedValue { $0 }, "Cancelled MainActor blocker failed to drain")+            try #require(didStart, "MainActor blocker did not start within 2 seconds; no read was admitted")+        }+        let start = ContinuousClock.now+        let bytes = try await MCPPortfolioFoundationHarness.route {+            await MCPReadTransportAdapter.response(coordinator: coordinator,+                timeout: MCPPortfolioFoundationHarness.timeout, busy: MCPPortfolioFoundationHarness.busy) { _ in+                await MainActor.run {+                    MCPPortfolioFoundationHarness.result(Data("{\"snapshotId\":\"late\"}".utf8),+                                                        publications: [publication])+                }+            }+        }+        let elapsed = start.duration(to: .now)+        print("PORTFOLIO_BLOCKED router_and_body_elapsed=\(elapsed) blocked_main_actor=6s")+        #expect(bytes == MCPPortfolioFoundationHarness.timeout)+        #expect(elapsed <= .seconds(5))+        #expect(coordinator.unfinishedCount == 1)+        await blocker.value+        for _ in 0..<100 where coordinator.unfinishedCount != 0 {+            try await Task.sleep(for: .milliseconds(5))+        }+        #expect(publication.counts == [false, true])+        #expect(coordinator.unfinishedCount == 0)+    }++    @Test @concurrent func wholeReadOnlyRouterBatchBoundsSlowEncodingAndDiscardsReadyPublication() async throws {+        let coordinator = MCPReadCoordinator()+        let publication = PortfolioFoundationPublication(domain: coordinator.domain)+        let work = MCPReadBatchWork(timeout: MCPPortfolioFoundationHarness.timeout,+                                   busy: MCPPortfolioFoundationHarness.busy, responds: true) { _ in+            MCPPortfolioFoundationHarness.result(Data("{\"snapshotId\":\"private\"}".utf8),+                                                publications: [publication])+        }+        let start = ContinuousClock.now+        let bytes = try await MCPPortfolioFoundationHarness.route {+            let result = await coordinator.executeBatch([.read(work)]) { values in+                Self.slowEncode()+                return MCPPortfolioFoundationHarness.result(+                    MCPReadBatchEncoding.array(values.map { $0?.encodedResponse }) ?? Data(),+                    publications: values.compactMap { $0 }.flatMap(\.publications))+            }+            return Response(status: .ok, body: .init(byteBuffer: ByteBuffer(data: result ?? Data())))+        }+        let elapsed = start.duration(to: .now)+        print("PORTFOLIO_BATCH router_and_body_elapsed=\(elapsed) slow_encode=6s")+        #expect(elapsed <= .seconds(5))+        #expect(bytes == Data("[{\"error\":\"READ_TIMEOUT\"}]".utf8))+        #expect(coordinator.unfinishedCount == 1)+        for _ in 0..<150 where coordinator.unfinishedCount != 0 {+            try await Task.sleep(for: .milliseconds(10))+        }+        #expect(coordinator.unfinishedCount == 0)+        #expect(publication.counts == [false, true])+    }++    @Test @concurrent func routerBodyFailurePreservesErrorAndAwaitsChannelCleanup() async throws {+        let started = ContinuousClock.now+        do {+            _ = try await MCPPortfolioFoundationHarness.route {+                Response(status: .ok, body: .init { writer in+                    try await writer.write(ByteBuffer(string: "partial fixture body"))+                    throw FoundationBodyFailure.intentional+                })+            }+            Issue.record("Throwing response body unexpectedly succeeded")+        } catch let error as FoundationBodyFailure {+            #expect(error == .intentional)+        }+        #expect(started.duration(to: .now) <= .seconds(5))+        let bytes = try await MCPPortfolioFoundationHarness.route {+            Response(status: .ok, body: .init(byteBuffer: ByteBuffer(string: "next clean response")))+        }+        #expect(bytes == Data("next clean response".utf8))+    }++    private enum FoundationBodyFailure: Error, Equatable { case intentional }++    @MainActor private static func blockMainActor(_ signal: DispatchSemaphore) {+        signal.signal()+        Thread.sleep(forTimeInterval: 6)+    }++    private static func waitForStart(_ signal: DispatchSemaphore) -> Bool {+        signal.wait(timeout: .now() + .seconds(2)) == .success+    }+    private static func slowEncode() { Thread.sleep(forTimeInterval: 6) }+}+#endif
Transit/TransitTests/MCPPortfolioReconciliationTests.swift Added
diff --git a/Transit/TransitTests/MCPPortfolioReconciliationTests.swift b/Transit/TransitTests/MCPPortfolioReconciliationTests.swiftnew file mode 100644index 00000000..925a6188--- /dev/null+++ b/Transit/TransitTests/MCPPortfolioReconciliationTests.swift@@ -0,0 +1,230 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++extension MCPPortfolioProjectionTests {+    @Test(arguments: ["idea", "planning", "spec", "ready-for-implementation", "in-progress",+                      "ready-for-review", "done", "abandoned"])+    func everyEffectiveStatusReconcilesAcrossAllPages(status: String) throws {+        let capture = try MCPPortfolioSavedFixture(taskCount: 37).capture()+        let root = try MCPReusableSnapshotStoreTests().bundle(capture).root+        let summary = try PortfolioSummaryService.summarize(view: capture, window: root.window)+        let project = try #require(summary.projects.first { $0.projectId == MCPPortfolioFixture.populatedProjectID })+        let plan = try MCPPortfolioProjection.query(+            root: root, request: query(root, limit: 1, projectId: project.projectId, statuses: [status]))+        let selected = try rows(plan)+        let expected = capture.tasks.filter { $0.effectiveStatus == status }+        #expect(selected.count == expected.count)+        let position = try #require(PortfolioSummaryTestValues.statuses.firstIndex(of: status))+        #expect(selected.count == PortfolioSummaryTestValues.buckets(project.countsByStatus)[position])+        #expect(selected.allSatisfy { $0["status"] as? String == status })+        #expect(selected.compactMap { $0["taskId"] as? String } == expected.map(\.id.uuidString).sorted())+        #expect(plan.pages.count == max(0, selected.count - 1))+        #expect(plan.pages.count == plan.cursors.count && plan.cursors.allSatisfy {+            MCPCursorFamily.classify($0) == .reusable+        })+        #expect(plan.frozenMetadataBytes == root.frozenMetadataBytes)+        #expect(plan.snapshotId == root.capture.metadata.snapshotId)+        #expect(plan.retentionDeadline == root.capture.retentionDeadline)+    }++    @Test func absentAndEmptyFiltersReturnAllRecordsWithDeterministicOrdering() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let reversed = PortfolioSummaryTestValues.view(capture, tasks: Array(capture.tasks.reversed()))+        let root = try MCPReusableSnapshotStoreTests().bundle(reversed).root+        let plan = try MCPPortfolioProjection.query(root: root, request: query(root, limit: 2))+        let selected = try rows(plan)+        #expect(selected.count == capture.tasks.count)+        #expect(selected.compactMap { $0["taskId"] as? String } == capture.tasks.map(\.id.uuidString).sorted())+        let emptyProject = try MCPPortfolioProjection.query(+            root: root, request: query(root, projectId: MCPPortfolioFixture.emptyProjectID))+        #expect(try rows(emptyProject).isEmpty && emptyProject.pages.isEmpty && emptyProject.cursors.isEmpty)+        #expect(try object(emptyProject.firstPage)["nextCursor"] is NSNull)+        #expect(emptyProject.frozenMetadataBytes == plan.frozenMetadataBytes)+    }++    @Test func selectedPhysicalScopeCannotBeExpandedByForeignIdentityClosure() throws {+        let fixture = try MCPPortfolioSavedFixture()+        let foreign = try #require(try fixture.owner.context.fetch(FetchDescriptor<Project>()).first {+            $0.id == MCPPortfolioFixture.emptyProjectID+        })+        let foreignTask = TransitTask(name: "Foreign closure task", type: .feature, project: foreign,+                                      displayID: .permanent(10))+        foreignTask.id = UUID(uuidString: "00000000-0000-4002-8000-000000000001")!+        foreignTask.taskDescription = "Foreign body must remain outside the captured physical scope"+        foreignTask.metadata = ["foreign": "excluded"]+        fixture.owner.context.insert(foreignTask)+        try fixture.owner.context.save()+        let scoped = try MCPReadCaptureBuilder(container: fixture.owner.container, fence: .actorOnlyTestFixture)+            .capture(ReadCaptureRequest(projectSelectors: [.id(fixture.project.id)], selection: .portfolio,+                                        completeness: .completePortfolio, includeComments: false))+        let selected = try #require(scoped.projects.first { $0.id == fixture.project.id })+        let foreignIdentity = try #require(scoped.tasks.first { $0.id == foreignTask.id })+        #expect(scoped.captureScope == .projects([selected.physicalKey]))+        #expect(scoped.tasks.count == 10)+        #expect(scoped.tasks.filter { $0.projectKey == selected.physicalKey }.count == 9)+        #expect(scoped.tasks.filter { $0.projectKey == selected.physicalKey }.allSatisfy {+            $0.revision != nil && $0.fullRecordWithoutCommentsJSON != nil+        })+        #expect(foreignIdentity.projectKey != selected.physicalKey)+        #expect(foreignIdentity.fullRecordWithoutCommentsJSON == nil && foreignIdentity.revision == nil)+        #expect(foreignIdentity.taskDescription == nil && foreignIdentity.metadata.isEmpty)+        let root = try MCPReusableSnapshotStoreTests().bundle(scoped).root+        let plan = try MCPPortfolioProjection.query(root: root, request: query(root))+        let returned = try rows(plan)+        #expect(returned.count == 9)+        #expect(!returned.contains { $0["taskId"] as? String == foreignTask.id.uuidString })+        #expect(throws: MCPReusableSnapshotError.incompatible) {+            try MCPPortfolioProjection.query(+                root: root, request: query(root, projectId: MCPPortfolioFixture.emptyProjectID))+        }+        #expect(throws: MCPReusableSnapshotError.incompatible) {+            try MCPPortfolioProjection.query(root: root, request: query(root, projectId: UUID()))+        }+        let narrowed = try MCPPortfolioProjection.query(root: root, request: query(root, projectId: selected.id))+        #expect(try rows(narrowed).count == 9)+    }++    @Test func selectedQueryAndMismatchedSnapshotCannotMasqueradeAsReusableQuery() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let helper = MCPReusableSnapshotStoreTests()+        let unsupported = [+            PortfolioSummaryTestValues.view(capture, scope: .selectedQuery),+            PortfolioSummaryTestValues.view(capture, completeness: .selectedRead)+        ]+        for view in unsupported {+            let root = try helper.bundle(view).root+            #expect(throws: MCPReusableSnapshotError.incompatible) {+                try MCPPortfolioProjection.query(root: root, request: query(root))+            }+        }+        let valid = try helper.bundle(capture).root+        #expect(throws: MCPReusableSnapshotError.invalidSnapshot) {+            try MCPPortfolioProjection.query(root: valid,+                request: .initial(snapshotId: UUID().uuidString, detail: .summary, limit: 2,+                                  projectId: nil, statuses: []))+        }+        #expect(throws: MCPReusableSnapshotError.incompatible) {+            try MCPPortfolioProjection.query(root: valid,+                request: .continuation(cursor: helper.cursorToken(), policy: nil))+        }+    }++    @Test func ambiguousTaskUUIDIntoSelectedScopeFailsWithoutMergingRecords() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let selected = try #require(capture.projects.first { $0.id == MCPPortfolioFixture.populatedProjectID })+        let foreign = try #require(capture.projects.first { $0.id == MCPPortfolioFixture.emptyProjectID })+        let tasks = capture.tasks.sorted { $0.id.uuidString < $1.id.uuidString }+        let duplicate = PortfolioSummaryTestValues.task(tasks[1], id: tasks[0].id,+                                                        projectKey: .some(foreign.physicalKey))+        let changed = PortfolioSummaryTestValues.view(capture, scope: .projects([selected.physicalKey]),+                                                      tasks: [tasks[0], duplicate])+        let root = try MCPReusableSnapshotStoreTests().bundle(changed).root+        #expect(throws: PortfolioSummaryError.identityAmbiguity) {+            try MCPPortfolioProjection.query(root: root, request: query(root))+        }+    }++    @Test func summaryRowsUseNormalizedNameThenUUIDAndMilestonesUseUUID() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let projects = capture.projects.map { PortfolioSummaryTestValues.project($0, name: " Shared ") }+        let changed = PortfolioSummaryTestValues.view(capture, projects: Array(projects.reversed()),+                                                      milestones: Array(capture.milestones.reversed()))+        let summary = try PortfolioSummaryService.summarize(view: changed, window: MCPPortfolioFixture.window)+        #expect(summary.projects.map(\.projectId.uuidString) == projects.map(\.id.uuidString).sorted())+        for project in summary.projects {+            #expect(project.milestones.map(\.milestoneId.uuidString)+                == project.milestones.map(\.milestoneId.uuidString).sorted())+        }+    }++    @Test func ordinaryTaskStatusFiltersKeepStoredStatusSemantics() throws {+        let fixture = try MCPPortfolioSavedFixture()+        let filters = MCPQueryFilters.from(args: ["status": ["idea"]], type: nil,+                                           projectId: nil, search: nil, milestoneIds: nil)+        let ordinary = fixture.tasks.filter { filters.matches($0) }+        #expect(ordinary.count == 1 && ordinary.allSatisfy { $0.statusRawValue == "idea" })+        let capture = try fixture.capture()+        #expect(capture.tasks.filter { $0.effectiveStatus == "idea" }.count == 2)+    }++    @Test func savedMutationDeletionAndNewStoreTransactionCannotChangeRetainedPages() throws {+        let fixture = try MCPPortfolioSavedFixture(taskCount: 19)+        let capture = try fixture.capture()+        let helper = MCPReusableSnapshotStoreTests()+        let candidate = try helper.bundle(capture)+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        try helper.commit(helper.stage(candidate, store: store), in: domain)+        let root = candidate.root+        let before = try MCPPortfolioProjection.query(root: root, request: query(root, detail: .full, limit: 2))+        fixture.project.name = "Changed live project"+        fixture.tasks[0].statusRawValue = "abandoned"+        fixture.tasks[0].taskDescription = "Changed live description"+        fixture.tasks[0].metadata = ["changed": "live"]+        fixture.comment.content = "Changed live comment"+        let deletedID = fixture.tasks[1].id+        fixture.owner.context.delete(fixture.tasks[1])+        try fixture.owner.context.save()+        // A separate committed context models another writer's transaction, not proof of CloudKit import.+        let otherContext = ModelContext(fixture.owner.container)+        let laterProject = Project(name: "Later saved project", description: "", gitRepo: nil, colorHex: "#778899")+        otherContext.insert(laterProject)+        let added = TransitTask(name: "Later saved task", type: .feature, project: laterProject,+                                displayID: .permanent(500))+        otherContext.insert(added)+        try otherContext.save()+        let current = try fixture.capture()+        #expect(current.tasks.contains { $0.id == added.id })+        #expect(!current.tasks.contains { $0.id == deletedID })+        let retained = try store.retainedView(for: root.capture.metadata.snapshotId, now: capture.createdAt)+        let after = try MCPPortfolioProjection.query(root: retained, request: query(retained, detail: .full, limit: 2))+        #expect(NSArray(array: try rows(before)).isEqual(to: try rows(after)))+        #expect(after.frozenMetadataBytes == before.frozenMetadataBytes)+        #expect(after.snapshotId == before.snapshotId && after.retentionDeadline == before.retentionDeadline)+        #expect(retained.window == root.window)+        #expect(try PortfolioSummaryService.summarize(view: retained.capture, window: retained.window)+            == PortfolioSummaryService.summarize(view: root.capture, window: root.window))+        try verifyPublishedPages(after, root: root, store: store, domain: domain, helper: helper)+    }++    private func verifyPublishedPages(_ plan: EncodedSnapshotTaskPages, root: RetainedView,+                                      store: MCPReusableSnapshotStore, domain: MCPReadPublicationDomain,+                                      helper: MCPReusableSnapshotStoreTests) throws {+        let reservation = try store.reserveAppend(snapshotID: plan.snapshotId, pages: plan.pages, cursors: plan.cursors,+                                                   publicationDeadline: root.capture.retentionDeadline)+        try helper.commit(store.prepare(reservation: reservation), in: domain)+        var page = try object(plan.firstPage)+        let expiry = try #require(page["expiresAt"] as? String)+        let formatter = ISO8601DateFormatter()+        formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+        let capturedAt = try #require(formatter.date(from: root.capture.metadata.asOf))+        let pageExpiry = formatter.date(from: expiry) ?? ISO8601DateFormatter().date(from: expiry)+        #expect(pageExpiry == capturedAt.addingTimeInterval(300))+        var allRows = try #require(page["results"] as? [[String: Any]])+        var visited: Set<String> = []+        while let cursor = page["nextCursor"] as? String {+            try #require(visited.insert(cursor).inserted)+            let retained = try store.page(for: cursor, now: root.capture.createdAt)+            #expect(retained.root.frozenMetadataBytes == root.frozenMetadataBytes)+            #expect(retained.root.window == root.window)+            #expect(retained.root.capture.retentionDeadline == root.capture.retentionDeadline)+            page = try object(retained.encodedPage)+            #expect(page["expiresAt"] as? String == expiry)+            allRows += try #require(page["results"] as? [[String: Any]])+        }+        #expect(page["nextCursor"] is NSNull && allRows.count == root.capture.tasks.count)+        domain.setTestingInstant(root.capture.retentionDeadline)+        #expect(throws: MCPReusableSnapshotError.invalidSnapshot) {+            try store.retainedView(for: plan.snapshotId, now: root.capture.retentionDeadline)+        }+        for cursor in plan.cursors {+            #expect(throws: MCPReusableSnapshotError.invalidCursor) {+                try store.page(for: cursor, now: root.capture.retentionDeadline)+            }+        }+    }+}+#endif
Transit/TransitTests/MCPPortfolioScopedCaptureTests.swift Added
diff --git a/Transit/TransitTests/MCPPortfolioScopedCaptureTests.swift b/Transit/TransitTests/MCPPortfolioScopedCaptureTests.swiftnew file mode 100644index 00000000..8a88b422--- /dev/null+++ b/Transit/TransitTests/MCPPortfolioScopedCaptureTests.swift@@ -0,0 +1,50 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPPortfolioScopedCaptureTests {+    @Test func scopedCaptureDoesNotExpandToUnrelatedTaskBodies() throws {+        let fixture = try MCPPortfolioSavedFixture()+        let foreign = try #require(try fixture.owner.context.fetch(FetchDescriptor<Project>()).first {+            $0.id == MCPPortfolioFixture.emptyProjectID+        })+        let unrelated = TransitTask(name: "Unrelated body", type: .feature, project: foreign,+                                    displayID: .permanent(10))+        unrelated.taskDescription = "Must not be copied for another project's scoped capture"+        fixture.owner.context.insert(unrelated)+        try fixture.owner.context.save()+        let view = try MCPReadCaptureBuilder(container: fixture.owner.container, fence: .actorOnlyTestFixture)+            .capture(ReadCaptureRequest(projectSelectors: [.id(fixture.project.id)], selection: .portfolio,+                                        completeness: .completePortfolio, includeComments: false))+        let selectedKey = try #require(view.projects.first { $0.id == fixture.project.id }?.physicalKey)+        #expect(view.captureScope == .projects([selectedKey]))+        // Identity closure may include endpoint identities; it cannot require a full+        // unrelated task body or revision for this declared scope.+        #expect(!view.tasks.contains { $0.id == unrelated.id && $0.fullRecordWithoutCommentsJSON != nil })+        #expect(view.tasks.filter { $0.projectKey == selectedKey }.count == 9)+        #expect(view.tasks.filter { $0.projectKey == selectedKey }.allSatisfy { $0.revision != nil })+        let identity = try #require(view.tasks.first { $0.id == unrelated.id })+        #expect(identity.revision == nil && identity.taskDescription == nil && identity.metadata.isEmpty)++        let prepared = try MCPPortfolioFoundationHarness.prepareCapture(view)+        let envelope = try #require(+            try JSONSerialization.jsonObject(with: prepared.encodedResponse) as? [String: Any])+        let records = try #require(envelope["records"] as? [String])+        #expect(envelope["taskCount"] as? Int == 9)+        #expect(records.count == 9)+        let evidence = try #require(envelope["taskEvidence"] as? [[String: Any]])+        #expect(evidence.count == 10)+        let foreignEvidence = try #require(evidence.first { $0["id"] as? String == unrelated.id.uuidString })+        #expect(foreignEvidence["revision"] == nil)+        #expect(envelope["snapshotId"] as? String == view.metadata.snapshotId)+        for encoded in records {+            let data = try #require(Data(base64Encoded: encoded))+            let task = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any])+            #expect(task["taskId"] as? String != unrelated.id.uuidString)+        }+    }+}+#endif
Transit/TransitTests/MCPPortfolioSnapshotRequestTests.swift Added
diff --git a/Transit/TransitTests/MCPPortfolioSnapshotRequestTests.swift b/Transit/TransitTests/MCPPortfolioSnapshotRequestTests.swiftnew file mode 100644index 00000000..85b1cc8b--- /dev/null+++ b/Transit/TransitTests/MCPPortfolioSnapshotRequestTests.swift@@ -0,0 +1,113 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++extension MCPPortfolioProjectionTests {+    @Test func supportedSnapshotArgumentsDeduplicateStatuses() throws {+        var arguments = args()+        let projectID = UUID()+        arguments["projectId"] = projectID.uuidString+        arguments["status"] = ["idea", "done", "idea"]+        let parsed = try MCPSnapshotTaskQueryRequest.parse(arguments)+        guard case .initial(let id, let detail, let limit, let project, let statuses) = parsed else {+            Issue.record("Initial snapshot query parsed as continuation")+            return+        }+        #expect(id == arguments["snapshotId"] as? String && detail == .summary && limit == 2)+        #expect(project == projectID && Set(statuses) == ["idea", "done"] && statuses.count == 2)+    }++    @Test func omittedAndEmptyStatusArrayHaveNoRestriction() throws {+        for status in [Optional<[String]>.none, []] {+            var arguments = args()+            arguments["status"] = status+            guard case .initial(_, _, _, _, let statuses) = try MCPSnapshotTaskQueryRequest.parse(arguments) else {+                Issue.record("Initial snapshot query parsed as continuation")+                return+            }+            #expect(statuses.isEmpty)+        }+    }++    @Test(arguments: ["snapshotId", "detailLevel", "includeComments", "limit"])+    func requiredFieldsCannotBeOmitted(key: String) {+        var arguments = args()+        arguments.removeValue(forKey: key)+        #expect(throws: MCPSnapshotTaskQueryError.invalidInput) { try MCPSnapshotTaskQueryRequest.parse(arguments) }+    }++    @Test(arguments: ["project", "search", "type", "priority", "unfinished", "not_status",+                      "displayId", "taskIds", "displayIds", "milestone", "milestoneDisplayId", "readPolicy", "unknown"])+    func unsupportedFieldsHaveTypedCompatibilityError(key: String) {+        var arguments = args()+        arguments[key] = "unsupported"+        #expect(throws: MCPSnapshotTaskQueryError.incompatible) { try MCPSnapshotTaskQueryRequest.parse(arguments) }+    }++    @Test func commentBodiesAreExplicitlyUnsupported() {+        var arguments = args()+        arguments["includeComments"] = true+        #expect(throws: MCPSnapshotTaskQueryError.incompatible) { try MCPSnapshotTaskQueryRequest.parse(arguments) }+    }++    @Test func wrongScalarTypesAndMalformedUUIDsFailValidation() {+        let overrides: [(String, Any)] = [+            ("snapshotId", 1), ("snapshotId", "not-a-uuid"), ("snapshotId", NSNull()),+            ("projectId", true), ("projectId", "not-a-uuid"), ("projectId", NSNull()),+            ("detailLevel", "verbose"), ("detailLevel", 1),+            ("includeComments", "false"), ("includeComments", 0), ("includeComments", NSNull()),+            ("limit", true), ("limit", 1.5), ("limit", 0), ("limit", 101), ("limit", "2"),+            ("status", "idea"), ("status", ["unknown"]), ("status", [1]), ("status", NSNull())+        ]+        for (key, value) in overrides {+            var arguments = args()+            arguments[key] = value+            #expect(throws: MCPSnapshotTaskQueryError.invalidInput) {+                try MCPSnapshotTaskQueryRequest.parse(arguments)+            }+        }+    }++    @Test func fullDetailAndJSONIntegralLimitAreSupported() throws {+        var arguments = args()+        arguments["detailLevel"] = "full"+        arguments["limit"] = Double(100)+        guard case .initial(_, let detail, let limit, _, _) = try MCPSnapshotTaskQueryRequest.parse(arguments) else {+            Issue.record("Initial snapshot query parsed as continuation")+            return+        }+        #expect(detail == .full && limit == 100)+    }++    @Test func reusableContinuationPreservesOptionalPolicyAndRejectsOtherFields() throws {+        let cursor = "00000000-0000-8000-8000-000000000001"+        for policy in [Optional<String>.none, "cached", "refresh_if_needed"] {+            var arguments: [String: Any] = ["cursor": cursor]+            arguments["readPolicy"] = policy+            let request = try MCPSnapshotTaskQueryRequest.parse(arguments)+            guard case .continuation(let parsed, let parsedPolicy) = request else {+                Issue.record("Continuation parsed as initial query")+                return+            }+            #expect(parsed == cursor && parsedPolicy?.rawValue == policy)+        }+        #expect(throws: MCPSnapshotTaskQueryError.incompatible) {+            try MCPSnapshotTaskQueryRequest.parse(["cursor": cursor, "limit": 2])+        }+        #expect(throws: MCPSnapshotTaskQueryError.invalidInput) {+            try MCPSnapshotTaskQueryRequest.parse(["cursor": cursor, "readPolicy": "invalid"])+        }+    }++    @Test func reusableParserDoesNotConsumeOrdinaryV4OrUnknownCursorFamilies() {+        for cursor in [UUID().uuidString, "00000000-0000-1000-8000-000000000001", "invalid"] {+            #expect(throws: MCPSnapshotTaskQueryError.invalidCursor) {+                try MCPSnapshotTaskQueryRequest.parse(["cursor": cursor])+            }+        }+        #expect(MCPCursorFamily.classify("00000000-0000-8000-8000-000000000001") == .reusable)+        #expect(MCPCursorFamily.classify(UUID().uuidString) == .ordinary)+    }+}+#endif
Transit/TransitTests/MCPReusableSnapshotLookupRaceTests.swift Added
diff --git a/Transit/TransitTests/MCPReusableSnapshotLookupRaceTests.swift b/Transit/TransitTests/MCPReusableSnapshotLookupRaceTests.swiftnew file mode 100644index 00000000..53203061--- /dev/null+++ b/Transit/TransitTests/MCPReusableSnapshotLookupRaceTests.swift@@ -0,0 +1,106 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++extension MCPReusableSnapshotStoreTests {+    @Test func pinnedRootSurvivesUnrelatedCreateBeforeReturn() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let original = try bundle(capture)+        let unrelated = try bundle(capture)+        try commit(stage(original, store: store), in: domain)+        let root = try store.retainedView(for: original.root.capture.metadata.snapshotId, now: capture.createdAt,+            testingAfterPin: { try commit(stage(unrelated, store: store), in: domain) })+        #expect(root.capture.metadata.snapshotId == original.root.capture.metadata.snapshotId)+        #expect(try metadataBytes(root) == metadataBytes(original.root))+        #expect(try store.view(for: unrelated.root.capture.metadata.snapshotId, now: capture.createdAt)+            .metadata.snapshotId == unrelated.root.capture.metadata.snapshotId)+    }++    @Test func pinnedPageSurvivesSameRootAppendBeforeReturn() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let originalCursor = cursorToken()+        let original = try bundle(capture, pages: [Data([1, 2])], cursors: [originalCursor])+        try commit(stage(original, store: store), in: domain)+        let addedCursor = cursorToken()+        let page = try store.page(for: originalCursor, now: capture.createdAt, testingAfterPin: {+            let reservation = try store.reserveAppend(snapshotID: original.root.capture.metadata.snapshotId,+                pages: [Data([3])], cursors: [addedCursor], publicationDeadline: capture.retentionDeadline)+            try commit(store.prepare(reservation: reservation), in: domain)+        })+        #expect(page.encodedPage == Data([1, 2]))+        #expect(try metadataBytes(page.root) == metadataBytes(original.root))+        #expect(try store.page(for: addedCursor, now: capture.createdAt).encodedPage == Data([3]))+    }++    @Test func pinnedLookupsRejectLifecycleInvalidationBeforeReturn() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let original = try bundle(capture)+        try commit(stage(original, store: store), in: domain)+        #expect(throws: MCPReusableSnapshotError.invalidSnapshot) {+            try store.retainedView(for: original.root.capture.metadata.snapshotId, now: capture.createdAt,+                                  testingAfterPin: { try store.invalidate() })+        }+        let cursor = cursorToken()+        let replacement = try bundle(capture, pages: [Data([1])], cursors: [cursor])+        try commit(stage(replacement, store: store), in: domain)+        #expect(throws: MCPReusableSnapshotError.invalidCursor) {+            try store.page(for: cursor, now: capture.createdAt, testingAfterPin: { try store.invalidate() })+        }+    }++    @Test(arguments: [false, true])+    func pinnedLookupsRejectRecreatedRootIdentity(pageLookup: Bool) throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let cursor = cursorToken()+        let original = try bundle(capture, pages: [Data([1])], cursors: [cursor])+        let replacement = try bundle(capture, id: original.root.capture.metadata.snapshotId,+                                 pages: [Data([9])], cursors: [cursor])+        try commit(stage(original, store: store), in: domain)+        let replace = {+            try store.invalidate()+            try commit(stage(replacement, store: store), in: domain)+        }+        if pageLookup {+            #expect(throws: MCPReusableSnapshotError.invalidCursor) {+                try store.page(for: cursor, now: capture.createdAt, testingAfterPin: replace)+            }+        } else {+            #expect(throws: MCPReusableSnapshotError.invalidSnapshot) {+                try store.retainedView(for: original.root.capture.metadata.snapshotId, now: capture.createdAt,+                                      testingAfterPin: replace)+            }+        }+        #expect(try store.page(for: cursor, now: capture.createdAt).encodedPage == Data([9]))+    }++    @Test(arguments: [false, true])+    func pinnedLookupsRejectExpiryBeforeReturn(pageLookup: Bool) throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let cursor = cursorToken()+        let original = try bundle(capture, pages: [Data([1])], cursors: [cursor])+        try commit(stage(original, store: store), in: domain)+        if pageLookup {+            #expect(throws: MCPReusableSnapshotError.invalidCursor) {+                try store.page(for: cursor, now: capture.createdAt,+                    testingAfterPin: { domain.setTestingInstant(capture.retentionDeadline) })+            }+        } else {+            #expect(throws: MCPReusableSnapshotError.invalidSnapshot) {+                try store.retainedView(for: original.root.capture.metadata.snapshotId, now: capture.createdAt,+                    testingAfterPin: { domain.setTestingInstant(capture.retentionDeadline) })+            }+        }+    }+}+#endif
Transit/TransitTests/MCPReusableSnapshotPublicationTests.swift Added
diff --git a/Transit/TransitTests/MCPReusableSnapshotPublicationTests.swift b/Transit/TransitTests/MCPReusableSnapshotPublicationTests.swiftnew file mode 100644index 00000000..c30a83f6--- /dev/null+++ b/Transit/TransitTests/MCPReusableSnapshotPublicationTests.swift@@ -0,0 +1,186 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++extension MCPReusableSnapshotStoreTests {+    func result(_ publication: any MCPPreparedPublication, id: String) -> PreparedReadResult {+        PreparedReadResult(encodedResponse: Data("success:".appending(id).utf8), publications: [publication],+            publicationErrors: PreencodedPublicationErrors(busy: Data("READ_BUSY".utf8),+                expired: Data("INVALID_SNAPSHOT".utf8), capacity: Data("QUERY_CAPACITY_EXCEEDED".utf8)))+    }++    @Test func allStoresValidateBeforeAnyCommitAndRejectedBytesContainNoIDs() async throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let firstStore = try MCPReusableSnapshotStore(domain: domain)+        let secondStore = try MCPReusableSnapshotStore(domain: domain)+        let first = try bundle(capture)+        let second = try bundle(capture)+        let left = try stage(first, store: firstStore)+        let right = try stage(second, store: secondStore)+        try secondStore.invalidate()+        let coordinator = MCPReadCoordinator(domain: domain)+        let prepared = PreparedReadResult(encodedResponse: Data("success:first,second".utf8),+            publications: [left, right], publicationErrors: PreencodedPublicationErrors(+                busy: Data("READ_BUSY".utf8), expired: Data("INVALID_SNAPSHOT".utf8),+                capacity: Data("QUERY_CAPACITY_EXCEEDED".utf8)))+        let response = await coordinator.execute(timeout: Data("READ_TIMEOUT".utf8),+            busy: Data("READ_BUSY".utf8)) { _ in+            prepared+        }+        #expect(response == Data("READ_BUSY".utf8))+        #expect(try #require(String(bytes: response, encoding: .utf8))+            .contains(first.root.capture.metadata.snapshotId) == false)+        #expect(try #require(String(bytes: response, encoding: .utf8))+            .contains(second.root.capture.metadata.snapshotId) == false)+        for store in [firstStore, secondStore] {+            #expect(try domain.accounting(for: store.publicationStoreID).visibleEntries == 0)+            #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+        }+    }++    @Test func lateEncodedSuccessAfterTimeoutCannotPublishRoot() async throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let candidate = try bundle(capture)+        let publication = try stage(candidate, store: store)+        let prepared = result(publication, id: candidate.root.capture.metadata.snapshotId)+        let coordinator = MCPReadCoordinator(domain: domain, cutoff: .milliseconds(20))+        let response = await coordinator.execute(timeout: Data("READ_TIMEOUT".utf8),+            busy: Data("READ_BUSY".utf8)) { _ in+            try? await Task.sleep(for: .milliseconds(80))+            return prepared+        }+        #expect(response == Data("READ_TIMEOUT".utf8))+        // Physical completion follows coordinator.offer and its reservation cleanup.+        // Poll cooperatively so this async test never blocks an executor with a semaphore.+        for _ in 0..<1_000 {+            if coordinator.unfinishedCount == 0 { break }+            try await Task.sleep(for: .milliseconds(2))+        }+        #expect(coordinator.unfinishedCount == 0)+        #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+        #expect(try domain.accounting(for: store.publicationStoreID).visibleEntries == 0)+        #expect(throws: MCPReusableSnapshotError.invalidSnapshot) {+            try store.view(for: candidate.root.capture.metadata.snapshotId, now: capture.createdAt)+        }+    }++    @Test func encodingFailureRollsBackPrivateReservationWithoutLeakingIDs() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let candidate = try bundle(capture)+        let reservation = try store.reserveCreate(bundle: candidate, publicationDeadline: capture.retentionDeadline)+        // Handler-side encoding abort owns rollback, before any prepared success enters the gate.+        try store.rollback(reservation)+        let failureBytes = Data("serialization_failure".utf8)+        #expect(try #require(String(bytes: failureBytes, encoding: .utf8))+            .contains(candidate.root.capture.metadata.snapshotId) == false)+        #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+        #expect(throws: MCPReusableSnapshotError.invalidSnapshot) {+            try store.view(for: candidate.root.capture.metadata.snapshotId, now: capture.createdAt)+        }+    }++    @Test func admissionDeadlineIsIndependentOfRootLifetime() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let candidate = try bundle(capture)+        let deadline = capture.createdAt + .milliseconds(4_850)+        let publication = try stage(candidate, store: store, deadline: deadline)+        domain.setTestingInstant(deadline)+        #expect(domain.withLock { publication.validateLocked(in: domain) } == .expired)+        domain.withLock { publication.discardLocked(in: domain) }+        #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+        #expect(capture.retentionDeadline > deadline)+    }++    @Test func concurrentExpiryAndLifecycleInvalidationCannotPublishPendingAppend() async throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let candidate = try bundle(capture)+        try commit(stage(candidate, store: store), in: domain)+        let cursor = cursorToken()+        let reservation = try store.reserveAppend(snapshotID: candidate.root.capture.metadata.snapshotId,+            pages: [Data([1])], cursors: [cursor], publicationDeadline: capture.retentionDeadline + .seconds(1))+        let publication = try store.prepare(reservation: reservation)+        let expiry = Task.detached { domain.setTestingInstant(capture.retentionDeadline) }+        let restart = Task.detached { try store.invalidate() }+        await expiry.value+        try await restart.value+        #expect(domain.withLock { publication.validateLocked(in: domain) } != nil)+        domain.withLock { publication.discardLocked(in: domain) }+        #expect(throws: MCPReusableSnapshotError.invalidCursor) {+            try store.page(for: cursor, now: capture.retentionDeadline)+        }+        #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+    }++    private func probedBundle(_ capture: CapturedReadView, domain: MCPReadPublicationDomain,+                              outcome: MCPStoreLifetimeOutcome) throws -> EncodedViewBundle {+        let base = try bundle(capture)+        return EncodedViewBundle(root: base.root, pages: base.pages, cursors: base.cursors,+            encodedCaptureByteCount: base.encodedCaptureByteCount,+            lifetimeProbe: MCPStoreLifetimeProbe(domain: domain, outcome: outcome))+    }++    @Test func discardedBundleLastReferenceIsReleasedAfterUnlock() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let outcome = MCPStoreLifetimeOutcome()+        var publication: (any MCPPreparedPublication)? = try stage(+            probedBundle(capture, domain: domain, outcome: outcome), store: store)+        domain.withLock {+            publication?.discardLocked(in: domain)+            publication = nil+        }+        #expect(outcome.released.wait(timeout: .now() + 2) == .success)+        #expect(outcome.reenteredWithoutBlocking)+    }++    @Test func invalidatedBundleLastReferenceIsReleasedAfterUnlock() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let outcome = MCPStoreLifetimeOutcome()+        var publication: (any MCPPreparedPublication)? = try stage(+            probedBundle(capture, domain: domain, outcome: outcome), store: store)+        try commit(try #require(publication), in: domain)+        publication = nil+        try store.invalidate()+        #expect(outcome.released.wait(timeout: .now() + 2) == .success)+        #expect(outcome.reenteredWithoutBlocking)+    }+}++nonisolated private final class MCPStoreLifetimeOutcome: @unchecked Sendable {+    let released = DispatchSemaphore(value: 0)+    private let lock = NSLock()+    private var reentered = false+    var reenteredWithoutBlocking: Bool { lock.withLock { reentered } }+    func record(_ value: Bool) { lock.withLock { reentered = value }; released.signal() }+}++nonisolated private final class MCPStoreLifetimeProbe: MCPReusableSnapshotLifetimeProbe {+    let domain: MCPReadPublicationDomain+    let outcome: MCPStoreLifetimeOutcome+    init(domain: MCPReadPublicationDomain, outcome: MCPStoreLifetimeOutcome) {+        self.domain = domain+        self.outcome = outcome+    }+    deinit {+        let reentered = DispatchSemaphore(value: 0)+        let domain = domain+        DispatchQueue.global().async { _ = domain.withLock { reentered.signal() } }+        // A release under the domain lock blocks the other queue until deinit returns.+        outcome.record(reentered.wait(timeout: .now() + .milliseconds(250)) == .success)+    }+}++#endif
Transit/TransitTests/MCPReusableSnapshotReadPinTests.swift Added
diff --git a/Transit/TransitTests/MCPReusableSnapshotReadPinTests.swift b/Transit/TransitTests/MCPReusableSnapshotReadPinTests.swiftnew file mode 100644index 00000000..fdb1ffb0--- /dev/null+++ b/Transit/TransitTests/MCPReusableSnapshotReadPinTests.swift@@ -0,0 +1,220 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++/// Focused store publication-guard regressions; these use real retained entries and domain gates.+@MainActor @Suite(.serialized)+struct MCPReusableSnapshotReadPinTests {+    private let fixtures = MCPReusableSnapshotStoreTests()++    private func cursorToken() -> String { fixtures.cursorToken() }++    private func bundle(_ capture: CapturedReadView, pages: [Data] = [], cursors: [String] = [])+        throws -> EncodedViewBundle {+        try fixtures.bundle(capture, pages: pages, cursors: cursors)+    }++    private func stage(_ bundle: EncodedViewBundle, store: MCPReusableSnapshotStore)+        throws -> any MCPPreparedPublication {+        try fixtures.stage(bundle, store: store)+    }++    private func commit(_ publication: any MCPPreparedPublication, in domain: MCPReadPublicationDomain) throws {+        try fixtures.commit(publication, in: domain)+    }++    @Test func readOnlyPinsValidateWithoutReservingOrSwappingStore() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let cursor = cursorToken()+        let candidate = try bundle(capture, pages: [Data([1, 2])], cursors: [cursor])+        try commit(stage(candidate, store: store), in: domain)+        let initialVersion = try domain.snapshot(for: store.publicationStoreID).version+        let initialAccounting = try domain.accounting(for: store.publicationStoreID)+        let root = try store.preparedRetainedView(for: candidate.root.capture.metadata.snapshotId,+                                                 now: capture.createdAt)+        let page = try store.preparedPage(for: cursor, now: capture.createdAt)+        #expect(root.pin.identity == page.pin.identity)+        #expect(page.page.encodedPage == Data([1, 2]))+        let aggregate = try store.prepareAggregate([root.pin, page.pin, root.pin], in: domain)+        let guardOnly = try #require(aggregate as? MCPReusableSnapshotGuardedPublication)+        #expect(guardOnly.pins.count == 1 && guardOnly.mutation == nil)+        try commit(aggregate, in: domain)+        domain.withLock { aggregate.discardLocked(in: domain) }+        #expect(try domain.snapshot(for: store.publicationStoreID).version == initialVersion)+        #expect(try domain.accounting(for: store.publicationStoreID) == initialAccounting)+        #expect(guardOnly.pins[0].deadline == capture.retentionDeadline)+    }++    @Test func preparedReadPinExpiryRejectsEncodedSuccessAtCoordinatorGate() async throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let candidate = try bundle(capture)+        try commit(stage(candidate, store: store), in: domain)+        let pinned = try store.preparedRetainedView(for: candidate.root.capture.metadata.snapshotId,+                                                   now: capture.createdAt)+        let guardOnly = try store.prepareAggregate([pinned.pin], in: domain)+        let prepared = PreparedReadResult(encodedResponse: candidate.root.firstPage, publications: [guardOnly],+            publicationErrors: PreencodedPublicationErrors(busy: Data("READ_BUSY".utf8),+                expired: Data("INVALID_SNAPSHOT".utf8), capacity: Data("QUERY_CAPACITY_EXCEEDED".utf8)))+        domain.setTestingInstant(capture.retentionDeadline)+        let coordinator = MCPReadCoordinator(domain: domain)+        let response = await coordinator.execute(timeout: Data("READ_TIMEOUT".utf8),+            busy: Data("READ_BUSY".utf8)) { _ in prepared }+        let drainDeadline = ContinuousClock.now + .seconds(1)+        while coordinator.unfinishedCount != 0 && ContinuousClock.now < drainDeadline {+            await Task.yield()+        }+        #expect(coordinator.unfinishedCount == 0)+        #expect(response == Data("INVALID_SNAPSHOT".utf8))+        #expect(domain.withLock { pinned.pin.validateLocked(in: domain) } == .expired)+        #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+    }++    @Test func sameIDRecreationRejectsOldPinWhileNewRootIsValid() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let candidate = try bundle(capture)+        let id = candidate.root.capture.metadata.snapshotId+        try commit(stage(candidate, store: store), in: domain)+        let old = try store.preparedRetainedView(for: id, now: capture.createdAt).pin+        try store.invalidate()+        #expect(domain.withLock { old.validateLocked(in: domain) } == .expired)+        try commit(stage(candidate, store: store), in: domain)+        let current = try store.preparedRetainedView(for: id, now: capture.createdAt).pin+        #expect(old.identity != current.identity)+        #expect(domain.withLock { old.validateLocked(in: domain) } == .expired)+        #expect(domain.withLock { current.validateLocked(in: domain) } == nil)+    }++    @Test func readPinsSurviveUnrelatedCreateAndSameRootAppendAfterLookup() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let firstCursor = cursorToken()+        let candidate = try bundle(capture, pages: [Data([1])], cursors: [firstCursor])+        let id = candidate.root.capture.metadata.snapshotId+        try commit(stage(candidate, store: store), in: domain)+        let oldRoot = try store.preparedRetainedView(for: id, now: capture.createdAt).pin+        let oldPage = try store.preparedPage(for: firstCursor, now: capture.createdAt).pin+        try commit(stage(bundle(capture), store: store), in: domain)+        let appended = try store.reserveAppend(snapshotID: id, pages: [Data([2])], cursors: [cursorToken()],+                                               publicationDeadline: capture.retentionDeadline)+        try commit(store.prepare(reservation: appended), in: domain)+        #expect(domain.withLock { oldRoot.validateLocked(in: domain) } == nil)+        #expect(domain.withLock { oldPage.validateLocked(in: domain) } == nil)+        let version = try domain.snapshot(for: store.publicationStoreID).version+        try commit(store.prepareAggregate([oldPage, oldRoot], in: domain), in: domain)+        #expect(try domain.snapshot(for: store.publicationStoreID).version == version)+        #expect(try store.page(for: firstCursor, now: capture.createdAt).encodedPage == Data([1]))+    }++    @Test func oldPinRejectsCompositeAppendAndRollsBackOtherwiseValidMutation() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let candidate = try bundle(capture)+        let id = candidate.root.capture.metadata.snapshotId+        try commit(stage(candidate, store: store), in: domain)+        let oldPin = try store.preparedRetainedView(for: id, now: capture.createdAt).pin+        try store.invalidate()+        try commit(stage(candidate, store: store), in: domain)+        let cursor = cursorToken()+        let reservation = try store.reserveAppend(snapshotID: id, pages: [Data([1, 2, 3])], cursors: [cursor],+                                                  publicationDeadline: capture.retentionDeadline)+        let mutation = try store.prepare(reservation: reservation)+        let composite = try store.prepareAggregate([oldPin, mutation], in: domain)+        let guarded = try #require(composite as? MCPReusableSnapshotGuardedPublication)+        let transferred = try #require(guarded.mutation)+        #expect(domain.withLock { transferred.validateLocked(in: domain) } == nil)+        #expect(domain.withLock { composite.validateLocked(in: domain) } == .expired)+        domain.withLock { composite.discardLocked(in: domain); composite.discardLocked(in: domain) }+        #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+        #expect(try domain.accounting(for: store.publicationStoreID).visibleEntries == 1)+        #expect(throws: MCPReusableSnapshotError.invalidCursor) { try store.page(for: cursor, now: capture.createdAt) }+        #expect(try store.view(for: id, now: capture.createdAt).metadata.snapshotId == id)+    }++    @Test func eightDistinctRootsCompactRepeatedRootAndPagePinsWithinBound() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        var pins: [any MCPPreparedPublication] = []+        var ids: [String] = []+        for _ in 0..<8 {+            let cursor = cursorToken()+            let candidate = try bundle(capture, pages: [Data([1])], cursors: [cursor])+            try commit(stage(candidate, store: store), in: domain)+            let root = try store.preparedRetainedView(for: candidate.root.capture.metadata.snapshotId,+                                                     now: capture.createdAt).pin+            let page = try store.preparedPage(for: cursor, now: capture.createdAt).pin+            pins += [root, page, root, page]+            ids.append(root.snapshotID)+        }+        let aggregate = try store.prepareAggregate(pins, in: domain)+        let guarded = try #require(aggregate as? MCPReusableSnapshotGuardedPublication)+        #expect(guarded.pins.count == 8)+        #expect(guarded.pins.map(\.snapshotID) == ids.sorted())+        #expect(guarded.pins.allSatisfy { $0.cursor == nil })+        #expect(domain.withLock { aggregate.validateLocked(in: domain) } == nil)+        #expect(try domain.accounting(for: store.publicationStoreID).pendingEntries == 0)+    }++    @Test func moreThanEightDistinctPinnedRootsFailClosedWithoutReservation() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        var pins: [any MCPPreparedPublication] = []+        for _ in 0..<8 {+            let candidate = try bundle(capture)+            try commit(stage(candidate, store: store), in: domain)+            pins.append(try store.preparedRetainedView(for: candidate.root.capture.metadata.snapshotId,+                                                      now: capture.createdAt).pin)+        }+        try store.invalidate()+        let ninth = try bundle(capture)+        try commit(stage(ninth, store: store), in: domain)+        pins.append(try store.preparedRetainedView(for: ninth.root.capture.metadata.snapshotId,+                                                  now: capture.createdAt).pin)+        #expect(throws: PublicationRejection.busy) { try store.prepareAggregate(pins, in: domain) }+        #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+    }++    @Test func conflictingSameIDPinIdentitiesCannotBeCompacted() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let candidate = try bundle(capture)+        let id = candidate.root.capture.metadata.snapshotId+        try commit(stage(candidate, store: store), in: domain)+        let old = try store.preparedRetainedView(for: id, now: capture.createdAt).pin+        try store.invalidate()+        try commit(stage(candidate, store: store), in: domain)+        let current = try store.preparedRetainedView(for: id, now: capture.createdAt).pin+        #expect(throws: PublicationRejection.busy) { try store.prepareAggregate([old, current], in: domain) }+        #expect(try domain.accounting(for: store.publicationStoreID).pendingEntries == 0)+    }++    @Test func readPinsAndAggregatesRejectOtherDomainsAndStores() throws {+        let capture = try MCPPortfolioSavedFixture().capture()+        let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let otherDomain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+        let store = try MCPReusableSnapshotStore(domain: domain)+        let otherStore = try MCPReusableSnapshotStore(domain: domain)+        let candidate = try bundle(capture)+        try commit(stage(candidate, store: store), in: domain)+        let pin = try store.preparedRetainedView(for: candidate.root.capture.metadata.snapshotId,+                                                now: capture.createdAt).pin+        #expect(otherDomain.withLock { pin.validateLocked(in: otherDomain) } == .busy)+        #expect(throws: PublicationRejection.busy) { try store.prepareAggregate([pin], in: otherDomain) }+        #expect(throws: PublicationRejection.busy) { try otherStore.prepareAggregate([pin], in: domain) }+        let guarded = try store.prepareAggregate([pin], in: domain)+        #expect(otherDomain.withLock { guarded.validateLocked(in: otherDomain) } == .busy)+        #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+    }+}+#endif
Transit/TransitTests/PortfolioSummaryPropertyTests.swift Added
diff --git a/Transit/TransitTests/PortfolioSummaryPropertyTests.swift b/Transit/TransitTests/PortfolioSummaryPropertyTests.swiftnew file mode 100644index 00000000..836fa52f--- /dev/null+++ b/Transit/TransitTests/PortfolioSummaryPropertyTests.swift@@ -0,0 +1,174 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++extension PortfolioSummaryServiceTests {+    @Test(arguments: [UInt64(1), 17, 2382, 0xC0FFEE])+    // swiftlint:disable:next function_body_length+    func seededPhysicalRecordPartitionsMatchIndependentFilters(seed: UInt64) throws {+        let fixture = try MCPPortfolioSavedFixture(taskCount: 127)+        let projects = try fixture.owner.context.fetch(FetchDescriptor<Project>())+        let foreign = try #require(projects.first { $0.id == MCPPortfolioFixture.emptyProjectID })+        let milestones = try fixture.owner.context.fetch(FetchDescriptor<Milestone>())+        let localMilestone = try #require(+            milestones.first { $0.id == MCPPortfolioFixture.openMilestoneID })+        let foreignMilestone = Milestone(name: "Foreign", project: foreign, displayID: .permanent(99))+        foreignMilestone.id = UUID(uuidString: "00000000-0000-4003-8000-000000000001")!+        fixture.owner.context.insert(foreignMilestone)+        var random = PortfolioSummarySeed(state: seed)+        let rawStatuses = PortfolioSummaryTestValues.statuses + ["legacy", "", "IN-PROGRESS"]+        let offsets: [TimeInterval?] = [nil, -0.001, 0, 1, 3_599.999, 3_600, 3_601]+        for task in fixture.tasks {+            task.statusRawValue = rawStatuses[random.next(rawStatuses.count)]+            switch random.next(5) {+            case 0: task.project = nil+            case 1: task.project = foreign+            default: task.project = fixture.project+            }+            switch random.next(3) {+            case 0: task.milestone = nil+            case 1: task.milestone = localMilestone+            default: task.milestone = foreignMilestone+            }+            task.completionDate = offsets[random.next(offsets.count)].map {+                MCPPortfolioFixture.window.start.addingTimeInterval($0)+            }+        }+        try fixture.owner.context.save()+        let captured = try fixture.capture()+        let summary = try PortfolioSummaryService.summarize(+            view: captured, window: MCPPortfolioFixture.window)+        for project in summary.projects {+            let identity = try #require(captured.projects.first { $0.id == project.projectId })+            let records = captured.tasks.filter { $0.projectKey == identity.physicalKey }+            #expect(+                PortfolioSummaryTestValues.buckets(project.countsByStatus)+                    == PortfolioSummaryTestValues.referenceBuckets(records))+            #expect(project.totalTaskCount == records.count)+            #expect(+                project.totalTaskCount+                    == PortfolioSummaryTestValues.buckets(project.countsByStatus).reduce(0, +))+            #expect(project.ideaCount == project.countsByStatus.idea)+            #expect(project.inProgressCount == project.countsByStatus.inProgress)+            #expect(+                project.workflowTaskCount+                    == PortfolioSummaryTestValues.buckets(project.countsByStatus)[1...5].reduce(0, +))+            #expect(project.nonterminalTaskCount == project.ideaCount + project.workflowTaskCount)+            #expect(+                project.recentCompletions+                    == PortfolioSummaryTestValues.referenceCompletions(+                        records, window: MCPPortfolioFixture.window))+            try checkPartitions(project, identity: identity, records: records, captured: captured)+        }+        let projectKeys = Set(captured.projects.map(\.physicalKey))+        let orphans = captured.tasks.filter { $0.projectKey.map { !projectKeys.contains($0) } ?? true }+        #expect(summary.unresolvedProjects.totalTaskCount == orphans.count)+        #expect(+            PortfolioSummaryTestValues.buckets(summary.unresolvedProjects.countsByStatus)+                == PortfolioSummaryTestValues.referenceBuckets(orphans))+        #expect(+            summary.projects.reduce(0) { $0 + $1.totalTaskCount }+                + summary.unresolvedProjects.totalTaskCount == captured.tasks.count)+        let permuted = PortfolioSummaryTestValues.view(+            captured, projects: random.shuffled(captured.projects),+            tasks: random.shuffled(captured.tasks),+            milestones: random.shuffled(captured.milestones), comments: random.shuffled(captured.comments)+        )+        #expect(+            try PortfolioSummaryService.summarize(view: permuted, window: MCPPortfolioFixture.window)+                == summary)+    }++    private func checkPartitions(+        _ project: PortfolioProjectSummary, identity: ReadProject, records: [ReadTask],+        captured: CapturedReadView+    ) throws {+        let unassigned = records.filter { $0.milestoneKey == nil }+        let invalid = records.filter { task in+            guard let key = task.milestoneKey else { return false }+            return !captured.milestones.contains {+                $0.physicalKey == key && $0.projectKey == identity.physicalKey+            }+        }+        #expect(+            PortfolioSummaryTestValues.buckets(project.unassignedMilestone.countsByStatus)+                == PortfolioSummaryTestValues.referenceBuckets(unassigned))+        #expect(+            PortfolioSummaryTestValues.buckets(project.invalidMilestoneAssociations.countsByStatus)+                == PortfolioSummaryTestValues.referenceBuckets(invalid))+        #expect(+            project.unassignedMilestone.recentCompletions+                == PortfolioSummaryTestValues.referenceCompletions(+                    unassigned, window: MCPPortfolioFixture.window))+        #expect(+            project.invalidMilestoneAssociations.recentCompletions+                == PortfolioSummaryTestValues.referenceCompletions(+                    invalid, window: MCPPortfolioFixture.window))+        for milestone in project.milestones {+            let endpoint = try #require(captured.milestones.first { $0.id == milestone.milestoneId })+            let selected = records.filter { $0.milestoneKey == endpoint.physicalKey }+            #expect(+                PortfolioSummaryTestValues.buckets(milestone.countsByStatus)+                    == PortfolioSummaryTestValues.referenceBuckets(selected))+            #expect(milestone.totalTaskCount == selected.count)+            #expect(+                milestone.recentCompletions+                    == PortfolioSummaryTestValues.referenceCompletions(+                        selected, window: MCPPortfolioFixture.window))+        }+        #expect(+            project.milestones.reduce(0) { $0 + $1.totalTaskCount } + unassigned.count + invalid.count+                == project.totalTaskCount)+    }+}++@MainActor @Suite(.serialized)+struct PortfolioCompletionWindowTests {+    @Test(arguments: [+        "2026-10-03T00:00:00Z", "2026-10-03T00:00:00.0Z",+        "2026-10-03T00:00:00.00Z", "2026-10-03T00:00:00.000Z",+        "2026-10-03T02:00:00+02:00", "2026-10-02T19:00:00-05:00"+    ])+    func offsetsAndSupportedFractionPrecisionPreserveInstant(start: String) throws {+        let parsed = try CompletionWindow.parse(start: start, end: "2026-10-03T01:00:00Z")+        #expect(parsed == MCPPortfolioFixture.window)+    }++    @Test(arguments: ["1", "12", "123"])+    func nonzeroFractionalSecondsAreNotRoundedAway(fraction: String) throws {+        let parsed = try CompletionWindow.parse(+            start: "2026-10-03T00:00:00.\(fraction)Z", end: "2026-10-03T01:00:00Z"+        )+        let expected = Double("0.\(fraction)")!+        #expect(+            abs(parsed.start.timeIntervalSince(MCPPortfolioFixture.window.start) - expected) < 0.000_001)+    }++    @Test(arguments: [+        "", "2026-10-03", "2026-10-03T00:00:00", "2026-10-03T00:00Z",+        "2026-10-03T00:00:00.1234Z", "2026-10-03T00:00:00.Z",+        "2026-02-30T00:00:00Z", "2026-13-03T00:00:00Z", "2026-10-00T00:00:00Z",+        "2026-10-03T24:00:00Z", "2026-10-03T00:60:00Z", "2026-10-03T00:00:60Z",+        "2026-10-03T00:00:00+0200", "2026-10-03T00:00:00+24:00",+        "2026-10-03T00:00:00+00:60", "2026-10-03T00:00:00Z trailing",+        " 2026-10-03T00:00:00Z", "2026-10-03t00:00:00z", "20261003T000000Z"+    ])+    func strictMalformedInputsHaveTypedValidationFailure(input: String) {+        #expect(throws: CompletionWindowError.invalidInput) {+            try CompletionWindow.parse(start: input, end: "2026-10-03T01:00:00Z")+        }+        #expect(throws: CompletionWindowError.invalidInput) {+            try CompletionWindow.parse(start: "2026-10-02T00:00:00Z", end: input)+        }+    }++    @Test(arguments: ["2026-10-03T00:00:00Z", "2026-10-02T23:59:59.999Z"])+    func equalOrReversedIntervalsFail(end: String) {+        #expect(throws: CompletionWindowError.invalidInput) {+            try CompletionWindow.parse(start: "2026-10-03T00:00:00Z", end: end)+        }+    }+}+#endif
Transit/TransitTests/PortfolioSummaryServiceTests.swift Added
diff --git a/Transit/TransitTests/PortfolioSummaryServiceTests.swift b/Transit/TransitTests/PortfolioSummaryServiceTests.swiftnew file mode 100644index 00000000..b580a0f8--- /dev/null+++ b/Transit/TransitTests/PortfolioSummaryServiceTests.swift@@ -0,0 +1,314 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct PortfolioSummaryServiceTests {+    @Test func allBucketsDerivedCountsEmptyProjectsAndNoBodies() throws {+        let fixture = try MCPPortfolioSavedFixture()+        let summary = try summarize(fixture.capture())+        let project = try #require(summary.projects.first { $0.projectId == fixture.project.id })+        #expect(project.countsByStatus == MCPPortfolioFixture.expectedCounts)+        #expect(project.totalTaskCount == 9)+        #expect(project.ideaCount == 2 && project.inProgressCount == 1)+        #expect(project.workflowTaskCount == 5 && project.nonterminalTaskCount == 7)+        #expect(project.recentCompletions == MCPPortfolioFixture.expectedCompletions)+        #expect(summary.completionWindow == MCPPortfolioFixture.window)+        let empty = try #require(+            summary.projects.first { $0.projectId == MCPPortfolioFixture.emptyProjectID })+        #expect(PortfolioSummaryTestValues.buckets(empty.countsByStatus) == Array(repeating: 0, count: 8))+        #expect(+            empty.totalTaskCount == 0 && empty.lastRecordedActivity == nil && empty.milestones.isEmpty)+        let invalid = try #require(project.diagnostics.first { $0.category == "invalid_task_status" })+        #expect(invalid.affectedCount == 1 && invalid.sampleComplete && invalid.samples.count == 1)+        let rendering = String(reflecting: summary)+        for forbidden in [+            "Captured description", "Canonical comment coverage", "taskDescription", "metadata"+        ] {+            #expect(!rendering.contains(forbidden))+        }+    }++    @Test func emptyPortfolioIsSuccessfulAndHasEightZeroOrphanBuckets() throws {+        let view = try MCPPortfolioSavedFixture().capture()+        let summary = try summarize(+            PortfolioSummaryTestValues.view(+                view, projects: [], tasks: [], milestones: [], comments: []+            ))+        #expect(summary.projects.isEmpty && summary.diagnostics.isEmpty)+        #expect(summary.unresolvedProjects.totalTaskCount == 0)+        #expect(+            PortfolioSummaryTestValues.buckets(summary.unresolvedProjects.countsByStatus)+                == Array(repeating: 0, count: 8))+    }++    @Test(arguments: ["open", "done", "abandoned", "future-status"])+    func milestoneRawStatusIsIndependentOfTerminalTasks(raw: String) throws {+        let view = try MCPPortfolioSavedFixture().capture()+        let milestone = try #require(+            view.milestones.first { $0.id == MCPPortfolioFixture.openMilestoneID })+        let changed = PortfolioSummaryTestValues.milestone(milestone, status: raw)+        let tasks = view.tasks.map {+            PortfolioSummaryTestValues.task($0, status: "done", milestoneKey: .some(changed.physicalKey))+        }+        let summary = try summarize(+            PortfolioSummaryTestValues.view(view, tasks: tasks, milestones: [changed]))+        let output = try #require(summary.projects.flatMap(\.milestones).first)+        #expect(output.rawStatus == raw)+        #expect(output.status == (raw == "future-status" ? "open" : raw))+        #expect(output.invalidStatus == (raw == "future-status"))+        #expect(output.countsByStatus.done == tasks.count)+        #expect(output.displayId == milestone.permanentDisplayId)+    }++    @Test func emptyMilestonesAndMissingDisplayIDsStayPresent() throws {+        let view = try MCPPortfolioSavedFixture().capture()+        let milestones = view.milestones.map {+            PortfolioSummaryTestValues.milestone($0, displayID: .some(nil))+        }+        let summary = try summarize(+            PortfolioSummaryTestValues.view(view, tasks: [], milestones: milestones, comments: []))+        let output = summary.projects.flatMap(\.milestones)+        #expect(output.count == 2 && output.allSatisfy { $0.displayId == nil })+        #expect(+            output.allSatisfy {+                PortfolioSummaryTestValues.buckets($0.countsByStatus) == Array(repeating: 0, count: 8)+            })+    }++    @Test func completionWindowEdgesRestorationAndMissingDates() throws {+        let view = try MCPPortfolioSavedFixture().capture()+        let window = MCPPortfolioFixture.window+        let statuses = [+            "done", "done", "done", "abandoned", "abandoned", "abandoned", "done", "planning", "unknown"+        ]+        let dates: [Date?] = [+            window.start, window.end, window.start.addingTimeInterval(-0.001),+            window.start, window.end.addingTimeInterval(-0.001), window.end, nil,+            window.start, window.start+        ]+        let ordered = view.tasks.sorted { $0.id.uuidString < $1.id.uuidString }+        let tasks = zip(ordered, statuses.indices).map { task, index in+            PortfolioSummaryTestValues.task(+                task, status: statuses[index], completion: .some(dates[index]))+        }+        let summary = try summarize(PortfolioSummaryTestValues.view(view, tasks: tasks))+        let project = try #require(+            summary.projects.first { $0.projectId == MCPPortfolioFixture.populatedProjectID })+        #expect(+            project.recentCompletions+                == PortfolioRecentCompletions(done: 1, abandoned: 2, missingCompletionDateCount: 1))+        #expect(project.countsByStatus.done == 4 && project.countsByStatus.abandoned == 3)+    }++    @Test func orphanAndInvalidMilestonePartitionsCountPhysicalRecordsExactlyOnce() throws {+        let view = try MCPPortfolioSavedFixture().capture()+        let tasks = view.tasks.sorted { $0.id.uuidString < $1.id.uuidString }+        let milestone = try #require(view.milestones.first)+        let foreign = try #require(view.projects.first { $0.id == MCPPortfolioFixture.emptyProjectID })+        let foreignMilestone = PortfolioSummaryTestValues.milestone(+            milestone, projectKey: .some(foreign.physicalKey))+        let nonexistent = LocalRecordKey(encodedIdentifier: Data("unresolved-endpoint".utf8))+        let changed = [+            PortfolioSummaryTestValues.task(tasks[0], projectKey: .some(nil)),+            PortfolioSummaryTestValues.task(tasks[1], projectKey: .some(nonexistent)),+            PortfolioSummaryTestValues.task(tasks[2], milestoneKey: .some(foreignMilestone.physicalKey)),+            PortfolioSummaryTestValues.task(tasks[3], milestoneKey: .some(nonexistent)),+            PortfolioSummaryTestValues.task(tasks[4], milestoneKey: .some(nil))+        ]+        let summary = try summarize(+            PortfolioSummaryTestValues.view(view, tasks: changed, milestones: [foreignMilestone]))+        let project = try #require(+            summary.projects.first { $0.projectId == MCPPortfolioFixture.populatedProjectID })+        #expect(summary.unresolvedProjects.totalTaskCount == 2)+        #expect(project.totalTaskCount == 3 && project.invalidMilestoneAssociations.totalTaskCount == 2)+        #expect(project.unassignedMilestone.totalTaskCount == 1)+        #expect(summary.projects.flatMap(\.milestones).allSatisfy { $0.totalTaskCount == 0 })+        #expect(project.totalTaskCount + summary.unresolvedProjects.totalTaskCount == changed.count)+    }++    @Test func insufficientCaptureFailsWithTypedCoherenceError() throws {+        let view = try MCPPortfolioSavedFixture().capture()+        #expect(throws: PortfolioSummaryError.incoherentCapture) {+            try summarize(PortfolioSummaryTestValues.view(view, completeness: .selectedRead))+        }+        #expect(throws: PortfolioSummaryError.incoherentCapture) {+            try summarize(PortfolioSummaryTestValues.view(view, scope: .selectedQuery))+        }+    }++    private func summarize(_ view: CapturedReadView) throws -> PortfolioSummary {+        try PortfolioSummaryService.summarize(view: view, window: MCPPortfolioFixture.window)+    }+}++extension PortfolioSummaryServiceTests {+    @Test(arguments: [+        "task_creation", "task_status", "comment_creation", "milestone_creation", "milestone_status"+    ])+    func everyActivityKindCanWin(kind: String) throws {+        let view = try MCPPortfolioSavedFixture().capture()+        let baseline = MCPPortfolioFixture.window.start.addingTimeInterval(-600)+        let latest = MCPPortfolioFixture.window.end.addingTimeInterval(600)+        let tasks = view.tasks.map {+            PortfolioSummaryTestValues.task(+                $0, creation: kind == "task_creation" ? latest : baseline,+                statusChange: kind == "task_status" ? latest : baseline+            )+        }+        let milestones = view.milestones.map {+            PortfolioSummaryTestValues.milestone(+                $0, creation: kind == "milestone_creation" ? latest : baseline,+                statusChange: kind == "milestone_status" ? latest : baseline+            )+        }+        let comments = view.comments.map {+            PortfolioSummaryTestValues.comment(+                $0, creation: kind == "comment_creation" ? latest : baseline+            )+        }+        let summary = try summarize(+            PortfolioSummaryTestValues.view(+                view, tasks: tasks, milestones: milestones, comments: comments))+        let evidence = try #require(+            summary.projects.first { $0.projectId == MCPPortfolioFixture.populatedProjectID }?+                .lastRecordedActivity)+        #expect(evidence.timestamp == latest && evidence.kind.rawValue == kind)+        let expectedIDs =+            kind.hasPrefix("task_")+            ? tasks.map(\.id) : (kind.hasPrefix("milestone_") ? milestones.map(\.id) : comments.map(\.id))+        #expect(evidence.id == expectedIDs.min { $0.uuidString < $1.uuidString })+    }++    @Test func tiedActivityUsesLexicalKindThenIdentityAndOrphanCommentsDoNotInventActivity() throws {+        let view = try MCPPortfolioSavedFixture().capture()+        let tie = MCPPortfolioFixture.window.end+        let tasks = view.tasks.map {+            PortfolioSummaryTestValues.task($0, creation: tie, statusChange: tie)+        }+        let milestones = view.milestones.map {+            PortfolioSummaryTestValues.milestone($0, creation: tie, statusChange: tie)+        }+        let comments = view.comments.map { PortfolioSummaryTestValues.comment($0, creation: tie) }+        let summary = try summarize(+            PortfolioSummaryTestValues.view(+                view, tasks: tasks, milestones: milestones, comments: comments))+        let evidence = try #require(+            summary.projects.first { $0.projectId == MCPPortfolioFixture.populatedProjectID }?+                .lastRecordedActivity)+        #expect(evidence.kind == .commentCreation && evidence.id == MCPPortfolioFixture.commentID)+        let orphanComments = comments.map {+            PortfolioSummaryTestValues.comment($0, creation: tie, taskKey: .some(nil))+        }+        let empty = try summarize(+            PortfolioSummaryTestValues.view(view, tasks: [], milestones: [], comments: orphanComments))+        #expect(empty.projects.allSatisfy { $0.lastRecordedActivity == nil })+    }++    @Test func milestoneOnlyActivityIsIncluded() throws {+        let view = try MCPPortfolioSavedFixture().capture()+        let summary = try summarize(PortfolioSummaryTestValues.view(view, tasks: [], comments: []))+        let project = try #require(+            summary.projects.first { $0.projectId == MCPPortfolioFixture.populatedProjectID })+        #expect(project.lastRecordedActivity?.kind == .milestoneCreation)+        #expect(+            project.lastRecordedActivity?.id+                == view.milestones.map(\.id).min { $0.uuidString < $1.uuidString })+    }++    @Test func namesAndDisplayIDsNeverMergeAndDiagnosticSamplingIsStable() throws {+        let view = try MCPPortfolioSavedFixture(taskCount: 24).capture()+        let projects = view.projects.enumerated().map { index, project in+            PortfolioSummaryTestValues.project(project, name: index == 0 ? " Shared " : "SHARED")+        }+        let tasks = view.tasks.map { PortfolioSummaryTestValues.task($0, displayID: .some(7)) }+        let milestones = view.milestones.map {+            PortfolioSummaryTestValues.milestone($0, displayID: .some(8))+        }+        let changed = PortfolioSummaryTestValues.view(+            view, projects: projects, tasks: tasks, milestones: milestones)+        let summary = try summarize(changed)+        #expect(+            summary.projects.count == 2 && summary.projects.reduce(0) { $0 + $1.totalTaskCount } == 24)+        #expect(summary.projects.flatMap(\.milestones).count == 2)+        let diagnostics = summary.diagnostics + summary.projects.flatMap(\.diagnostics)+        let taskCollision = try #require(diagnostics.first { $0.category == "duplicate_task_display_id" })+        #expect(+            taskCollision.affectedCount == 24 && taskCollision.samples.count == 10+                && !taskCollision.sampleComplete)+        #expect(+            taskCollision.samples.map(\.id)+                == tasks.map(\.id).sorted { $0.uuidString < $1.uuidString }.prefix(10).map { $0 })+        let nameCollision = try #require(diagnostics.first { $0.category == "duplicate_project_name" })+        #expect(+            nameCollision.affectedCount == 2 && nameCollision.samples.count == 2+                && nameCollision.sampleComplete)+        let milestoneCollision = try #require(+            diagnostics.first { $0.category == "duplicate_milestone_display_id" })+        #expect(milestoneCollision.affectedCount == 2 && milestoneCollision.sampleComplete)+        let reversed = try summarize(+            PortfolioSummaryTestValues.view(+                changed, projects: Array(projects.reversed()), tasks: Array(tasks.reversed()),+                milestones: Array(milestones.reversed())+            ))+        #expect(reversed == summary)+    }++    @Test func duplicateUUIDWithinScopeOrEnteringItsIdentityClosureFailsExplicitly() throws {+        let view = try MCPPortfolioSavedFixture().capture()+        let selected = try #require(+            view.projects.first { $0.id == MCPPortfolioFixture.populatedProjectID })+        let foreign = try #require(view.projects.first { $0.id == MCPPortfolioFixture.emptyProjectID })+        let tasks = view.tasks.sorted { $0.id.uuidString < $1.id.uuidString }+        let duplicateTasks = [tasks[0], PortfolioSummaryTestValues.task(tasks[1], id: tasks[0].id)]+        #expect(throws: PortfolioSummaryError.identityAmbiguity) {+            try summarize(PortfolioSummaryTestValues.view(view, tasks: duplicateTasks))+        }+        let enteringDuplicate = PortfolioSummaryTestValues.task(+            tasks[1], id: tasks[0].id, projectKey: .some(foreign.physicalKey))+        #expect(throws: PortfolioSummaryError.identityAmbiguity) {+            try summarize(PortfolioSummaryTestValues.view(+                view, scope: .projects([selected.physicalKey]), tasks: [tasks[0], enteringDuplicate]))+        }+        let duplicateProjects = [selected, PortfolioSummaryTestValues.project(foreign, id: selected.id)]+        #expect(throws: PortfolioSummaryError.identityAmbiguity) {+            try summarize(+                PortfolioSummaryTestValues.view(+                    view, scope: .projects([selected.physicalKey]), projects: duplicateProjects))+        }+        let milestone = try #require(view.milestones.first)+        let other = try #require(view.milestones.first { $0.physicalKey != milestone.physicalKey })+        #expect(throws: PortfolioSummaryError.identityAmbiguity) {+            try summarize(+                PortfolioSummaryTestValues.view(+                    view,+                    milestones: [+                        milestone, PortfolioSummaryTestValues.milestone(other, id: milestone.id)+                    ]+                ))+        }+    }++    @Test func unrelatedDuplicateUUIDsDoNotFailOrWidenScopedSummary() throws {+        let view = try MCPPortfolioSavedFixture().capture()+        let selected = try #require(+            view.projects.first { $0.id == MCPPortfolioFixture.populatedProjectID })+        let foreign = try #require(view.projects.first { $0.id == MCPPortfolioFixture.emptyProjectID })+        let tasks = view.tasks.sorted { $0.id.uuidString < $1.id.uuidString }+        let foreignTasks = [tasks[0], tasks[1]].map {+            PortfolioSummaryTestValues.task(+                $0, id: UUID(uuidString: "00000000-0000-4002-8000-000000000001")!,+                projectKey: .some(foreign.physicalKey), milestoneKey: .some(nil))+        }+        let selectedTasks = Array(tasks.dropFirst(2))+        let summary = try summarize(+            PortfolioSummaryTestValues.view(+                view, scope: .projects([selected.physicalKey]), tasks: selectedTasks + foreignTasks+            ))+        #expect(summary.projects.count == 1 && summary.projects.first?.projectId == selected.id)+        #expect(summary.projects.first?.totalTaskCount == selectedTasks.count)+        #expect(summary.unresolvedProjects.totalTaskCount == 0)+    }+}+#endif
Transit/TransitTests/PortfolioSummaryTestValues.swift Added
diff --git a/Transit/TransitTests/PortfolioSummaryTestValues.swift b/Transit/TransitTests/PortfolioSummaryTestValues.swiftnew file mode 100644index 00000000..57034546--- /dev/null+++ b/Transit/TransitTests/PortfolioSummaryTestValues.swift@@ -0,0 +1,135 @@+#if os(macOS)+import Foundation+@testable import Transit++/// Mutations of a real saved capture keep its physical keys and authoritative revisions.+/// Only the field being exercised changes; this is not a second capture provider.+nonisolated enum PortfolioSummaryTestValues {+    static let statuses = [+        "idea", "planning", "spec", "ready-for-implementation", "in-progress",+        "ready-for-review", "done", "abandoned"+    ]++    static func view(+        _ source: CapturedReadView, scope: ReadCaptureScope? = nil,+        projects: [ReadProject]? = nil, tasks: [ReadTask]? = nil,+        milestones: [ReadMilestone]? = nil, comments: [ReadCommentEvidence]? = nil,+        completeness: CaptureCompleteness? = nil+    ) -> CapturedReadView {+        CapturedReadView(+            completeness: completeness ?? source.completeness, captureScope: scope ?? source.captureScope,+            metadata: source.metadata, createdAt: source.createdAt,+            retentionDeadline: source.retentionDeadline,+            projects: projects ?? source.projects, tasks: tasks ?? source.tasks,+            milestones: milestones ?? source.milestones, comments: comments ?? source.comments+        )+    }++    static func project(_ source: ReadProject, id: UUID? = nil, name: String? = nil) -> ReadProject {+        ReadProject(+            physicalKey: source.physicalKey, id: id ?? source.id, name: name ?? source.name,+            projectDescription: source.projectDescription, gitRepo: source.gitRepo,+            colorHex: source.colorHex, taskKeys: source.taskKeys, milestoneKeys: source.milestoneKeys,+            selectedRecordJSON: source.selectedRecordJSON)+    }++    static func task(+        _ source: ReadTask, id: UUID? = nil, displayID: Int?? = nil, status: String? = nil,+        projectKey: LocalRecordKey?? = nil, milestoneKey: LocalRecordKey?? = nil,+        creation: Date? = nil, statusChange: Date? = nil, completion: Date?? = nil+    ) -> ReadTask {+        let raw = status ?? source.rawStatus+        return ReadTask(+            physicalKey: source.physicalKey, id: id ?? source.id,+            permanentDisplayId: displayID ?? source.permanentDisplayId, name: source.name,+            taskDescription: source.taskDescription, projectKey: projectKey ?? source.projectKey,+            milestoneKey: milestoneKey ?? source.milestoneKey, storedProjectID: source.storedProjectID,+            storedMilestoneID: source.storedMilestoneID, rawStatus: raw,+            effectiveStatus: statuses.contains(raw) ? raw : "idea", rawType: source.rawType,+            effectiveType: source.effectiveType, rawPriority: source.rawPriority,+            effectivePriority: source.effectivePriority, metadata: source.metadata,+            metadataJSON: source.metadataJSON, creationDate: creation ?? source.creationDate,+            lastStatusChangeDate: statusChange ?? source.lastStatusChangeDate,+            completionDate: completion ?? source.completionDate, commentKeys: source.commentKeys,+            selectedRecordJSON: source.selectedRecordJSON, revision: source.revision,+            fullRecordWithoutCommentsJSON: source.fullRecordWithoutCommentsJSON,+            requestedCommentRecordsJSON: source.requestedCommentRecordsJSON+        )+    }++    static func milestone(+        _ source: ReadMilestone, id: UUID? = nil, displayID: Int?? = nil, status: String? = nil,+        projectKey: LocalRecordKey?? = nil, creation: Date? = nil, statusChange: Date? = nil+    ) -> ReadMilestone {+        let raw = status ?? source.rawStatus+        return ReadMilestone(+            physicalKey: source.physicalKey, id: id ?? source.id,+            permanentDisplayId: displayID ?? source.permanentDisplayId, name: source.name,+            milestoneDescription: source.milestoneDescription,+            projectKey: projectKey ?? source.projectKey,+            storedProjectID: source.storedProjectID, rawStatus: raw,+            effectiveStatus: ["open", "done", "abandoned"].contains(raw) ? raw : "open",+            creationDate: creation ?? source.creationDate,+            lastStatusChangeDate: statusChange ?? source.lastStatusChangeDate,+            completionDate: source.completionDate, taskKeys: source.taskKeys,+            selectedRecordJSON: source.selectedRecordJSON+        )+    }++    static func comment(_ source: ReadCommentEvidence, creation: Date, taskKey: LocalRecordKey?? = nil)+        -> ReadCommentEvidence {+        ReadCommentEvidence(+            physicalKey: source.physicalKey, id: source.id,+            taskKey: taskKey ?? source.taskKey, storedTaskID: source.storedTaskID,+            creationDate: creation, content: source.content, authorName: source.authorName,+            isAgent: source.isAgent, selectedRecordJSON: source.selectedRecordJSON)+    }++    static func buckets(_ counts: PortfolioStatusCounts) -> [Int] {+        [+            counts.idea, counts.planning, counts.spec, counts.readyForImplementation,+            counts.inProgress, counts.readyForReview, counts.done, counts.abandoned+        ]+    }++    /// Reference filters deliberately do not use effectiveStatus or service helpers.+    static func referenceBuckets(_ tasks: [ReadTask]) -> [Int] {+        statuses.map { status in+            tasks.filter { statuses.contains($0.rawStatus) ? $0.rawStatus == status : status == "idea" }+                .count+        }+    }++    static func referenceCompletions(_ tasks: [ReadTask], window: CompletionWindow)+        -> PortfolioRecentCompletions {+        let inside: (ReadTask) -> Bool = { task in+            guard let date = task.completionDate else { return false }+            return date >= window.start && date < window.end+        }+        return PortfolioRecentCompletions(+            done: tasks.filter { $0.rawStatus == "done" && inside($0) }.count,+            abandoned: tasks.filter { $0.rawStatus == "abandoned" && inside($0) }.count,+            missingCompletionDateCount: tasks.filter {+                ["done", "abandoned"].contains($0.rawStatus) && $0.completionDate == nil+            }.count+        )+    }+}++/// Fixed seed and explicit Fisher–Yates make failing generated inputs reproducible.+nonisolated struct PortfolioSummarySeed {+    var state: UInt64+    mutating func next(_ upperBound: Int) -> Int {+        state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407+        return Int((state >> 32) % UInt64(upperBound))+    }+    mutating func shuffled<Value>(_ values: [Value]) -> [Value] {+        var result = values+        guard result.count > 1 else { return result }+        for index in stride(from: result.count - 1, through: 1, by: -1) {+            result.swapAt(index, next(index + 1))+        }+        return result+    }+}+#endif

Docs (16)

CHANGELOG.md Modified
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 567151ec..9399bb18 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).  ### Added +- T-2382: Complete portfolio regression coverage and caller guidance for saved summary counts, half-open completion windows and activity, with reusable frozen task queries. Remove the obsolete unused scaffold error.+ - T-63: MCP reads capture saved local data with explicit capture/import metadata, cached or bounded-refresh policies, a five-second response budget and physical admission retained through late cleanup. Frozen pages preserve their original evidence. Bounded phase diagnostics and caller guidance cover failures, backoff and unsupported force-pull limits. - T-2383: MCP tool results expose a versioned structured source/presentation envelope while preserving original text, saved receipt outcomes and retry evidence. Tool output schemas and a synthetic read-only loopback readiness harness cover the contract; navigable links remain unavailable pending T-572. - T-2380: Eight standard MCP writes require retry keys, and task/milestone updates require revision preconditions. Local receipts retain saved outcomes for seven days, durable guards protect uncertain requests across restart, and full-record reads return content revisions for conflict detection.
README.md Modified
diff --git a/README.md b/README.mdindex fd1c7ed0..242e57a2 100644--- a/README.md+++ b/README.md@@ -70,7 +70,7 @@ Transit includes a built-in MCP server on macOS for AI agent integration. Enable  **Breaking transport change:** Older MCP clients using `initialize`, session negotiation, GET streams or JSON-RPC wire arrays are unsupported. Requests require the modern headers and `_meta` fields described in the [MCP result contract](docs/mcp-result-contract.md). Missing required metadata returns an explanatory HTTP 400 protocol error; an otherwise valid modern `initialize` request returns HTTP 404 / JSON-RPC method-not-found. Actual installed-client compatibility remains unverified. -The eight write tools require an `idempotencyKey`. Task/milestone updates and milestone deletion also require the target's current `expectedRevision`. Read a revision before updating, and retry an interrupted request with the same key and arguments. Responses use structured saved-record outcomes; see the [MCP write contract](docs/mcp-write-contract.md) for examples, seven-day replay retention, conflicts, and local-store limits. See the [MCP result contract](docs/mcp-result-contract.md) for structuredContent, modern request headers and recovery. See the [bounded read contract](docs/mcp-read-contract.md) for saved capture freshness, policy, deadlines and retry guidance. Actual installed-client compatibility is deferred to post-merge MacBook validation and remains unverified. App Intent inputs are unchanged.+The eight write tools require an `idempotencyKey`. Task/milestone updates and milestone deletion also require the target's current `expectedRevision`. Read a revision before updating, and retry an interrupted request with the same key and arguments. Responses use structured saved-record outcomes; see the [MCP write contract](docs/mcp-write-contract.md) for examples, seven-day replay retention, conflicts, and local-store limits. See the [MCP result contract](docs/mcp-result-contract.md) for structuredContent, modern request headers and recovery. See the [bounded read contract](docs/mcp-read-contract.md) for saved capture freshness, policy, deadlines and retry guidance. See the [portfolio contract](docs/mcp-portfolio-contract.md) for project summaries and task queries over the same frozen snapshot. Actual installed-client compatibility is deferred to post-merge MacBook validation and remains unverified. App Intent inputs are unchanged.  ## Documentation 
docs/mcp-portfolio-contract.md Added
diff --git a/docs/mcp-portfolio-contract.md b/docs/mcp-portfolio-contract.mdnew file mode 100644index 00000000..7cfaa441--- /dev/null+++ b/docs/mcp-portfolio-contract.md@@ -0,0 +1,60 @@+# MCP portfolio summaries++`query_project_summaries` reports recorded saved-local workload. It uses the [modern single-object request/result contract](mcp-result-contract.md) and [bounded read/freshness contract](mcp-read-contract.md). Counts do not establish product, release or milestone readiness.++## Requests++For a new portfolio summary, supply these `tools/call` arguments:++```json+{"start":"2026-10-01T00:00:00Z","end":"2026-10-04T00:00:00Z","limit":100}+```++`limit` is an integer from 1 through 100. Omit selectors for the whole portfolio, or add exactly one of `projectId` (UUID) and `project` (name). Unknown, ambiguous, malformed or conflicting selectors fail explicitly. `readPolicy` may be `cached` or `refresh_if_needed`; the latter is the default.++`start` and `end` require explicit timezone offsets, seconds, and zero to three fractional digits. Date-only values, missing endpoints and `start >= end` are invalid. Results echo UTC endpoints with millisecond precision. The interval includes start and excludes end.++Continue with only `cursor` and, optionally, the original `readPolicy`. Replay the first summary page with only `snapshotId`. Neither operation recaptures current records or extends expiry; lost/expired views require a new summary.++## Count definitions++Every project and milestone has all eight effective task status buckets, including zeros. Project totals reconcile with valid milestone totals, tasks without a milestone, and tasks with an invalid milestone association. Tasks with missing/unresolved projects are reported separately from project totals. Empty projects and milestones remain visible.++- `ideaCount` is the idea bucket.+- `inProgressCount` is only the in-progress bucket.+- `workflowTaskCount` is planning + spec + ready-for-implementation + in-progress + ready-for-review.+- `nonterminalTaskCount` is idea + workflow. Existing `get_projects.activeTaskCount` retains this nonterminal meaning, including ideas.++Unknown stored task statuses count as effective idea and are diagnosed. Ordinary `query_tasks` without a reusable snapshot retains its existing stored-status filtering, fields, order and frozen cursor behavior.++Recent done/abandoned counts include only currently terminal records whose recorded `completionDate` lies in the half-open interval. Missing terminal completion dates are counted explicitly but excluded from window counts. Restored nonterminal records are excluded even if they retain a completion date. These are current-record counts, not historical transition counts.++## Activity, milestones and diagnostics++`lastRecordedActivity` is the newest task creation/status-change, comment creation, or milestone creation/status-change timestamp, with evidence kind and identity. It is null when no evidence exists. Ties sort lexically by evidence kind, UUID, then physical identity. Arbitrary project/task edits without a recorded modification timestamp are excluded.++Milestones report their raw and effective recorded status, UUID and optional display ID. Unknown milestone status is diagnosed and interpreted as open; terminal tasks do not change milestone status. Invalid cross-project/unresolved milestone links are reported rather than credited to that milestone.++Names and display-ID collisions never merge records. Diagnostics contain exact affected-record counts, at most ten deterministic identity samples and `sampleComplete`. Permanent display-ID fields are null when unavailable. Relevant duplicate UUIDs cause explicit identity ambiguity; unrelated scoped corruption does not broaden or fail the selected project.++Summaries omit individual task descriptions, task metadata and comment bodies.++## Reconcile against the captured view++Use the returned `snapshotId` in `query_tasks`:++```json+{"snapshotId":"<returned-UUID>","detailLevel":"summary","includeComments":false,"limit":100,"projectId":"<project-UUID>","status":["in-progress"]}+```++Snapshot mode requires `snapshotId`, `detailLevel` (`summary` or `full`), `includeComments:false` and `limit` (1–100). Supported filters are project UUID and an array of effective statuses; an empty array is unrestricted and duplicates are deduplicated. Initial snapshot mode permits no readPolicy override. Other options, comment bodies and scope expansion fail explicitly. Full detail includes captured descriptions/metadata and canonical comment-covered revisions without loading live comments.++For the same project and effective-status filters, counts across all task pages equal the summary buckets. Later saved changes/deletions do not change this comparison. These status counts are distinct from completion-window and invalid-association breakdowns.++The view expires five minutes from its original creation. Capture time (`asOf`), freshness evidence time, completion interval and expiry describe different facts. Pages/replay preserve original counts, metadata and expiry; they do not claim all remote changes have arrived. Eight views and 16 MiB of logical encoded capture/page charges are retained separately from ordinary query pagination. This is not a total heap cap; live views are not silently evicted to make room.++## Bounded outcomes++Single-object summary reads make encoded success or typed failure available within the tested five-second admission budget. Timeout/capacity/read failure never returns partial counts as complete success and never publishes a late snapshot. `READ_TIMEOUT`/`READ_BUSY` require explicit backoff/retry; compatibility and invalid snapshot/cursor errors require correcting options or starting a new summary. Shared storage/coherence/serialization failure categories remain distinguishable from validation and valid empty results.++Production JSON-RPC arrays are rejected. Application `mutate_tasks` remains one mutating `tools/call`; its receipts are preserved and it has no read-only five-second guarantee. Installed-client compatibility is deferred to the user's post-merge MacBook check.
specs/OVERVIEW.md Modified
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex 58fc12c9..a3b96685 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -38,6 +38,7 @@ | [MCP Write Safety](#mcp-write-safety) | 2026-10-03 | Done | Add retry-safe MCP writes, local revision preconditions, and structured saved outcomes | | [Structured MCP Results](#structured-mcp-results) | 2026-10-03 | Ready for Review | Structured/text results and latest-only transport locally verified; client compatibility explicitly deferred post-merge | | [Bounded Read Freshness](#bounded-read-freshness) | 2026-10-03 | Done | Bound MCP read completion and report immutable saved capture/import evidence |+| [Portfolio Summaries](#portfolio-summaries) | 2026-10-04 | Done | Saved portfolio counts and reusable frozen task views; qualified native verification complete |  --- @@ -412,3 +413,13 @@ All implementation tasks and native validation are complete. The remaining uniqu - [Task15 integrated GREEN acceptance](bounded-read-freshness/task15-green-acceptance.md) - [Task16 integrated native acceptance](bounded-read-freshness/task16-green-acceptance.md) - [Implementation explanation](bounded-read-freshness/implementation.md)++## Portfolio Summaries++T-2382 completes regression coverage and caller guidance for the portfolio implementation already integrated on main. Installed-client compatibility remains deferred to post-merge MacBook validation.++- [Requirements](portfolio-summaries/requirements.md)+- [Design](portfolio-summaries/design.md)+- [Tasks](portfolio-summaries/tasks.md)+- [Implementation](portfolio-summaries/implementation.md)+- [Acceptance qualifications](portfolio-summaries/integration-acceptance.md)
specs/portfolio-summaries/decision_log.md Added
diff --git a/specs/portfolio-summaries/decision_log.md b/specs/portfolio-summaries/decision_log.mdnew file mode 100644index 00000000..468a9fc3--- /dev/null+++ b/specs/portfolio-summaries/decision_log.md@@ -0,0 +1,111 @@+# Portfolio summaries: decision log++## Quick Decisions++| ID | Date | Decision | Rationale |+| --- | --- | --- | --- |+| Q1 | 2026-10-03 | Use full spec; feature name `portfolio-summaries`. | Explicit parent user approval: Sentinel_3ccdbb1152c88191b673f3dde9f76e60. |+| Q2 | 2026-10-03 | Prepare specs on dedicated `T-2382/portfolio-summaries` worktree based on `0db453b`. | User authorized isolation and commits; preserve T-2380 and other tasks. |+| Q3 | 2026-10-03 | Move T-2382 to spec after scope approval. | Local creating-spec workflow; confirmed committed Transit transition. |+| Q4 | 2026-10-03 | Preserve legacy activeTaskCount; add separate idea and in-progress counts. | Explicit user “Sounds good” to parent proposal, Sentinel_5479ed38c0cc8191a7c47a6487b6c0a1. In-progress count is the literal in-progress status; ready-for-review remains a separate bucket. |+| Q5 | 2026-10-03 | Retain actual five-second individual/read-only-batch response limit, with mixed-batch exception. | Parent reports user approved this response limit and explicitly instructed against adopting the proposed success-admission relaxation. Shared T-63 feasibility evaluation pending. |+| Q6 | 2026-10-03 | Approve the complete reviewed requirements and every remaining decision in the review. | Explicit user: “Both are approved for all decisions, including the ones in the requirements review” (Sentinel_fa39017e21a08191abdcd0b7ae6c9e8e). Design/tasks/implementation remain separate gates. |+| Q7 | 2026-10-03 | T-63 is sole writer of shared server/handler/schema registration; T-2382 supplies isolated summary/snapshot modules. | Parent coordination decision prevents concurrent conflicting shared-file edits; user design approval still required. |+| Q8 | 2026-10-03 | Reads return saved data only and exclude uncommitted UI edits. | Explicit user: “If something isn't saved, it shouldn't be returned” (Sentinel_bb00a4d9d8688191a33a0e6a34ea38db). This clarification applies to both tickets. |+| Q9 | 2026-10-03 | Align the isolated spec branch with merged T-2380 foundation `201205bd`. | Verified PR #249 merged at 201205bd4e786c7f152d8f99006b37da7da888c7. Its MCP tree matches inspected b618acf head; canonical main checkout and other worktrees remain untouched. |++## Approved requirements decisions++The following requirements proposals were approved together by Q6. Detailed implementation choices belong to the design gate.++| ID | Recommendation | Rationale / alternative |+| --- | --- | --- |+| P1 | Add workflow and nonterminal counts alongside approved idea/in-progress counts and all status buckets. | Makes every combined total explicit; these additional combined counts were approved in Q6. |+| P2 | Required timezone-qualified completion interval [start,end); current done and abandoned counts separate. | Existing completionDate records current terminal state, not event history. |+| P3 | Last recorded activity includes creation/status/comment/milestone evidence. | Uses existing timestamps; arbitrary edits cannot be claimed. |+| P4 | Retain views for five minutes with lifecycle invalidation and no silent eviction. | Matches T-2379 lifetime; cross-tool reuse itself is approved in Decision 1 below, but detailed lifetime/failure contract was approved in Q6. |+| P5 | Explicit orphan/invalid-link status buckets; collision diagnostics; duplicate UUID ambiguity fails summary. | Count physical records once without arbitrary attribution or silent deduplication. |+| P7 | Refresh-if-needed default, cached option, two-second wait and thirty-second import threshold. | Aligns T-63 recommendation; evidence never proves remote completeness. |+| P8 | At most ten deterministic identity samples per diagnostic category and scoped attribution-only failure. | Critic identified unbounded detail and unrelated-corruption failures; exact diagnostic counts remain complete. |+| P9 | Summary and snapshot-bound queries map unknown stored statuses to idea; ordinary queries retain stored-status filtering. | Technical peer verified MCPQueryFilters currently compares statusRawValue, unlike TransitTask.status fallback. Shared-view reconciliation requires one explicit rule without changing ordinary-query compatibility. |+| P10 | Reject incompatible/unsupported snapshot scope or options explicitly. | Architecture peer identified risk of silent live recapture or scope expansion defeating reuse. |+| P11 | Full/summary retained task details supported; comment bodies unsupported on reusable views. | User approved detailed task reconciliation, which needs captured descriptions/metadata; summary activity needs comment timestamps but not bodies. Unsupported body requests fail explicitly. |+| P13 | Preserve raw milestone status and expose effective open fallback with a warning. | Peer identified that model fallback alone could mislabel unknown raw status as recorded open. |++## Decision 1: Externally reusable captured views++**Date:** 2026-10-03++**Status:** Accepted — user Sentinel_5479ed38c0cc8191a7c47a6487b6c0a1.++### Context++The ticket requires counts that reconcile with equivalent queries at the same snapshot. Existing pagination retains encoded pages and cannot support new filters against a reusable captured task view.++### Decision++Allow summary and detailed task queries to use the same saved snapshot for real caller-visible reconciliation. T-63 owns the shared capture/freshness service supporting retained capture identity. T-2382 owns the externally reusable summary/task-query snapshot API and lifecycle, coordinated with T-63. Parent will assign shared handler/schema wiring ownership before design.++### Alternatives and consequences++An informational snapshot ID with internal tests only would cost less but would not permit callers to reconcile independently; the user approved real reuse. This expands query/API scope and requires retained immutable task data, filter semantics, capacity/lifecycle accounting, and compatibility tests. Five-minute expiry and detailed freshness policy were approved in Q6; the actual five-second response limit is approved.++## Coordination++## Decision 2: Reuse fenced committed-store capture++**Date:** 2026-10-03. **Status:** Accepted — parent user Sentinel_541ceb19e7c8819193d04d23c5263041.++T-63 supplies `captureScope: ReadCaptureScope` (`wholePortfolio`, `projects([LocalRecordKey])`, `selectedQuery` for ordinary narrow reads); completeness covers declared scope plus required identity/comment closure, and closure never grants broader reusable-query scope. T-63 supplies a fresh autosave-disabled SwiftData read context, value-only copy and before/after history/store/import-epoch fence; T-2382 consumes those values. This excludes unsaved edit forms without mutating the UI context. A prototype injected a saved transaction between project/task reads: the mixed values were rejected when history changed; a stable fresh context returned coherent new values. A UI-context transaction/save/rollback is rejected because it could commit or discard unrelated work. Unknown import/store association must remain unknown freshness; public evidence does not establish global convergence.++## Decision 3: Separate retained-view budget and explicit snapshot mode++**Date:** 2026-10-03. **Status:** Accepted — parent user Sentinel_541ceb19e7c8819193d04d23c5263041.++Use a new synchronized store with eight reusable views and 16 MiB charged encoded capture/page bytes, preserving the ordinary-page store's existing eight/16 MiB limits. This can retain up to 32 MiB of logical encoded data across both stores, plus object/transient overhead; it is not a heap cap. Combining stores would require reworking ordinary pagination and its compatibility/capacity semantics. Parent-approved single-writer integration routes explicit `snapshotId` queries to isolated T-2382 modules; ordinary filters/order/text remain unchanged. Retained full task detail includes canonical T-2380 revisions minted before comment stripping.++## Decision 4: Stage publication under independent completion arbitration++**Date:** 2026-10-03. **Status:** Accepted — parent user Sentinel_541ceb19e7c8819193d04d23c5263041.++No snapshot or cursor becomes visible until fully encoded success wins T-63's synchronized deadline/lifecycle gate. Coalesce selected batch changes into one candidate/version/reservation per store before entering the shared gate; validate all stores before any commit, and swap each store once. Retain displaced/discarded large bundles until after unlock so ARC destruction cannot block timeout arbitration. Timeout leaves physical admission charged until completion. Prototype measurements showed exact-boundary and coalesced timers can exceed five seconds; use a strict independent timer and internal response margin, and verify router/batch availability separately. A structured task-group race is rejected because group teardown waits for a noncooperative worker. Standalone counter/gate tests validate the mechanism but not app integration or real-time scheduling.++## Design quick decisions++| ID | Decision | Rationale |+| --- | --- | --- |+| D1 | One new tool `query_project_summaries`; replay `snapshotId` only; explicit snapshot `query_tasks` mode. | Exposes portfolio and scoped work without legacy payload changes or implicit live recapture. |+| D2 | Snapshot task filters are project UUID and effective status; full descriptions/metadata supported, comment bodies rejected. | Exactly supports approved reconciliation/detail scope without capturing an unbounded body API. |+| D3 | Accept zero to three fractional digits in window inputs and emit canonical UTC milliseconds. | Prevents normalized endpoints from losing comparison precision; parser/schema must declare restriction. |+| D4 | Use physical keys for attribution and UUIDs for public identities; deterministic bounded diagnostics. | Prevents display-ID/name collision deduplication and preserves corruption visibility. |++All design decisions above were approved unchanged by parent user Sentinel_541ceb19e7c8819193d04d23c5263041, including the final scoped-capture and aggregate publication amendments (T-2382 3932e88; T-63 5639c40). Task-list approval received in parent user Sentinel_c2e9343628948191b921868234aaf409; production implementation is authorized subject to foundation and integration gates.++T-2382 owns aggregation semantics and the dedicated summary service. T-63 owns read budgets and freshness. Parent coordinates shared snapshot capability and MCP handler/schema/read-only registration ownership before design/interface binding. No implementation has begun.++Scope/name approval does not approve requirements, design, tasks, or implementation. Requirements critic and peer review findings will be recorded with their disposition before the next approval request.++External Codex/Kiro CLI review startup was attempted after discovering installed binaries. Default sandbox initialization failed; initial escalated attempts were rejected for lacking disclosure authorization. Parent then supplied explicit user sharing approval Sentinel_7ba5dca061b4819183c1d6066aa1e949 and directed one retry. Both retries were rejected because automatic approval review did not recognize the delegated transcript as trusted direct user authorization. No further retry/workaround was attempted. The actual peer-review-validator instructions permit fallback; two independent subagent peers completed that path. Parent was notified of the exact remaining restriction.++The interim success-admission interpretation was not approved. Parent directed restoration of the actual five-second encoded-response/transport-availability guarantee and mixed-batch exception. T-63 supplied a source-backed independent timeout-coordinator hypothesis with bounded lingering work and late-publication gating, requiring a design prototype. The final requirements are aligned with that normative contract; no implementation was authorized.++## Implementation authorization++Parent user approved both task lists in Sentinel_c2e9343628948191b921868234aaf409. T-63 has the initial exclusive heavy build/test slot; T-2382 may prepare task1 interfaces and fixtures but cannot claim foundation verification or start dependent implementation before the foundation handoff passes. Use the repository’s Xcode27 toolchain throughout without downgrade; this is one execution constraint rather than a recurring product requirement. Commits are authorized; push, merge and deployment are not.+++## Mechanical transport alignment — 2026-10-04++Parent explicitly confirmed that historical wire-batch wording is superseded by the user-approved latest-only, single-object POST contract; production JSON-RPC arrays must be rejected, while generic component aggregation tests remain. Requirements 7.1/7.5, design and tasks are mechanically aligned without a new product gate. Preserve application-level mutate_tasks receipts, individual read deadlines, all-store validation/rollback and outside-lock retirement. Historical component prototype results remain evidence, not production array support. Final modern/API15 acceptance is still pending through the T-63/T-2383 combined revision.++## 2026-10-04 — Sequential integration acceptance and delivery boundary++Earlier preparation/prototype/partial-run records remain historical evidence. Parent authorized sequential completion on the dedicated final-verification branch after T63 and T2383 finished, including local review, Pulsar publication and branch push. The finalized current 149-declaration / 221-body result and exact qualified 2,277-declaration / 2,581-body union are documented in integration-acceptance.md. T63 overlap, baseline warnings, original classifier failure and qualified iOS/UI reuse remain explicit. No gate was inferred from an unseen specification. External Claude disclosure approval is still required before PR/review workflow; actual installed-client validation is deferred post-merge to the user's MacBook.++## 2026-10-04 — Main reconciliation and publication approval++The parent forwarded explicit user approval for all pushes to the private Transit GitHub destination, sharing changes with the Claude reviewer, and overnight merges. That approval resolves the earlier publication/disclosure gates; their historical records remain unchanged. PR Pilot resumes against main `747983a7009d0015280f6e88ec811d933f4ef449`, with T2383 PR250 and T63 PR251 already merged. The unique delta is owned regression fixtures/tests, portfolio specifications and caller guidance, plus removal of the unused four-line scaffold enum; no new portfolio runtime behavior is manufactured. Foreign T63/T2383 documentation edits are preserved. The full reviewed branch is retained at `T-2382/reviewed-a4a60de`; original worktree dirt remains untouched.++## 2026-10-04 — Scoped review fix and fresh native verification++The scoped quality/efficiency reviewers identified the same fixture cursor-cycle failure path. A throwing uniqueness requirement now terminates that failed regression immediately, preserving successful assertions. Fresh isolated Xcode27 sourcea60e12af passed149declarations/221bodies with finalized native evidence, no issues/NIO/runtime warnings and normaldrain. The independent exact2277/2581 union retains common-source/platform and T63 overlap qualifications. All four reviews completed; current approval summaries reflect resolved publication/disclosure approval. Delivery changes after this source are documentation only.
specs/portfolio-summaries/design-review.md Added
diff --git a/specs/portfolio-summaries/design-review.md b/specs/portfolio-summaries/design-review.mdnew file mode 100644index 00000000..0b38462b--- /dev/null+++ b/specs/portfolio-summaries/design-review.md@@ -0,0 +1,53 @@+# Portfolio summaries: design review++Status: design approved unchanged in parent Sentinel_541ceb19e7c8819193d04d23c5263041, including final aligned scope/publication amendments at T-2382 3932e88 and T-63 5639c40; user approved all requirements in Sentinel_fa39017e21a08191abdcd0b7ae6c9e8e. No tasks or production implementation approved.++Saved-only read clarification is explicitly approved in Sentinel_bb00a4d9d8688191a33a0e6a34ea38db. The isolated spec branch is based on merged T-2380 `201205bd4e786c7f152d8f99006b37da7da888c7`; the merged MCP tree equals the inspected PR head `b618acf`, so revision/capture integration conclusions remain valid. Canonical checkout and other worktrees were preserved.++## Explanation self-validation (local explain-like skill)++### Beginner++The server takes a saved picture of local projects and tasks, counts that picture, and gives it a short-lived ID. Asking for task detail with the same ID shows the same picture, even if records have changed. Its timestamps describe local observation, not proof that another device's edits have arrived. A separate response controller can report a timeout while the database worker is still blocked; that blocked worker continues to occupy one of eight slots.++### Intermediate++T-63 admits reads before MainActor queueing and captures Sendable values from a separate autosave-disabled context with a history/store fence. T-2382 aggregates those values and retains them with encoded pages for five minutes. Ordinary task queries keep their existing semantics; explicit snapshot queries use effective-status filtering and full captured task fields without comment bodies. Common schema/handler/server files have T-63 as the sole writer. Publication is staged until response encoding and the one-shot deadline/lifecycle gate both succeed.++### Expert++Completion-window and activity computations are pure over one fenced capture. Physical identity prevents UUID/display-ID deduplication from corrupting totals. Snapshot-scoped projections share root capture metadata and original monotonic expiry; new task pages cannot extend lifetime. Deadline state and physical-work accounting are distinct: timeout chooses one preencoded response, but completion alone frees the physical slot. Atomic completion/store insertion prevents late workers, lifecycle changes and encoding failures from creating unreachable or stale views. T-2380 revisions must be minted from raw canonical stored content including comments before derived statuses and omitted bodies change the returned projection.++### Validation findings++The beginner explanation exposed an important boundary: snapshots describe committed local store state, not unsaved UI forms or remote convergence. The expert pass requires a publication transaction covering both the response gate and retained store entry, and a capture fence that does not save unrelated UI edits. These contracts are explicit in the design. Actual transport timer reserve, CloudKit history correlation and real-volume revision capture remain prototype/measurement gates rather than inspection-based guarantees.++## Prototype evidence++The separate prototype uses Swift 6.4 with MainActor default isolation, complete strict concurrency and warnings as errors. It demonstrated 4.950227-second encoded timeout availability with a six-second MainActor block, eight retained timed-out physical workers, ninth busy, release after physical finish, and 120 exactly-once/publication race cases. Exact-boundary timers were late; the design must reserve scheduling/encoding margin. This is not an app-level Hummingbird/SwiftData proof.++Source and output remain outside the production checkout at `/Users/arjen/Documents/Codex/2026-10-03/task-2/design-prototypes/t2382-deadline/`. No Xcode/simulator tests were run. T-63 independently demonstrated history fencing rejecting an injected mixed capture; app-level capture/import and response integration remain required design validation.++## Review mode++Use design-critic followed by the actual peer-review-validator's two independent subagent fallback. External Codex/Kiro review retries remain stopped: automatic approval review rejected the delegated disclosure authorization despite parent user approval. No external-model review or new permission request is claimed.++## Design critic findings++| Finding | Disposition |+| --- | --- |+| Project selection before capture can race with rename/deletion. | Selector resolves inside the same fenced project copy that determines scope. |+| Per-tool publication can precede final batch encoding. | Enclosing T-63 batch permit owns all selected publication and rollback; child results remain private. |+| Concurrent page projections can overrun retention capacity. | Explicit create/append reservations charge pending plus published bytes; stale prepared state selects READ_BUSY and rolls back. |+| UUID cursor namespace undefined after expiry. | Reusable version-8 UUID family is distinct from ordinary version-4 cursors; unknown/expired tokens cannot recapture. |+| Commit-time rejection could expose unpublished IDs in success bytes. | Discard success and select preencoded matching error/whole-batch fallback; validation precedes all nonthrowing commits. |++Critic rereview confirmed the selection, batch, reservation and routing corrections; final completion-path clarification is in the design and verification table. App-level deadline, history/import capture and reservation/lifecycle experiments remain measurable prototype gates.++## Peer validation++Two independent fallback peers completed the full design review. Technical correctness passed; architecture conditionally passed with explicit out-of-lock ARC retirement and scoped capture-completeness clarification. Both corrections are now explicit and agree with T-63’s declared-scope-plus-closure contract. Parent/T-63 identified an additional shared publication correction: combine all selected changes per store before validation, then perform one swap per store. Final delta recheck passed the critic and both independent peers with no remaining must-fix. T-63 confirmed exact `captureScope: ReadCaptureScope` cases `wholePortfolio`, `projects([LocalRecordKey])`, and `selectedQuery` (ordinary narrow reads); reusable views preserve the same wholePortfolio/projects scope value. App-level deadline, coherence and publication experiments remain implementation gates.++## Parent approval gate (completed)++The user approved both designs unchanged in Sentinel_541ceb19e7c8819193d04d23c5263041. Approval covers the new tool/argument/schema plan, scoped retained-view filters, five-minute retention and byte/capacity accounting, committed-store capture/fence, projection/revision rules, and single-writer integration plan. It does not approve tasks, production implementation, push, merge, deployment or the T-2380 CloudKit release prerequisite.
specs/portfolio-summaries/design.md Added
diff --git a/specs/portfolio-summaries/design.md b/specs/portfolio-summaries/design.mdnew file mode 100644index 00000000..573175a5--- /dev/null+++ b/specs/portfolio-summaries/design.md@@ -0,0 +1,189 @@+# Portfolio summaries: design++## Overview++Add `query_project_summaries` and a snapshot-bound mode of `query_tasks`. Both operate on a retained immutable capture supplied by T-63; the summary service aggregates it without fetching live models.++## Architecture and ownership++| Owner | Files / responsibility | Integration contract |+| --- | --- | --- |+| T-63 | `MCPServer.swift`, server lifecycle extensions, `MCPToolHandler.swift`, `MCPToolDefinitions.swift`, `MCPTypes.swift` | Sole writer of routing, common dependency initialization, dispatch, read-only classification, shared schema wiring and `_meta` envelope. Register new summary tool and route `query_tasks` with `snapshotId` to the T-2382 helper. |+| T-63 | Shared read coordinator, capture/freshness DTOs and provider | Admit before executor queueing; preserve five-second encoded-response availability and eight unfinished physical reads, including timed-out workers. Provide a coherent, save-free, value-only capture and a publication permit. |+| T-2382 | `MCPToolHandler+PortfolioSummary.swift`, `MCPToolHandler+SnapshotTaskQuery.swift`, `MCPPortfolioToolDefinitions.swift` | Supply registry descriptor, strict request parsers and reusable-view handlers; ordinary queries remain on the existing path. |+| T-2382 | `MCPReusableSnapshotStore.swift`, `MCPPortfolioSummaryRequest.swift`, `MCPSnapshotTaskQueryRequest.swift`, `MCPPortfolioProjection.swift`, `Services/PortfolioSummaryService.swift` | Retain views/pages, aggregate counts, and project captured task detail. No transport timer, CloudKit trigger, model mutation, receipt or guard implementation. |++T-63 integrates the small registration patch after the isolated T-2382 modules exist. The workers exchange interface sketches and a deterministic capture fixture before production edits. Implementation uses an integration revision containing the approved T-2380 read contract; no work is copied into or changed on T-2380's branch. No migration or CloudKit schema deployment is part of this feature.++```mermaid+flowchart LR+  R[Nonisolated transport] --> C[T-63 admission and deadline coordinator]+  C --> P[T-63 coherent capture provider]+  P --> V[Immutable Sendable view]+  V --> A[T-2382 aggregation and projection]+  A --> E[Encode response and stage view/pages]+  E --> G[T-63 atomic completion/publication gate]+  G --> S[T-2382 retained view store]+  G --> R+```++### Pattern extension audit++| Existing site | Equivalent needed? | Plan |+| --- | --- | --- |+| `MCPToolDefinitions.tools` and handler `readOnlyToolNames` | Yes | T-63 registers summary descriptor as covered read, including fallback-storage classification. |+| `MCPToolHandler.init`, `handleToolCall` | Yes | T-63 injects summary/store dependencies and dispatches new tool and snapshot mode. |+| `MCPTaskQueryRequest.parse` / `handleQueryTasks` | Yes | T-63 dispatches snapshot mode before ordinary parser; no snapshot argument is silently ignored. Preserve ordinary stored-status filters. |+| `encodeQueryPages` / `MCPTaskQuerySnapshotStore` | Yes | Reusable pages belong to the new store, share the view's expiry, and retain outer metadata. Ordinary cursor pages retain their existing store/limits. |+| `setTaskQueryAdmission`, server start/stop/unexpected teardown | Yes | T-63 closes new-view admission and advances store lifecycle generation; clear reusable views and pages as well as ordinary pages. |+| T-2380 `MCPRecordSnapshot.task` / canonical revision helpers | Yes | Capture full comment-covered revision before stripping comment bodies; retain token across all snapshot queries and continuations. Do not remint from derived status fields. |+| `get_projects.activeTaskCount`, `ProjectService.activeTaskCount` | No change | Keep legacy nonterminal semantics. Explain it in schema/caller docs. |+| App Intents, `ReportLogic`, report UI | No | Requirements exclude these surfaces; do not add summary integration there. |++## Components and interfaces++The names below are interface sketches to agree with T-63 at design approval; their behavior and ownership are the integration contract.++```swift+// nonisolated Sendable value types supplied by T-63+struct CapturedReadView: Sendable {+    let metadata: ReadCaptureMetadata+    let captureScope: ReadCaptureScope // wholePortfolio, projects([LocalRecordKey]), or selectedQuery for ordinary narrow reads+    let createdAt: ContinuousClock.Instant+    let retentionDeadline: ContinuousClock.Instant+    let projects: [ReadProject]+    let tasks: [ReadTask]+    let milestones: [ReadMilestone]+    let comments: [ReadCommentEvidence]+}++// T-2382: pure value computation; no ModelContext or await+PortfolioSummaryService.summarize(view: CapturedReadView,+                                 window: CompletionWindow) throws -> PortfolioSummary+MCPPortfolioProjection.task(record: ReadTask,+                            detail: SnapshotTaskDetail) throws -> EncodedTaskRecord++// T-2382: synchronized retention, never actor-dependent for deadline arbitration+MCPReusableSnapshotStore.reserveCreate(viewBytes: Int) throws -> RetentionReservation+MCPReusableSnapshotStore.reserveAppend(root: RetainedView,+                                      pageBytes: Int) throws -> RetentionReservation+MCPReusableSnapshotStore.prepare(reservation: RetentionReservation,+                                bundle: EncodedViewBundle) throws -> StagedPublication+MCPReusableSnapshotStore.lookup(snapshotId: String) throws -> RetainedView+MCPReusableSnapshotStore.rollback(reservation: RetentionReservation)+// Common T-63 source: returns the existing shared capture, never recaptures+MCPRetainedViewSource.view(for snapshotID: String,+                         now: ContinuousClock.Instant) throws -> CapturedReadView+// T-63 enclosing response permit commits all staged entries + chooses response+// Common T-63 prepared result + injected single synchronization domain+PreparedReadResult(encodedResponseData: Data,+                   publications: [MCPPreparedPublication])+MCPPreparedPublication.validateLocked(domain: MCPReadPublicationDomain) -> PublicationRejection?+MCPPreparedPublication.commitLocked() // nonthrowing, after all validations+MCPPreparedPublication.discardLocked()+// Parent coordinator selects bytes and all publications under one domain lock+MCPReadPublicationDomain.complete(results: [PreparedReadResult],+                                  rejectionBytes: PreencodedPublicationErrors)+```++The shared types above use T-63's `CapturedReadView`, `ReadCaptureMetadata`, `ReadProject`, `ReadTask`, `ReadMilestone` and `ReadCommentEvidence`. The view includes `CaptureCompleteness.selectedRead` or `.completePortfolio`; `.completePortfolio` means complete resolved portfolio or project scope, including every selected task and all identity, relationship and comment closure needed to validate attribution and canonical revisions; it does not require unrelated task bodies for a scoped project. A portfolio/reusable capture requires that completeness, canonical r1/full task JSON and every required comment-evidence record. Inadequate completeness returns `incoherent_capture`, not a partial summary. T-2382's retained wrapper adds resolved scope, original completion window, initial summary options and page bundles; it does not define another capture DTO. The provider accepts a portfolio/project selection and resolves that selection inside its fence. Shared `ReadCaptureScope` explicitly records `.wholePortfolio`, `.projects([LocalRecordKey])`, or `.selectedQuery` for an ordinary narrow read on the captured view; completeness applies only to that declared scope. The retained wrapper preserves the same typed scope value; reusable summary views accept wholePortfolio/projects, never selectedQuery. A scoped view never claims whole-portfolio evidence, and reusable queries outside its captured physical project keys return `SNAPSHOT_INCOMPATIBLE`, even when identity closure includes other endpoint records. No scoped request expands to all unrelated task bodies. These exact shared field/type/case names are confirmed by T-63 through the parent’s single-writer coordination. The supplied new-tool descriptor names `query_project_summaries`, marks it covered/read-only, uses the shared `readPolicy` schema, and declares the initial/replay/continuation argument branches in the wire table.++Captured records carry canonical encoded SwiftData `PersistentIdentifier` physical keys (`LocalRecordKey`) as well as stored UUIDs; relationships carry the actual referenced physical keys and stored referenced UUIDs. Use those keys to count physical records, resolve relationships to the captured endpoint, and detect duplicate-UUID ambiguity. Public diagnostic samples expose stored identity and a capture-local discriminator only when needed; they do not grant a new persistent identity. `ReadCommentEvidence` contains comment ID, physical key, parent task physical key, stored task UUID and creation date.++Captured task values include raw/effective status, dates, project/milestone references, full task fields, metadata and the T-2380 revision token. Comment activity uses comment UUID/time/task reference. The provider reads all comment-covered values needed for revision generation, then retains comment evidence and comment-stripped task detail; `includeComments:false` does not mean an incomplete revision. No `@Model`, `ModelContext`, or `[String: Any]` crosses the actor boundary: convert to typed Sendable values or encoded `Data` inside capture.++T-63's capture provider is the coherence authority. Read committed local store state in a fresh autosave-disabled context; do not save/rollback the UI context or include uncommitted edit-form changes. Bracket a nonawaiting value copy with newest SwiftData history token, store identity and import-monitor epoch, using separate fresh validation contexts for history. A changed, expired, missing or unusable fence returns `incoherent_capture`; it cannot publish a mixed view. An empty persisted store uses a validated empty-history sentinel; CloudKit-free in-memory test fixtures use T-63's injected nonawaiting actor-only fence with no external writers. Fetch the newest transaction with `HistoryDescriptor.fetchLimit = 1`, descending transaction identifier. Copy relationship physical keys, raw UUIDs and all required evidence before returning; aggregation never fetches or repairs live relationships. If CoreData import-event store identity cannot be proven to correspond to SwiftData history store identity, freshness is `unknown`, not recent evidence. Reuse T-63's fence/provider rather than building another one. See Decision 2.++## Wire contract++All successful pages/replays include the identical T-63 outer metadata at `_meta["me.nore.ig.transit/read"] = {asOf, snapshotId, freshness, read}`. `asOf` is completed local capture time with UTC millisecond precision. Freshness assessment, import evidence, policy/outcome and capture identity belong to that view; no reuse waits for a new import. Failure without a capture does not invent these fields.++| Call | Accepted arguments | Behavior |+| --- | --- | --- |+| New `query_project_summaries` | Required `start`, `end`, `limit` (1–100); optional exclusive `projectId` or `project`; optional T-63 `readPolicy` | No selector means portfolio. Validate scalar arguments before capture; resolve UUID or `ProjectNamePolicy.normalized` name inside the fenced project copy and capture selected tasks/identity closure under that same fence. Reject both selectors, unknown/ambiguous identity, wrong types and unknown fields. Default refresh-if-needed. |+| Summary replay | `snapshotId` only | Return the original first page, original window and metadata. No scope, window, limit, or policy overrides. |+| Summary continuation | `cursor`, optional same T-63 `readPolicy` | Return original page; no selectors or new options. Policy validation/lookup precedence matches T-63 cursor contract. |+| Snapshot-bound `query_tasks` | Required `snapshotId`, `detailLevel` (`summary`/`full`), `includeComments:false`, `limit` (1–100); optional `projectId`, `status` array | Use captured UUID scope and effective statuses. Other selectors/filters, comment bodies, scope expansion and policy overrides return typed compatibility errors. |+| Task continuation | `cursor`, optional same T-63 `readPolicy` | Reusable cursors use UUID-formatted version-8 tokens; ordinary UUID-generation cursors use version 4. Route by version even after expiry, and reject unknown/expired tokens without fresh capture. Publication checks collisions against published and reserved tokens atomically. |++Task rows sort by task UUID then capture-local record key. Summary rows sort by normalized project name, project UUID and physical key; milestones sort by UUID/physical key. No locale-dependent ordering. All filters, including empty status-array semantics (no status restriction), are documented. Valid requested status strings must be one of the eight statuses; duplicate entries are deduplicated. Snapshot scope can narrow a portfolio capture to a project but cannot expand a project capture. A project that exists only in current live data is not added to a retained view.++The summary text payload is `{projects, unresolvedProjects, diagnostics, completionWindow, nextCursor, expiresAt}`. `projects` entries contain `projectId`, `name`, `countsByStatus`, `totalTaskCount`, `ideaCount`, `inProgressCount`, `workflowTaskCount`, `nonterminalTaskCount`, `recentCompletions`, `lastRecordedActivity`, `milestones`, `unassignedMilestone`, `invalidMilestoneAssociations`, and scoped diagnostics. Every bucket includes zero statuses. `recentCompletions` contains `done`, `abandoned`, and `missingCompletionDateCount`; unknown project records appear only in the portfolio's separate breakdown.++Milestone rows expose `milestoneId`, nullable `displayId`, `name`, `rawStatus`, effective `status`, `invalidStatus`, status buckets, totals and recent completions. Snapshot full task rows preserve captured descriptions/metadata and canonical revision; `status` is effective, with `storedStatus` when raw status differs. Revisions cover stored content and comments, not derived display fields. Summary task detail has the ordinary summary fields, using captured values and the documented effective-status rule.++Window parsing accepts calendar-date ISO 8601 timestamps with seconds, an explicit `Z` or `±HH:mm` offset and zero to three fractional digits; reject date-only/local timestamps, invalid calendar components, unsupported precision/leap seconds and `start >= end`. Normalize output to UTC milliseconds and require canonical round-trip to preserve the parsed instant. Current done/abandoned membership and `start <= completionDate < end` determine window counts; missing dates contribute only to missing-date diagnostics.++## Aggregation and integrity++Build captured indexes by physical record key and UUID. If duplicate UUIDs make attribution or task filtering ambiguous for the requested scope, fail with `IDENTITY_AMBIGUITY`; unrelated duplicate UUIDs do not fail a scoped view. Never collapse task records by display ID, project name, or UUID. Scope closure includes relationship endpoints needed to detect ambiguity into the requested project.++Seed every captured project and milestone with eight zero status buckets. Traverse each included task once: increment project buckets, then exactly one of a valid same-project milestone, no milestone, or invalid milestone association. Portfolio orphans contribute to `unresolvedProjects` instead of a named project. Effective task status falls back to idea; invalid raw values receive separate exact diagnostic counts. Effective milestone status falls back to open with raw value retained. Compute derived counts from final buckets, not independent filters.++Activity candidates are task creation/status change, comment creation, milestone creation/status change. Select greatest timestamp; ties use lexical `(evidenceKind, evidenceUUID, physicalRecordKey)` ascending. Evidence kinds are stable strings (`task_creation`, `task_status`, `comment_creation`, `milestone_creation`, `milestone_status`). Empty projects have null activity. Milestone-only activity belongs to its captured project; orphan comments do not invent project activity.++Name/display-ID collision diagnostics count exact affected records. Sort identity samples lexically by entity kind, stored UUID, display ID and physical key, retain at most ten per category, and emit `sampleComplete = sampledCount == affectedCount`. Detect collisions in the captured identity closure; scope filters do not make an ambiguous referenced identity appear unique. Diagnostic collection cannot change aggregate totals.++## Retention, response deadlines and lifecycle++Keep at most eight reusable views and 16 MiB of charged encoded capture/summary/query-page bytes in the new store, separately from the existing eight/16 MiB ordinary-page store. Creation reserves one root slot and capture/page bytes; append reserves only additional page bytes against an existing pinned root. Published bytes plus all pending reservations share the limit. Concurrent projections cannot each spend the same remaining budget. Roll back reservations on timeout, failed encoding, stale store version, expired root or lifecycle invalidation; never evict a live view to make space. Purge expired entries using `ContinuousClock`; expiry is five minutes from completed capture creation, never extended by lookup, replay or new task-page generation. Logical encoded charges are not a total heap limit.++Lookup pins a retained view during bounded projection. The pin permits computation but not publication past its expiry or after lifecycle generation changes. New task pages carry that view's metadata and deadline; their root view, pages and charges are removed together. Cursor replay returns retained encoded payload and captured metadata. Server restart/stop/unexpected teardown invalidates reusable views/cursors; in-flight publication checks the same lifecycle generation. Timed-out physical workers retain T-63 admission across listener restart until they finish.++The T-63 coordinator owns deadline arbitration outside MainActor and independently admits at most eight unfinished physical operations. Timed-out workers remain charged until they really finish; do not release slots on cancellation/timeout alone. It pre-encodes request-specific timeout responses before dispatch and includes final enclosing-response encoding in the shared five-second deadline. Use T-63's strict independent timer at 4,850 ms and reserve the remaining 150 ms for compact final response completion; a timer scheduled exactly at five seconds has no remaining delivery margin. Verify that reserve under actual transport load before depending on it. Application-level mutate_tasks delivery never cancels or rewrites T-2380 write receipts; the read-only deadline does not apply to a mutating call.++Aggregation/encoding runs on detached value-only work. Check deadline/publication cancellation between record chunks; cancellation limits waste but is not the deadline guarantee. Stage immutable view/page/index bundles without exposing IDs. Outside the completion lock, coalesce all selected create/append publications for each store into one aggregate immutable index candidate, one expected store version and one capacity reservation covering their combined net charge. An internal aggregate may publish one candidate per affected store; independent whole-index candidates against the same store version are forbidden because successive swaps would lose earlier changes. T-63's `MCPReadPublicationDomain` supplies the single lock injected into ordinary and reusable stores; no store introduces an independent nested commit lock. Under that domain, validate deadline, lifecycle, root expiry, reservation ownership, cursor uniqueness and store version for every aggregate store candidate before committing any; perform exactly one index/budget swap per affected store and choose the response together. Prepared `commitLocked` is nonthrowing; `discardLocked` releases reservation ownership exactly once. A stale candidate selects preencoded `READ_BUSY` and rolls back rather than overwriting concurrent publication. Any commit-time rejection discards success bytes and selects matching preencoded error bytes: success cannot contain a snapshot/cursor ID whose publication failed. Preencode these rejection variants and their internal aggregate fallbacks before entering the gate. Retain displaced, expired or discarded large view/page/index bundles in a retirement result while under the gate and release their last references only after unlocking, including rejection, timeout and lifecycle paths. Gate bookkeeping is bounded; no encoding, capture, history scan, bulk-index construction or bulk ARC destruction occurs inside this completion critical section.++For an individual read submitted as one JSON-RPC object per POST, the enclosing T-63 permit owns the complete encoded response and staged publications. Publication succeeds only when final response encoding, validation and deadline arbitration all succeed; otherwise select preencoded typed failure bytes without unpublished IDs. Production JSON-RPC arrays are rejected under the user-approved latest-only transport contract. Application-level `mutate_tasks` remains one `tools/call`; preserve write receipts and do not apply the read-only deadline to a mutating call. Late workers cannot publish a snapshot, cursor or second response. Do not use a task group whose scope exit waits for a blocking fetch to finish.++Generic component aggregation remains an internal coordinator capability and test boundary, not production wire batching. Internal selected child reads retain private encoded results and staged publications under one aggregate permit; children cannot commit independently. Prepare one candidate per affected store, validate every selected candidate before any commit, and commit only publications selected in the final encoded aggregate. Preserve tests for two same-store changes, multi-store validation rejection, ready and blocked children, slow aggregate encoding and internal-cutoff timeout entries. On encoding, validation or deadline failure, roll back every selected staged publication and select preencoded failure bytes without unpublished IDs. Retire displaced/discarded large bundles outside the sole publication-domain lock.++## Errors++| Category | Code / caller action |+| --- | --- |+| Invalid selectors/window/types | `INVALID_INPUT`; correct request, no capture or view publication. |+| Missing/ambiguous project | `PROJECT_NOT_FOUND` / `AMBIGUOUS_PROJECT`; resolve identity. |+| Duplicate UUID attribution | `IDENTITY_AMBIGUITY`; repair upstream data outside this read. |+| Unsupported snapshot options/scope | `SNAPSHOT_INCOMPATIBLE`; use documented captured scope/options or start a new view. |+| Unknown/expired view or new-store cursor | `INVALID_SNAPSHOT` / `INVALID_CURSOR`; start a new summary; never recapture implicitly. |+| Retention capacity | `QUERY_CAPACITY_EXCEEDED`; narrow scope or retry after expiry. |+| Deadline/admission/retention contention | T-63 `READ_TIMEOUT` / `READ_BUSY`; back off, physical slot is retained until worker completion; stale prepared retention state rolls back. |+| Required fetch/coherence/encoding | T-63 `storage_failure` / `incoherent_capture` / `serialization_failure` categories; no complete-success fallback. |++## Testing and requirement traceability++| Requirements | Verification |+| --- | --- |+| 1.1–1.3, 2.1–2.3 | Empty and populated portfolio/project captures, eight buckets and exact derived totals; schema/text shape and unchanged legacy count. |+| 2.4–2.5, 6.2, 6.6–6.7 | Invalid raw task status fixture; snapshot full/summary status equality; ordinary raw filters and field shapes unchanged; reject unsupported filters/comment bodies/scope expansion. |+| 3.1–3.4 | Offset/fraction/date-only/invalid intervals; exact start/end edges, restored tasks, missing dates, separate done/abandoned counts. |+| 4.1–4.2 | All evidence kinds, null and deterministic ties, late comment creation after capture ignored. |+| 5.1–5.5 | Every milestone status and unknown raw value; empty milestones; orphan/invalid links; duplicate names/display IDs/UUIDs; scoped corruption isolation, duplicate UUIDs across required identity closure and exact sampled diagnostic counts. |+| 6.1, 6.3–6.5 | Capture fixture mutation/deletion/import after publication; repeated pages/window/metadata identical; five-minute expiry; no eviction; lifecycle generation invalidation and simultaneous expiry/restart during append; omitted comment bodies preserve original canonical revision. |+| 7.1–7.5 | Standalone deadline experiment plus required app-level coordinator tests: blocked MainActor, slow encode, internal aggregate with one completed staged child and another blocked or failed aggregate encoding, application-level mutate_tasks receipts, eight unfinished physical workers across restart, ninth busy, late publication/release. Concurrent create/append reservations and stale-index races never exceed capacity or publish partial internal aggregates; two same-store creates/appends in one internal aggregate preserve both updates with one swap, and retirement releases occur outside the gate; commit-time rejection selects error bytes containing no unpublished IDs. All freshness states/policies and failure phases from T-63 fixtures. |++Use deterministic seeded generated fixtures with Swift Testing: random task statuses/relationships/dates and permutations. Assert `sum(statusBuckets) == total`, project totals equal valid-milestone + unassigned + invalid-link buckets, portfolio project totals plus orphan buckets equal captured records, and snapshot status-query counts match summary buckets. No external PBT dependency is needed. Compare against a simple reference filter over immutable records, not the implementation's aggregation helpers.++Before shared integration, test module fixtures independently. Then run a serialized shared integration gate on the agreed T-2380/T-63 base; coordinate Xcode/simulator use through parent. Do not report standalone prototype timings as proof of Hummingbird, SwiftData, or OS scheduling guarantees. The implementation's full pre-push review/Pulsar and release prerequisites are later gates.++## Risks and assumptions++Risk: SwiftData/import behavior may cross the provider's coherence fence | Verify: early T-63 capture prototype with import/mutation injection and pending UI changes | If wrong: strengthen capture isolation or fail `incoherent_capture`; do not save unrelated edits or weaken consistency.++Risk: real-volume capture/revision/encoding may exhaust the five-second budget | Verify: early integration measurement with 2,375 tasks and comment-covered revisions, including blocked MainActor | If wrong: return the approved timeout/capacity failure and reduce capture work without partial-success totals.++Risk: transport-wide scheduling/serialization may exceed standalone gate measurements | Verify: actual Hummingbird individual POST response plus internal read-only/mixed aggregate component prototype before dependent tasks | If wrong: fix independent coordination/encoding reserves before approving implementation tasks.++## Evidence informing the design++The standalone Swift 6.4 experiment outside the production checkout made preencoded timeout bytes available at 4.950227 seconds while MainActor work blocked for six seconds, retained all eight timed-out worker slots, rejected a ninth, and produced exactly one response per 120 race cases with no late publication. Boundary timers exceeded five seconds (strict: 5.000345; generic coalesced timer: 5.333136), so the design reserves response margin. These measurements validate the mechanism, not the app's transport integration; see [prototype evidence](../../../design-prototypes/t2382-deadline/README.md). T-63's independent strict-timer probe encoded eight timeouts by 4850.49 ms and the whole read-only batch by 4851.15 ms; its restart probe retained timed-out work capacity.++Swift's [SE-0304](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0304-structured-concurrency.md) requires task-group children to complete before the group scope returns, and detached tasks do not inherit actor context. Independent unstructured coordination is therefore required around noncooperative capture work.++[RFC 9562 §5.8](https://www.rfc-editor.org/rfc/rfc9562.html#section-5.8) permits application-defined UUID version-8 layouts. Reusable cursor tokens retain the UUID variant/version bits, use random remaining bits, and rely on the publication registry for collision checks; the version distinguishes them from the existing version-4 cursor family rather than proving uniqueness.++[T-2380 PR #249](https://github.com/ArjenSchwarz/transit/pull/249) was verified merged at `201205bd4e786c7f152d8f99006b37da7da888c7` (head `b618acf9e3d66a4a1ce493eea94091c058721731`). Its full task reads preserve comment-covered revisions even when comment bodies are excluded. The [guard-cost review](https://github.com/ArjenSchwarz/transit/pull/249#issuecomment-5966423094) motivates blocked-MainActor validation; T-2380 owns the guard implementation and its CloudKit receipt production deployment remains an owner release prerequisite.+++The recorded batch prototype measurements are historical generic component aggregation evidence. They do not authorize production JSON-RPC arrays; actual transport acceptance uses the latest-only single-object POST contract.
specs/portfolio-summaries/implementation.md Added
diff --git a/specs/portfolio-summaries/implementation.md b/specs/portfolio-summaries/implementation.mdnew file mode 100644index 00000000..ebe12d7a--- /dev/null+++ b/specs/portfolio-summaries/implementation.md@@ -0,0 +1,53 @@+# Portfolio summaries implementation++## Beginner Level++### What Changed++`query_project_summaries` reports the recorded workload for the whole portfolio or one selected project. It returns every status bucket, separate idea/workflow/in-progress/nonterminal counts, milestone breakdowns, recent current-record completions, and the newest recorded activity evidence. Empty projects remain visible. Counts describe saved records; they do not claim release readiness or that every workflow task is actively being worked on.++### Why It Matters++An agent can inspect compact summaries without downloading task descriptions or comment bodies. A returned snapshot can then answer task queries against exactly the same saved view, even if live records change. Its original capture time, freshness evidence and five-minute expiry stay fixed across pages and replay.++### Key Concepts++A capture is a consistent copy of saved local records. A snapshot is a temporary retained capture, not a live query. Freshness describes available local import evidence, not CloudKit-wide completeness. Completion windows include their start and exclude their end; they count tasks currently done or abandoned, not historical transitions.++## Intermediate Level++### Changes Overview++`PortfolioSummaryService` aggregates immutable T63 capture values. It attributes records by physical keys, validates the relevant UUID identity closure, and produces deterministic compact counts/activity/diagnostics. The portfolio request parser and snapshot task parser provide strict initial/replay/continuation modes. Snapshot queries support project UUID and effective status filters, summary/full detail and captured canonical revisions, while rejecting comment bodies or scope expansion.++### Implementation Approach++The shared T63 coordinator admits physical reads, evaluates freshness, captures saved values and arbitrates the original request deadline. Portfolio work and encoding operate on detached values. Reusable views use a separate eight-root/16-MiB logical encoded-data budget and immutable index candidates. Successful response encoding and publication are selected together under the shared publication domain; rejection releases reservations and returns typed failure without unreachable IDs.++Prepared modern result fragments are retained by identity. Replay changes JSON-RPC correlation while reusing the exact prepared fragment and original metadata. Read pins validate root identity, original expiry and lifecycle at the completion gate. Seeded router tests compare snapshot task IDs/status counts and completion windows against independently captured records, then mutate saved data and verify frozen replay without another capture.++### Trade-offs++A separate reusable-view store preserves ordinary pagination behavior and budgets. Encoded charges bound logical retention, not total heap use. Scoped capture carries sufficient identity closure to reject attribution ambiguity without broadening reusable query scope. Diagnostics retain exact affected counts with at most ten deterministic samples. Unsupported options fail explicitly instead of reading live data.++## Expert Level++### Technical Deep Dive++Aggregation keeps all eight effective status buckets and reconciles each project's valid milestone, unassigned and invalid-association partitions. Unknown raw task status maps to effective idea; ordinary queries preserve their existing stored-status behavior. Milestone raw/effective status remains independent of task completion. Activity selects the maximum recorded task/milestone creation/status or comment-creation evidence, with deterministic kind, public identity and physical-key tie-breaking. Window parsing restricts accepted precision and emits canonical UTC milliseconds.++Retention construction, page-owner validation, byte comparisons and retirement preparation occur outside the sole completion lock. Per-store changes coalesce into one immutable candidate/version/reservation; all selected stores validate before any swap. Original-operation checkpoints bound cooperative work, while independent deadline arbitration handles noncooperative capture/encoding and retains timed-out physical admission until actual completion. A read pin is not permission to publish after expiry or lifecycle invalidation.++### Architecture Impact++T2382 owns aggregation, reusable-view modules and explicit snapshot query semantics. T63 supplies saved capture, freshness, read budgets, common registration and publication. T2383 supplies latest-only single-object transport and modern provider preparation. Production JSON-RPC arrays are rejected; internal aggregate tests cover atomic publication and protected write receipts without claiming wire batching or a read deadline for mutation calls.++### Potential Issues++The five-second checks measure encoded response availability in the tested runtime, not hard real-time OS scheduling. CloudKit convergence and live signed-store import correlation remain unproved; unknown/unavailable evidence is binding. Corruption-heavy diagnostics and large prepared-owner sets have optional scaling improvements, but no measured deadline failure was established. Installed-client compatibility is explicitly deferred to the user's MacBook after merge.++## Completeness Assessment++Implementation and tests cover all approved portfolio, status, window, activity, identity, snapshot and bounded-outcome criteria. Final native acceptance and exact evidence qualifications are recorded in `integration-acceptance.md`. Temporary interface scaffolding was removed. Runtime verification, local review, publication and push status must be read from that acceptance/handoff rather than inferred from historical prototype or partial console results.++The user approved pushes to the private GitHub destination, external Claude review and overnight merges. PR Pilot proceeds under that approval; earlier paused-gate records remain historical. No client settings, live writes, CloudKit action or deployment were performed.
specs/portfolio-summaries/integration-acceptance.md Added
diff --git a/specs/portfolio-summaries/integration-acceptance.md b/specs/portfolio-summaries/integration-acceptance.mdnew file mode 100644index 00000000..728d13b4--- /dev/null+++ b/specs/portfolio-summaries/integration-acceptance.md@@ -0,0 +1,43 @@+# T-2382 integration acceptance++## Prior sequential acceptance: verified source and scope++Native build/test source: `33972bde496bccee5a764a17b0bed84003f827a8`, branch `T-2382/final-verification`. The cumulative T63 integration base is `ff6286a162d9ffb0b16a0aa07d5c5d5b6195b842`. Subsequent delivery changes are documentation/task bookkeeping only. Xcode 27.0 (27A266a) was used with a guarded two-phase native macOS runner, not an unmodified Makefile full test invocation.++## Native acceptance++The finalized current bundle passed all 149 selected declarations and 221 expanded bodies, including all three seeded reconciliation cases. Native issues, runtime warnings and NIO misuse diagnostics are zero. The process drained normally, and the exact signed isolated unit host was revalidated. The full compiled inventory contains 2,277 declarations.++Root reconciliation gives each of those 2,277 declarations exactly one accepted result: current 149/221 supersede overlapping baseline results; qualified T63 reuse supplies 2,128 declarations / 2,360 expanded bodies. The union is 2,581 expanded passed bodies, with no inventory gaps. This is **not one new full-suite run**.++T63 reuse retains its qualification: Chunk05 had post-body overlap with preceding stalled Chunk04. Stalled/unfinalized attempts are excluded, and their cause remains unproved. Common source equivalence is recorded separately; the only production delta from the integrated T63 base removes an unused scaffold enum. Owned suites were rerun on current source.++The current native build contains 82 warning entries / 41 unique signatures, all matching the preserved T63 baseline. No new warnings were accepted. An initial build had one additional unused-return warning; it was fixed before the accepted build. Selector preparation initially mistook extension filenames for suite names; native enumeration corrected the selectors before test execution.++The original attempt2 job record remains marked failed by a broad log classifier. Independent read-only acceptance proves the finalized native result and accepts only the expected controlled `FallbackOutcomeFixture.InjectedFailure` log whose generated Swift type contains “unknown context”. No native test issue exists; no other unknown-context or NIO message is exempted. Original evidence was preserved, not rewritten into a pass.++## Platform qualification++No new iOS or UI suite was run. Qualified active-source reuse carries forward the finalized T2383/T63 iOS 1,310 declarations / 1,358 executions and UI 21 declarations / 24 executions. All current changed Swift files are macOS gated; active iOS source and build configuration match the accepted cumulative source. These results are not macOS coverage. Actual installed-client compatibility remains explicitly deferred to the user's MacBook after merge.++## Review and evidence++Four local pre-push reviewers assessed reuse, quality, efficiency and approved-spec adherence. The unused scaffold was removed. No unresolved must-fix finding remains; optional helper reuse and corruption-heavy/prepared-owner scaling suggestions were deferred without an established deadline violation. Caller contract, all three explanation levels and completeness assessment are included.++Native evidence is under the task-2 `t2382-review-evidence/sequential-completion` directory: `attempt2-independent-acceptance-v4.json`, `root-native-coverage-union-33972bd.json`, source-equivalence records, preserved job/native trees and finalized `.xcresult` bundle. The generic ecosystem renderer has no detected JUnit runner for this Xcode repository; no JUnit or coverage result was fabricated. Native evidence is reported explicitly in the review instead.++Final lint, review publication and remote push are recorded in the delivery handoff. The user approved GitHub pushes, external Claude review and overnight merges; PR Pilot proceeds under that approval. No merge, deployment, live write, settings change, CloudKit action or production activation was performed.++## Main reconciliation acceptance++T2383 PR250 and T63 PR251 were squash merged before reconciliation onto main `747983a7009d0015280f6e88ec811d933f4ef449`. Remaining T2382 changes are owned regression tests/fixtures, specifications and caller documentation, plus removal of the unused scaffold enum. The original reviewed branch is preserved at `T-2382/reviewed-a4a60de`; foreign documentation and the original worktree's unstaged assertion remain untouched.++Four scoped pre-push reviewers found one fixture failure-path defect: a nonfatal duplicate-cursor assertion could loop indefinitely on a pagination regression. Commit `a60e12af4b0b9f4e013b5d702c97be6f34882eba` makes it throwing. Current approval summaries were also corrected; earlier dated pauses remain historical. Optional test-decoder consolidation was deferred without assertion churn. No unresolved must-fix finding remains.++A fresh guarded Xcode27 build and focused native test run passed at that source. The finalized bundle has 149 declarations / 221 expanded bodies (19 parameterized declarations / 91 Argument bodies), including all three seeded reconciliation cases. Native issues, runtime warnings and NIO diagnostics are zero; exit0 and normal physical drain require no termination. The full compiled inventory is still 2,277 declarations. Build warnings are the exact known 82 entries / 41 signatures, with zero unmatched signatures. `make lint` passed all guards and reports zero violations in 546 Swift files.++Compiled-input comparison records 589 inputs: 588 match prior tested source33972bd, and the sole difference is the approved throwing assertion. This fresh build did not reuse the old compiled host after changing the assertion. Root independently queried the finalized bundle and reconciled 149 current declarations / 221 bodies plus 2,128 qualified common-source declarations / 2,360 bodies: exact union 2,277 / 2,581, each declaration once. This still is not a new full-suite run; all T63 overlap and iOS/UI reuse qualifications above remain binding. No new iOS/UI run or actual installed-client validation is claimed.++Evidence is retained under task-2 `t2382-review-evidence/main-reconciliation/review-fix-a60e12a`: `independent-native-acceptance.json`, `root-native-coverage-union.json`, `compiled-input-comparison.json`, inventory attestations, lint log and finalized `green-a60e12af4b0b9f4e013b5d702c97be6f34882eba/handler-tests-attempt1.xcresult`. Subsequent delivery documentation changes do not alter compiled inputs. The generic review renderer still has no detected JUnit runner; native results remain separately and explicitly reported.++Explicit user approval permits destination push, Claude disclosure and overnight merge after review/checks. PR Pilot status, review publication, PR URL and merge SHA are recorded in the delivery handoff. Installed-client compatibility remains deferred to post-merge MacBook validation before production activation. No live updates, settings changes, CloudKit action, deployment or activation occur here.
specs/portfolio-summaries/interface-handoff.md Added
diff --git a/specs/portfolio-summaries/interface-handoff.md b/specs/portfolio-summaries/interface-handoff.mdnew file mode 100644index 00000000..ce9f0b21--- /dev/null+++ b/specs/portfolio-summaries/interface-handoff.md@@ -0,0 +1,314 @@+# Portfolio foundation handoff++The self-contained result, completion-window and task-detail types are prepared in `MCPPortfolioSummaryTypes.swift`. They contain no parser, aggregation, retention or handler behavior. `MCPPortfolioFixture.swift` fixes identities, a UTC interval and independent count expectations; it does not manufacture shared capture DTOs or revision tokens.++Task 1 consumed verified T-63 foundation `6b34e83` through local integration revision `aa1715b`. The actual capture DTOs, read policy, retained-view source and publication participant protocols are bound by portfolio-owned seams. All service/parser/store/projection/handler operations throw `MCPPortfolioScaffoldError.notImplemented`; no aggregation or retention behavior is supplied. `make test-quick TEST_TARGETS='TransitTests/MCPPortfolioInterfaceTests'` passed both fixture/interface cases; `make lint` passed with zero violations. Task 2/3 are the next foundation risk gate; aggregation/store implementation remains blocked until they pass.++## Fixture construction needed from shared types++- Two projects: populated and empty. Two milestones: open with two tasks, and empty done. Nine distinct physical task keys, each legal task status once plus an unknown raw status whose effective value is idea. Physical relationships must use the actual shared `LocalRecordKey` representation.+- The idea and unknown-status tasks are assigned to the open milestone. Seven other tasks are unassigned. The done task has completion exactly at the interval start; abandoned is exactly at the end. Total is nine, workflow five, nonterminal seven; recent done is one and abandoned zero.+- One comment on the done task supplies the latest activity. A full frozen task record must come from the authoritative T-2380 revision routine with comment-covered r1 before comment-body removal. No fabricated revision may serve as canonical-evidence verification.+- A complete captured view carries T-63 `completePortfolio`, `captureScope: .wholePortfolio` (plus a separately scoped variant), shared metadata and monotonic creation/retention times. Fixtures must preserve closure records without widening the declared physical project scope.++## Pending signature binding++Confirmed actual fields/initializers for `ReadProject`, `ReadMilestone`, `ReadTask`, `ReadCommentEvidence`, `LocalRecordKey`, `ReadCaptureMetadata` and `CapturedReadView`. The saved fixture obtains every DTO from `MCPReadCaptureBuilder`, validates physical comment ownership and compares the captured token to authoritative `MCPRecordSnapshot.task`. It retains the owning `TestModelContainer`. No replacement DTOs or fabricated revisions are used.++The pure service signature is `PortfolioSummaryService.summarize(view: CapturedReadView, window: CompletionWindow) throws -> PortfolioSummary`. Projection is `MCPPortfolioProjection.task(record: ReadTask, detail: SnapshotTaskDetail) throws -> EncodedTaskRecord`. Both remain nonfunctional seams until their later GREEN tasks.++Store, prepared-publication and handler seams bind the actual T-63 `MCPReadPublicationDomain`, `MCPPreparedPublication`, `PreparedReadResult`, typed read policy and retained-view source. The parent confirmed the entrypoints before binding. Later GREEN behavior must coalesce all selected changes per store outside the gate and validate all aggregate candidates before one swap per store. T-63 retains exclusive shared-file wiring ownership; no shared registration has been added at this checkpoint.++The interface checkpoint test `serviceAndRetentionRemainExplicitlyNonfunctional` is temporary: task 5 replaces its service not-implemented assertion with aggregation coverage, and task 7 replaces its store assertions with retention coverage. Do not leave these expectations failing the full suite after GREEN implementations land.++## Foundation risk verification++Task 2's compiling runtime RED is committed as `80cc699`: the frozen-evidence adapter throws `notImplemented`. Both real router timing baselines pass. An incidental missing SwiftData import and a method filter that ran zero cases are retained in logs but are not counted as behavioral RED.++Task 3 supplies only test adapters: the encoded fixture envelope includes every frozen full task record, canonical revision, physical task/comment relationship, projects/milestones and shared metadata. Service, projection, parser, retention and handler production methods remain nonfunctional. A synthetic mixed-call adapter waits for a real protected project write, then preserves the exact saved receipt payload; it does not establish final MCP mixed-batch dispatch, which remains task 13.++The combined app run passed all seven portfolio/interface cases and 31 of 32 selected T-63 cases (38/39 overall). The existing `MCPReadCoordinatorTests.actualRouterReturnsTimeoutWhileMainActorIsBlocked` failed its final 30ms cleanup expectation while the concurrent volume capture still occupied MainActor; its router timeout was 4.851223 seconds. The unchanged coordinator suite passed all eight cases when run alone. Record both results; there is no clean combined-suite claim.++| Portfolio experiment | Observed |+| --- | --- |+| 2,375-task / 2,376-comment fixture setup, before admission | 2.810541 seconds |+| Volume admission/router body, typed timeout with no success fields | 4.851548 seconds |+| Physical capture plus complete frozen-evidence encoding | 83.393310 seconds |+| Blocked MainActor router body, timeout and no late publication | 4.857256 seconds |+| Slow whole-batch encoding router body, timeout and no late publication | 4.853930 seconds |++All volume evidence assertions passed and the physical worker drained before test completion. The 83-second capture is material: the current implementation returns the approved timeout at this volume rather than a useful successful portfolio. A likely cost is `taskValue` scanning all comments twice per task and repeatedly JSON-encoding parent physical identifiers inside the inner ownership scan; this is a source-based hypothesis, not a completed profiler attribution. T-63 owns investigation and correction; canonical r1 semantics and saved-state fencing cannot be weakened.++During task 3 inspection, the provider's completePortfolio branch (`MCPReadCaptureBuilder.swift:144`) was found to copy `allTasks` for scoped project requests as well as portfolio requests. The approved design forbids copying all unrelated full task bodies for a scoped request. The focused portfolio-owned `scopedCaptureDoesNotExpandToUnrelatedTaskBodies` case compiled and failed at runtime: an unrelated task still carried full canonical record JSON. The case preserves required identity closure and confirms the nine selected records retain canonical revisions. Task 3 remains in progress and dependent implementation is stopped pending T-63's correction and actual regression pass. No shared source was edited.++`rune next --phase --stream 1` reported no ready tasks after task 1 completed, although `rune list` retained its completed status and the stable dependency ID matched. The parent authorized explicit `rune progress` for tasks 2 then 3 after independently verifying their satisfied dependencies; no dependent aggregation/store task was started.++Evidence lives outside Git in `../t2382-review-evidence/foundation/` relative to the worktree: `interfaces.xcresult`, `risk-red.xcresult`, `combined.xcresult`, `coordinator-isolated.xcresult`, `scoped-capture-red.xcresult`, their corresponding logs, and exported diagnostics. Final lint passed with zero violations across 428 Swift files. All owned test invocations finished and their physical workers drained; the parent can release the heavy test slot. Full production dispatch/aggregation/reconciliation acceptance remains outstanding.++## Verified provider correction and task 3 completion++The parent consumed T-63 correction `a694c27` through local cherry-pick `9b3d619`, preserving portfolio-owned files. The provider now copies full task bodies/revisions only within declared physical scope and retains unrelated minimal task identity records without full JSON, revision, description or metadata. Comment ownership/canonical indexes replace the repeated inner scans. No shared source was edited by T-2382.++The fixture adapter now encodes/counts full records only for the declared physical scope, while retaining every original task identity in its evidence envelope. The original scoped regression assertion remains intact, with additional assertions proving nine selected full records, ten retained identities, absent foreign body/revision and unchanged snapshot identity. The original scoped suite passed 1/1; the original portfolio/interface suite passed 7/7. Final lint passed with zero violations across 428 Swift files.++| Same full-envelope volume fixture after correction | Observed |+| --- | --- |+| Setup before admission | 2.704333 seconds |+| Saved capture, including queueing | 3.526669 seconds |+| Physical capture plus complete envelope encoding | 3.617544 seconds |+| Router and encoded body, complete success | 3.622145 seconds |+| Full encoded result | 6,373,596 bytes |+| Canonical full records / comment evidence | 2,375 / 2,376 |+| Blocked MainActor timeout body | 4.854159 seconds |+| Slow whole-batch encoding timeout body | 4.853895 seconds |++Saved-only/pending-edit preservation, exact canonical revision, original scoped boundaries, full evidence encoding, mixed protected-write receipt preservation, no late publication and physical-worker drain assertions all passed. The body is the same synthetic full captured-evidence envelope used before correction, not a counts-only projection. These measurements establish this fixture's foundation behavior; they are not final summary aggregation/dispatch acceptance or a hard scheduling guarantee under every load.++Task 3 is complete. The shared-provider blocker is resolved for this gate; no dependent task was started in this delegation. The generic production reusable-capture validator remains T-63-owned: verify required selected-record/comment evidence without globally rejecting diagnosable orphan/invalid links or unrelated duplicate identities, and do not narrow away the original closure. T-2382 owns later filter/options and scoped attribution logic.++Rerun commands used, sequentially in the parent-granted slot:++```sh+make test-quick TEST_TARGETS='TransitTests/MCPPortfolioScopedCaptureTests'+make test-quick TEST_TARGETS='TransitTests/MCPPortfolioInterfaceTests TransitTests/MCPPortfolioReadFoundationTests'+```++Preserved artifacts: `provider-fix-scoped.log` / `.xcresult`, `provider-fix-portfolio.log` / `.xcresult`, `provider-fix-portfolio-results.json`, `provider-fix-diagnostics/`, and `provider-fix-verified-lint.log` in the evidence directory above. All owned physical workers drained and both test commands exited; the parent can release the heavy test slot.++## Historical draft compatibility inspection (superseded by verified foundation)++Read T-63's MCPReadCaptureTypes.swift, MCPReadMetadata.swift and MCPReadPublicationTypes.swift before its verification handoff. These files are drafts; the publication domain is explicitly an identity scaffold, not a runtime completion/capacity guarantee. Nothing was copied or bound into T-2382.++Aggregation/projection fields are present: physical record/reference keys and stored UUIDs; task/milestone raw and effective status; creation/status/completion dates; descriptions, display IDs, type/priority, metadata; full comment-stripped task JSON and authoritative revision; comment keys/evidence; declared typed capture scope; frozen capture/freshness/read metadata.++Two points were reported promptly through the parent:++- The ReadTask comment says both full JSON fields are mandatory for completePortfolio. A reusable portfolio with includeComments:false requires authoritative r1/fullRecordWithoutCommentsJSON and complete comment-key/evidence closure, but requestedCommentRecordsJSON may be nil. Body-request policy must not suppress comment-covered canonical revision/evidence capture. Comment activity evidence is required even when body output is excluded.+- Runtime publication must provide a concrete same-store grouping/coalescing hook and shared-domain reservation/lookup/retirement access. The current validate/commit/discard-only protocol cannot itself identify and coalesce multiple child updates for one store. Resolve the coordinator/store hook at the T-63 runtime task before binding; one aggregate candidate and one swap per store remain mandatory.++At that earlier draft inspection, task1 remained in progress. The verified foundation consumption and current task3 blocker are recorded above.++### Confirmed capture selection++T-63 added and parent confirmed ReadCaptureSelection.projects/.milestones/.tasks(detail: ReadTaskCaptureDetail)/.portfolio, with detail.summary/.fullRecord. ReadCaptureRequest carries selection, projectSelectors, completeness and includeComments as output preference. Portfolio requests use selection.portfolio, completeness.completePortfolio and includeComments:false; they still require complete comment-covered canonical revision/evidence. Ordinary task summary selection preserves the no-comment-fetch path unless comment output is requested. The concrete draft declaration was inspected; runtime foundation remains pending. The requestedCommentRecordsJSON nullable-body clarification and publication coalescing hooks remain open in that draft.++### Proposed publication grouping seam++Parent relayed verified draft interface commit1b34efb and proposed MCPPublicationStoreID (UUID-backed Hashable/Sendable), publicationStoreID on MCPPreparedPublication and MCPReadPublicationParticipant, and participant.prepareAggregate(selected publications, in: domain) returning one prepared publication outside the terminal lock. This is compatible with one-candidate/store publication. It is not the verified runtime foundation.++Runtime must validate participant/store identity and unique operation ownership, group only final-response selected successes, transfer reservation ownership atomically without double charge or an unreserved gap, and retain one rollback owner for every reservation after aggregate preparation throws or a later participant fails. The returned aggregate retains the same store ID. Domain lookup/reservation/retirement APIs remain pending; large displaced/discarded values must survive unlocking before last-reference release.++### Runtime domain API agreement++The proposed MCPPublicationIndex exposes precomputed entryCount, encodedByteCount and tokens. Domain register/snapshot/reserve/transfer/retire operations, with MCPPublicationStoreSnapshot versioned index and MCPDomainPreparedPublication, supply the needed reusable-store seam. The participant privately merges indexes before transfer; terminal validation covers all stores before any one-swap commit. Compatibility was acknowledged through parent with these conditions:++- Append deadline is the original retained-root expiry, never a new lifetime. Root existence, base version and lifecycle remain valid at transfer/terminal commit.+- Register once per store identity. Reservation charges are nonnegative net additions against the captured base; whole replacement bytes are not charged twice. Candidate accounting and token ownership cannot admit unreserved additions. Transfer accepts live same-store/same-base children, moves summed charge/token ownership atomically once, and leaves ownership unchanged on throw.+- Snapshot/lookup/reserve/CAS/token collision use the same domain; capacity counts visible plus pending, with no live eviction. Retirement only purges expired or lifecycle-invalidated entries. All displaced/discarded indexes survive unlock before destruction, including terminal commit/discard paths.++This is API compatibility agreement, not verified runtime evidence or permission to bypass the foundation gate.++## Exact reproduction for T-63 provider correction++Current checkpoint: T-2382 `4599cd5`, incorporating T-63 foundation `6b34e83` through local dependency merge `aa1715b`. Tasks1/2 complete; task3 blocked. These commands are reproduction instructions, not additional tests run after slot release. Use an assigned shared build slot. Target whole suites because the earlier method-only filter executed zero cases.++Scoped failure:++```sh+make test-quick TEST_TARGETS='TransitTests/MCPPortfolioScopedCaptureTests'+```++Case: `MCPPortfolioScopedCaptureTests.scopedCaptureDoesNotExpandToUnrelatedTaskBodies` in `Transit/TransitTests/MCPPortfolioScopedCaptureTests.swift:9`. Start `MCPPortfolioSavedFixture(taskCount:9, commentOnEveryTask:false)` (defaults): two projects, two milestones, nine tasks and one canonical sample comment. Add a tenth task to the fixture's initially empty foreign project (UUID00000000-0000-4000-8000-000000000002), permanent displayID10, name `Unrelated body`, description `Must not be copied for another project's scoped capture`. Save it. Capture the populated project (UUID00000000-0000-4000-8000-000000000001) with `projectSelectors:[.id(fixture.project.id)]`, `selection:.portfolio`, `completeness:.completePortfolio`, `includeComments:false`, `fence:.actorOnlyTestFixture`. The declared physical scope, nine selected records and their canonical revisions pass; the assertion that the foreign task has no full record fails.++Offending foundation source: `Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swift:143–149`, specifically line144 selecting `allTasks` for every completePortfolio request. Keep necessary lightweight identity/relationship/comment closure, but do not serialize unrelated task descriptions/metadata/full revisions. Do not filter away ambiguity into the selected scope. Evidence: `scoped-capture-red.log`, `scoped-capture-red.xcresult`, `scoped-capture-red-results.json` under the evidence directory above.++Volume workload:++```sh+make test-quick TEST_TARGETS='TransitTests/MCPPortfolioReadFoundationTests'+```++Case: `MCPPortfolioReadFoundationTests.actualRouterBoundsComplete2375TaskCaptureAndRevisionEncoding` in `Transit/TransitTests/MCPPortfolioReadFoundationTests.swift:33`. Exact constructor: `MCPPortfolioSavedFixture(taskCount:2_375, commentOnEveryTask:true)`. It saves two projects and two milestones, 2,375 tasks cycling all eight valid statuses plus unknown, one `Revision evidence N` comment per task plus the canonical sample comment on task6 (2,376 comments total). Tasks use deterministic UUIDs/displayIDs, `Captured description N`, metadata `["fixture":"N"]`, and the fixture's fixed completion/window dates. TestModelContainer is in-memory with CloudKit disabled; fixture context autosave is disabled and all records are saved before admission. No unsaved form state or live CloudKit store is used.++Capture request is whole portfolio (`projectSelectors:nil`, `.portfolio`, `.completePortfolio`, `includeComments:false`) through a fresh MCPReadCaptureBuilder context and real MCPReadCoordinator/MCPReadTransportAdapter/Hummingbird router. The fixture envelope encodes every frozen full task record/r1, physical ownership, project/milestone values, comment evidence and shared metadata. Timing excludes fixture setup from request admission. Setup2.810541s; encoded typed timeout/body4.851548s; physical capture+encoding83.393310s. Diagnostic cleanup waits for actual completion (up to120s), then checks unfinishedCount0; it does not release permits early or widen the five-second response limit. Evidence: `combined.xcresult`, combined log and exported diagnostics.++Source inspection for the cost: `MCPReadCaptureBuilder.swift:233–239` scans all comments once for UUID-covered canonical comments and again for physical ownership per task, encoding each owner's PersistentIdentifier during that inner scan. At 2,375 tasks/2,376 comments, the ownership loop visits roughly5.64million pairs. Index canonical-UUID and physical-owner lookups once and cache capture-local physical keys while preserving authoritative r1 semantics; actual optimization verification remains T-63's work.++To reproduce the separate baseline cleanup finding, `MCPReadCoordinatorTests.actualRouterReturnsTimeoutWhileMainActorIsBlocked` failed its final30ms unfinishedCount assertion during the combined portfolio/coordinator run; the unchanged full coordinator suite alone passed8/8. Do not describe this as a response-deadline failure. The accepted production-validator split is T-63 capture/closure/physical-scope validation without public query arguments or narrowing away original closure, and T-2382 snapshot API/filter compatibility and scope-aware attribution.+++## Task 6 RED preparation: reusable retention++Stream `stream/portfolio-summaries-stage2-2` starts at `ef67ff4`. Task 6 is in progress: 22 behavior assertions are drafted across `MCPReusableSnapshotStoreTests.swift` and `MCPReusableSnapshotPublicationTests.swift`, all within the `MCPReusableSnapshotStoreTests` suite. The T-63 heavy slot excludes app builds/test execution here. `make lint` passed with zero violations in 430 files; `swiftc -frontend -parse` passed syntax-only inspection. Neither establishes app compilation, actual RED, or runtime correctness. Task 7 GREEN remains blocked until runtime RED failures are established against the unchanged nonfunctional methods.++Requested serialized RED run after parent grants the slot:++```sh+make test-quick TEST_TARGETS='TransitTests/MCPReusableSnapshotStoreTests'+```++The test contract covers eight views/no eviction; sixteen MiB charged capture plus first summary page plus continuation bytes; pending charges and idempotent rollback; append-only page charges; root/cursor expiry at the original five-minute boundary; immutable capture metadata, revisions/full bodies, original request/window and declared physical scope; one swap/version increment for two same-store creates and two same-root appends; stale CAS; lifecycle and concurrent lifecycle/expiry invalidation; reserved/published/cross-store v8 cursor collisions; selected-query scope and malformed page-pair rejection; independent admission deadline; real coordinator validation of all stores before any commit and timeout rejection of late encoded success; private encoding-abort rollback; actual retained bundle deinitialization after discard/invalidation outside the domain lock. No shared DTO/provider/registration source changes are included.++Candidate-backed signature refinement is necessary for the actual shared domain: `reserve` validates exact root IDs, root deadlines, candidate-index deltas and globally allocated tokens. Reserving anonymous byte counts cannot later transfer ownership to a differently identified root. Added nonfunctional signatures are `reserveCreate(bundle:publicationDeadline:)`, `reserveAppend(snapshotID:pages:cursors:publicationDeadline:)` and `prepare(reservation:)`; the admission deadline is separate from original retained capture expiry. `retainedView(for:now:)` supports original-request replay, and `page(for:now:)` returns `RetainedPage(root:encodedPage:)`, preserving frozen metadata/options rather than returning unassociated bytes. Typed store errors distinguish invalid snapshots, invalid cursors and incompatible captured options/scope.++Store initialization is now throwing so task 7 can register its empty immutable index with the existing shared domain without swallowing registration failures. The current initializer remains registration-free, so RED tests reach explicit operational scaffold failures. The temporary interface checkpoint callsite adds `try`; its old byte-only reservation assertion is retained solely until task 7 replaces that checkpoint and removes obsolete byte-only/prepare-bundle seams. No retention behavior is implemented.++`EncodedViewBundle.lifetimeProbe` is an optional internal Sendable reference, nil by default. Tests attach a deinitialization probe to the actual immutable bundle/index lifetime; GREEN must retain this reference with that bundle. A probe attempts domain reentry from another queue and reports whether deinit blocked under the domain lock. It is never a manually invoked callback and adds no user-visible schema/API fields. Existing shared domain retirement tests remain regression coverage; they do not replace these store-level lifetime assertions.++Rune `next specs/portfolio-summaries/tasks.md --phase --stream 2 --format json` returned no ready tasks despite completed tasks 1–3 and task 6's satisfied dependency. Parent already identified this selection anomaly; explicit `rune progress ... 6` records preparation without marking RED complete. Actual app compilation may uncover interface/test-isolation errors and must precede interpretation of behavioral failures. Missing symbols or compile errors must be corrected before accepting RED evidence.++## Integrated task 4/6 preparation checkpoint++User approval `Sentinel_eafda56391a48191a3c414fef34d1307` explicitly authorizes local implementation sub-branch merges into their ticket branches while leaving main untouched. After that approval, aggregation preparation `a449af6` and retention preparation `563dc93` were integrated into `T-2382/portfolio-summaries` by local merges `de8c4b8` and `6280dbb`. The earlier integration attempt was rejected by automatic approval review under the original no-merge wording; it made no repository change. No main/PR merge, push or deployment occurred.++Task 4 adds aggregation/activity/window tests and seeded independent reference checks in `PortfolioSummaryServiceTests.swift`, `PortfolioSummaryPropertyTests.swift` and `PortfolioSummaryTestValues.swift`. Own typed error declarations distinguish identity ambiguity/incoherent capture and invalid completion windows without implementing behavior. The aggregation and retention preparations passed read-only peer review. On the combined revision, `make lint` passed both repository guards and reported zero violations in 433 files; `git diff --check ef67ff4..HEAD` passed. Tasks 4/6 remain in progress: no app compilation or runtime RED has been claimed.++Queued serialized commands, pending the parent's shared-slot grant:++```sh+make test-quick TEST_TARGETS='TransitTests/PortfolioSummaryServiceTests TransitTests/PortfolioCompletionWindowTests'+make test-quick TEST_TARGETS='TransitTests/MCPReusableSnapshotStoreTests'+```++Read-only inspection of T-63 revision `0ff9876` identified a later handler integration alignment: its `prepareCoveredRead` returns tool-level `MCPPreparedToolRead`, carrying encoded tool results, frozen metadata bytes and staged publications. T-2382 task-1 handler stubs still return transport-level `PreparedReadResult`. Coordinate the own-handler signature adjustment through parent before task 10/12 binding; no shared interface/source or handler signature was changed at this checkpoint, and this T-63 revision was not imported.++## Tasks 4/6 runtime RED checkpoint++The parent granted one serialized heavy slot for the two queued commands above. The first aggregation attempt failed compilation before any tests ran: the retention test file used a semaphore wait from an async context and a helper signature exposed a private type. Own test-only correction `ab04455` replaced the wait with cooperative physical-completion polling and made the helper private. No production behavior was added. Preserve this failed attempt as compilation evidence; it is not RED.++On `ab04455`, the aggregation/window retry compiled and executed 54 cases (including parameterized cases), all failing against explicit `MCPPortfolioScaffoldError.notImplemented`; xcresult has zero compiler errors and zero skipped tests. Typed invalid-window/identity expectations reject that scaffold error. The subsequent retention run compiled and executed 22 cases, all failing, with zero compiler errors and zero skipped tests. Twenty-one retention cases reach operational scaffold failures or reject that scaffold in typed error assertions. `aggregateTwoCreatesUsesOneSwapAndPreservesBoth` first encounters `PublicationRejection.busy` when taking a domain snapshot because the task-1 store initializer deliberately has not registered its index; malformed-page/scope assertions also encounter that missing-registration baseline during their final accounting check. These are missing store-feature baselines, not proof that the downstream accounting, timeout, race or lifetime assertions have exercised implemented behavior.++Tasks 4/6 are now complete as RED checkpoints; GREEN tasks 5/7 are ready according to both `rune next --phase --format json` and `rune streams --available --json`. The grant's two runs are finished; no test or build job remains owned by T-2382, and the heavy slot is released. Future GREEN runtime checks require another parent-coordinated slot.++Evidence directory: `/Users/arjen/Documents/Codex/2026-10-03/task-2/t2382-review-evidence/stage2/`. Files: `aggregation-red.log` (compile failure), `aggregation-compile-failure.json` and `.xcresult`; `aggregation-red-retry.log`, `aggregation-red-results.json`, `aggregation-red.xcresult`; `retention-red.log`, `retention-red-results.json`, `retention-red.xcresult`. The modern xcresult summary export attempted an unavailable write to its TestReport cache; the successful legacy object exports supply the verified metrics and failure messages instead.++## Task 7 source implementation checkpoint++The reusable store now registers an empty immutable index with the sole shared `MCPReadPublicationDomain`, bounded to eight roots and sixteen MiB of logical encoded bytes. `RetentionReservation` owns the actual shared-domain reservation; candidate-backed create/append/prepare signatures remain, and obsolete anonymous byte-only reservation and prepare-with-bundle methods are removed. The temporary combined service/store scaffold test is removed because tasks 5/7 now implement those seams.++Each root entry owns its original encoded bundle (including the actual lifetime probe), captured values, original request/window, first summary page and continuation mapping. Create charges capture plus first page plus continuation bytes; append charges only added bytes. Published and pending tokens use the domain's global collision/CAS checks. Lookup pins an immutable index, checks original expiry and version, and returns frozen values/pages. Expiry prepares a reduced index outside the gate; lifecycle invalidation retires the old index and pending reservations through the shared domain. Retained roots never extend their original five-minute deadline or evict a live neighbor.++Same-store aggregate preparation merges new roots and append deltas outside the lock, then transfers child ownership into one shared reservation with one index swap. Sibling discards after transfer are harmless. No independent lock, mutable budget, provider change, shared DTO change or common-handler initialization edit was added. Domain retirement retains discarded/displaced candidates until after unlocking; the bundle reference is retained by the actual index, rather than a manually invoked test callback.++Store compatibility rejects selected-query/incomplete captures, non-initial roots, non-five-minute lifetimes, malformed page pairs and non-v8 continuations. It does not duplicate T-63's generic canonical/closure validator. `validateReusableCapture` from T-63 revision `0ff9876` is absent on this source base; the later agreed handler admission must call that shared validator before retention, and identity diagnostics remain the summary service's responsibility. Minimal foreign milestone JSON `{milestoneId, name}` is sufficient provided the typed identities, relationships, optional display ID, statuses and timestamps remain captured. Foreign closure cannot widen the retained scope.++Source verification: `swiftc -frontend -parse` passed; `make lint` passed both repository guards and zero violations in 434 files; `git diff --check` passed. A lightweight standalone `swiftc -typecheck -swift-version 6 -default-isolation MainActor` passed using the actual shared domain/DTO files and small request/window/cursor declarations in `/tmp`; this is not an app build or runtime test. Its first attempt could not write the default Clang cache under the sandbox; the successful rerun used `/tmp/t2382-retention-module-cache`, without escalation or changing global settings. Task 7 remains in progress until the parent grants the serialized GREEN command:++```sh+make test-quick TEST_TARGETS='TransitTests/MCPReusableSnapshotStoreTests'+```++No app build/test, simulator job, task 8 projection implementation, push, main/PR merge or deployment occurred at this checkpoint.+## Focused GREEN checkpoint and remaining retention correction++Source streams `5219c15` (aggregation/window) and `70c1209` (retention) were integrated into the dedicated ticket branch at `857b949`. Combined lint passed with zero violations in 434 files. After the parent granted an exclusive slot, the two focused commands ran sequentially on that stable revision: aggregation/window **54/54 passed**, retention **22/22 passed**, both with zero compiler errors and zero skipped tests. Task 5 is complete. Both runs finished and the slot was released; no further heavy job is authorized by that completed grant.++Read-only peer review found one remaining task-7 defect not covered by the existing 22 tests: `retainedView` and `page` check the entire store version after pinning, so an unrelated create/append can make a still-live requested root/cursor appear invalid. Task 7 remains in progress despite its existing suite passing. The store worker paused all edits during the focused runs; after slot release it is preparing a per-root immutable-identity correction plus deterministic outside-lock interleaving regression tests. Future validation requires a new coordinated slot. Do not describe this checkpoint as complete retention correctness or final integration.++Evidence directory: `/Users/arjen/Documents/Codex/2026-10-03/task-2/t2382-review-evidence/stage2-green/`; `aggregation-green.log`, `aggregation-green-results.json`, `aggregation-green.xcresult`, `retention-green.log`, `retention-green-results.json`, `retention-green.xcresult`. No T-63 repair or validator source was mixed into these focused runs.++Confirmed tool-level return for the later T-63 bridge: own helpers should return `MCPPreparedToolRead` with staged publications; T-63 encodes the outer JSON-RPC envelope using the actual request ID before `PreparedReadResult` and terminal selection. Proposed exact own helper signatures are `handlePortfolioSummary(request: MCPPortfolioSummaryRequest, view: CapturedReadView, operation: MCPReadOperation) throws -> MCPPreparedToolRead` and `handleSnapshotTaskQuery(request: MCPSnapshotTaskQueryRequest, view: CapturedReadView, operation: MCPReadOperation) throws -> MCPPreparedToolRead`. Pass the existing admitted operation to cooperative cancellation/budget checks; do not create an independent timer or reuse retention expiry as an admission deadline. These signatures await shared wiring coordination before task 10/12 delivery; the existing handler stubs have not yet been altered.+## Verified lookup correction and capture seam++Own correction `8d4e851` preserves an immutable per-root identity across direct/aggregate appends and validates the current requested root/cursor rather than the store-wide version. Deterministic tests interleave unrelated publication, same-root append, lifecycle invalidation, expiry and same-ID/token recreation after lookup pinning. Read-only peer review confirmed the earlier defect resolved. The parent granted only the focused retention rerun; it **passed 29/29** with zero compiler errors and zero skipped tests. Task 7 is complete. The run finished and the heavy slot was released. Task 8 is the next ready task in the approved DAG.++Evidence under `/Users/arjen/Documents/Codex/2026-10-03/task-2/t2382-review-evidence/stage2-green/`: `retention-lookup-green.log`, `retention-lookup-green-results.json`, `retention-lookup-green.xcresult`. No T-63 shared source was consumed for this run.++The proposed `MCPReadCapturedPreparing.prepareCapturedRead(request:policy:operation:transform:) async throws -> MCPPreparedToolRead` is compatible with initial summaries when the transform receives a Sendable `MCPPreparedReadCapture` containing the complete declared-scope view and original `frozenMetadataBytes`, plus the same admitted operation. T-63 retains and validates observation through private preparation under that original budget; no live Models escape. T-2382 owns scope-aware ambiguity, aggregation, encoding and staged retention inside the transform, using shared generic capture validation. Replay/continuation bypass live capture and reuse the original retained view and frozen metadata bytes. The root wrapper needs an own-field refinement to persist those capsule bytes before later handler delivery; the current focused store tests compare encoded typed metadata and do not yet bind this new capsule.+## Task 8 verified RED and frozen-metadata regression++Task-8 preparation `14f050a` added projection/request/reconciliation assertions plus required `RetainedView.frozenMetadataBytes`. Scope refinement `d094e03` uses the actual provider to capture nine selected canonical task records and one foreign identity-only task, asserting that both default and explicitly narrowed queries exclude foreign closure records. Read-only peer review found no further preparation gap.++The granted projection command first failed before tests because the later-writer task used a nil required project; the first fixture correction then omitted two required Project initializer arguments. Test-only fixes `857981c` and `2d4565c` now create a separate-context project with the actual complete initializer signature. Preserve both compiler-failure results as preparation evidence, not RED or production failures.++On `2d4565c`, `MCPPortfolioProjectionTests` compiled and ran **45 cases: 43 failed against explicit `notImplemented` projection/parser seams, two existing service/ordinary stored-status checks passed**. No compiler errors or skipped tests occurred. The subsequent `MCPReusableSnapshotStoreTests` regression **passed 29/29**, verifying the required frozen-metadata field, updated fixture callsites and retained byte-preservation assertion. Both commands ran sequentially and finished; the heavy slot was released. Task 8 is complete as a RED checkpoint; task 9 is ready. Actual task-query transformation, compatibility and reconciliation behavior remains unimplemented at this checkpoint.++Evidence directory `/Users/arjen/Documents/Codex/2026-10-03/task-2/t2382-review-evidence/stage3/`: `projection-red.log` and `projection-red-retry.log`, compile-failure JSON/xcresult bundles; `projection-red-retry-2.log`, `projection-red-results.json`, `projection-red.xcresult`; `retention-regression.log`, `retention-regression-results.json`, `retention-regression.xcresult`. Later production handler preparation must explicitly include original frozen-metadata bytes in its `encodedCaptureByteCount` accounting; no accounting behavior was changed during task-8 test preparation.++## Task 9 verified GREEN under isolated host++Projection/parser source `4e1bfd38dc6562d3e70178babf5e6bb51bd9e1c9` passed peer source review with no must-fix. The parent-authorized isolation component `870a4baf6bf6d2d117e1c9c3a4446fd3fc431524` was cherry-picked as `0aef5c4a5bc0c5f2ae2a6c87a65e42ee455c3b5c`, based exactly on that source. The cherry-pick changed no MCP files. No other isolation/T-63 component was merged.++The narrow sequential grant completed: standalone isolation harness passed with `sequentialInvariantPassed:true`; dedicated development-host smoke passed 1/1; fresh projection build-for-testing succeeded. Signed-host preflight verified `me.nore.ig.Transit.development`, Debug test permission, absence of CloudKit/push/App Group entitlements, explicit `TRANSIT_PERSISTENCE_MODE=unit-test`, exact fresh host path and startup isolation guard. The generated launch retains only TransitTests/MCPPortfolioProjectionTests, with parallel testing disabled.++The first projection launch was rejected by Xcode before any cases because copied `__TESTROOT__` paths resolved relative to the evidence directory. It exited 70, with owned host drained and zero terminated PIDs. Preserve that failure as runner preparation evidence. The runner correction resolves test-root/test-host placeholders to the attested absolute products/host paths and preserves known Xcode developer placeholders. Separate attempt2 artifacts preserve all original evidence; preflight rechecks the same signed build and attested launch without overwrite.++Attempt2 passed **45 cases across 22 test declarations**, zero failures, zero skips. Xcode test-without-building and result-summary verification exited zero. Physical cleanup confirms `drained:true`, no terminated PIDs. Task 9 is complete. All owned build/test jobs have finished; the heavy slot is released. Live Transit mutations and production/server launches remain paused independently of this isolated success.++Evidence is under `/Users/arjen/Documents/Codex/2026-10-03/task-2/t2382-review-evidence/isolation/`: `harness-results.json`, `smoke-preflight.json`, `smoke-results.json`, `projection-build.log`, `projection-external-build-observation.json`, `projection-build.json`, `projection-preflight-attempt2.json`, `ProjectionOnly-attempt2.xctestrun`, `projection-tests-attempt2.log`, `projection-test-summary-attempt2.json`, `projection-test-job-attempt2.json`, `projection-tests-attempt2.xcresult`. First-attempt log/job/result and `.attempt1` preflight/launch copies remain. The summary device/configuration count records 45 passed cases; its top-level 22 count is declarations.++Task 10 is now dependency-ready, but shared binding still requires parent coordination of the exact T-63 capture-validation/preparation revision and T-2383 result-fragment delivery. This checkpoint does not consume `0ff9876` or `dc85eab`, alter shared routing, complete the full phase, run broader suites, publish a review, push, merge to main or deploy. Original freshness bytes and capture identity remain required for every retained page.++## Task 10 descriptor source checkpoint++Own descriptor source is committed at `0b7305`, with peer response-availability wording correction `1150286`. It exposes `MCPPortfolioToolDefinitions.queryProjectSummaries`, `snapshotTaskQueryInitialSchema`, `reusableContinuationSchema` and `snapshotTaskQueryDescription`. Strict disjoint branches match the existing parsers; shared query_tasks must merge its cursor alternative rather than append overlapping oneOf branches. Actual shared-type Swift 6 typecheck and lint pass, without app builds, hosts or tests. Root/peer review corrections preserve exact wire field names, lowercase read failure categories and the five-second response-availability contract.++Task 10 remains in progress pending T-63 registration/dispatch/lifecycle and shared schema bounds/const/default resolution. The exact source/API handoff and remaining helper ABI needs are recorded in `t63-module-handoff.md` for the parent's T-63 relay. Preparation does not claim delivered handlers or final integration. Parent released the slot to T-2383; T-2382 will prepare own RED source without heavy execution or live writes.++## Task 11 source preparation, dependency retained++Parent-authorized preparation `c02987b` adds 15 public-handler test declarations only. Syntax and lint pass; read-only peer review found no concrete fixture/API or false-expectation defect. A standalone typecheck against the stale isolated compiled app module was blocked before source checking by `_AtomicsShims`; no app compile, host or behavioral RED occurred. Task 11 remains pending, not started/completed in Rune, while task 10 shared wiring remains in progress. Capture fault-injection cases await the exact delivered public seam, and opaque metadata-byte wire tests await the T-2383 boundary. No shared fixture or production code was altered by this preparation.++The exact initial-summary helper ABI must forward original capsule metadata bytes as well as its typed view and admitted operation; the earlier proposed view-only signature cannot itself preserve those bytes. Parent/T-63 coordination must settle a capsule or explicit-data parameter before binding. The updated `t63-module-handoff.md` documents this requirement and the verified descriptor/test source checkpoints. All owned jobs/hosts are drained; no heavy slot is held. Live write/production-launch holds remain in force. Full integration and pre-push review/Pulsar remain outstanding.++## Agreed task-10 ABI and admitted RED fixture binding++Own `166752b` implements only the exact agreed nonisolated throw-stub interfaces: summary(request,capture:optional original capsule,operation) and snapshot(request,operation) return MCPPreparedToolRead. Initial receives the capsule directly; summary replay/continuation pass nil, and all retained paths use own root bytes without live capture. It also applies the delivered shared numeric bounds, false constant and initial-only policy default to the descriptor.++Verified T-63 b500543 MCP-only preparation was imported as 8e8d855, sole schema f4e2955 as 591555f, and failure mapper 1b2e813 as 346ceda. No App/project/isolation source changed. Updated test preparation ebaa044 has 16 declarations/18 source cases and uses authoritative bounded-dispatch Data, actual producer/service failures and actual metadata categories; plain nonquery failure text is not mistaken for an encoded READ_FAILED code. Syntax/lint and peer source review pass; app compilation and runtime remain unverified. Task10 registration/reusable-store/lifecycle wiring is still outstanding, task11 stays pending, and no heavy job/slot is held. The exact updated ABI and source handoff are in t63-module-handoff.md for parent/T-63 integration.++## T-63 exact source wiring and modern transport wording++Parent-authorized common component `226db40ec2aa78290e11ca57d40b9d7ffd18d759` was inspected with its handoff, owner map and import manifest and imported as `e13fa6f`. Only its five common MCP files changed; the ten previously owned module files were not recopied. Source-component SHA-256 is `f9da28bf0aa795651dfda650907ba65f62985fffed1aa6cca27942308b3fa57c`.++The delivered wiring registers the summary descriptor, replaces the ordinary cursor branch with the shared continuation branch, classifies summaries for bounded read admission and fallback storage, and routes retained requests before ordinary task parsing. The optional injected reusable store must share the ordinary store/coordinator/read-service publication domain; the nonisolated `Result<MCPReusableSnapshotStore, Error>` retains registration failures. Listener lifecycle invalidation fails closed. Initial summaries receive the original capsule directly under admitted capture preparation; replay, reusable continuation and snapshot task queries bypass recapture. Portfolio helper bodies remain explicit `notImplemented` stubs.++Own descriptor-only `42d2d82b8596c5a0ac65887f83d25b5bc2bf3613` follows the approved latest-only modern transport: each POST accepts one JSON-RPC object, batch arrays are rejected, and `mutate_tasks` carries application-level operations within one `tools/call` under its own write/receipt contract. Separate test-oracle correction `1cccab77cf4d4f48bc3bc640e4cc980225f4c55e` requires those positive statements. T-63 can apply the descriptor-only commit after its exact module import without copying tests or losing other owned changes. This latest transport agreement supersedes historical wire-batch wording in the planning documents.++Task 10 remains in progress until its required coordinated app compilation. Task 11 remains pending: its 16 declarations/18 expanded source cases are prepared against the delivered wiring, with no runtime RED claim. No new build, host test, live MCP write, production launch, publication, push or merge is authorized by this source-only integration checkpoint. Heavy execution awaits the parent's explicit owner-permission clarification.++A separately reported T-63 dispatcher follow-up remains pending: commit-time expiry currently emits `QUERY_EXPIRED` unconditionally. Approved retained snapshot requests require `INVALID_SNAPSHOT`, and reusable cursor requests require `INVALID_CURSOR`, with rollback and no publication. T-63 owns the family-aware preencoded fallback and focused regression. The unchanged `226db40` component does not establish the current generic expiry code as approved reusable behavior; handler expectations must preserve the required family distinction.++## Pre-gate portfolio fault normalization preparation++Parent delivered T-63 expiry regression `11cf1ab` and family mapping `11007996520d82c7e98523ad954cf072751f934c` for source-only consumption. The follow-up patch SHA-256 is `543f70119688004ac7487f63d6ae94ea23667fc082067eafdf27719a58d073c3`; original wiring and prior execution evidence remain unchanged. Its six parameterized regression cases cover actual shared stores, gate rollback, absent publication/metadata and physical drain. Neither RED nor GREEN execution is established by source delivery.++Task-12 helpers must catch retention faults before they escape into the common capture-failure mapper. The required machine-error mapping is: `PublicationRejection.capacity` → `QUERY_CAPACITY_EXCEEDED`; `PublicationRejection.busy` → `READ_BUSY`; `MCPReusableSnapshotError.invalidSnapshot` → `INVALID_SNAPSHOT`; `.invalidCursor` → `INVALID_CURSOR`; `.incompatible` → `SNAPSHOT_INCOMPATIBLE`. Pre-gate `.expired` must use the request family: summary initial/replay and snapshot task initial → `INVALID_SNAPSHOT`, summary/task reusable continuation → `INVALID_CURSOR`. Each is an error result without successful freshness metadata or unpublished identifiers; no retained lookup failure permits recapture. Preserve rollback of any reservation created before a subsequent failure.++Actual capture/coherence/serialization failures retain the shared capture mapper and its real failure metadata. Required portfolio identity/scope validation keeps its structured machine errors. Raw capacity/expiry must not escape to `prepareFailure`, whose generic fallback would mislabel them as saved-storage failures. This is a reviewed implementation contract and prepared acceptance scope; both owner helper bodies remain `notImplemented` until the actual handler RED gate permits GREEN work.++Consumed common regression `11cf1ab` as `dc84b751c6035518b698f7a015617e34a83156e0` and mapping `1100799` as `deead79815b5b9271f041c35438357d7a9cee364`; only dispatcher and its new regression file changed. Own prepared acceptance `b43dc1d` adds ninth-summary capacity and four pre-gate expired retained-family cases, using actual saved empty captures/store reservation and the existing deterministic domain clock. The handler suite now has 18 declarations/23 expanded source cases. Syntax and focused lint pass; no new source was compiled or executed. Task 10 remains in progress and task 11 pending; existing baseline evidence is preserved.++Both helpers must return the prepared machine-error result for normalized retention faults, rather than throw `MCPPortfolioRequestError`: the shared snapshot preparation bridge catches `MCPSnapshotTaskQueryError`, not `MCPPortfolioRequestError`. This distinction preserves the approved error shape across both tools.++Peer fixture correction `a2ca168acf7ab8c0ad1bda889fa89db0122db8d8` permits existing expired retained charges to remain after rejection while requiring no added visible or pending publication. Expiry text derives from captured `asOf` plus the original retention duration. This avoids imposing immediate removal or a particular helper clock implementation. The 18/23 source-case count is unchanged; parsing and focused lint pass, runtime remains unverified.++## Reviewed handler RED boundary with finalisation limitation++The parent granted an exclusive isolated run at `26e090b`. Build failed before execution solely in the delivered T-63 expiry fixture's throwing `store.prepare` inside `#require`; zero cases ran. Original build log/result/job and separate compile-failure classification remain under `handler-preparation/red-26e090b.../`. Exact owner correction `7a2f4de913beaffe166aca8d705102096488ecaf` was consumed as `cd20767592639c74ced5bd1569dfbccc0d3c868b`.++A separately granted fresh build at `cd20767` passed. Preflight verified signed development host `me.nore.ig.Transit.development`, no CloudKit/push/App Group entitlements, explicit unit-test persistence and exact-path startup guard. The restricted xctestrun selected only `MCPPortfolioHandlerTests`, serially. Console evidence records all 18 declarations/23 expanded cases completed in 0.523 seconds: four passed and nineteen failed. The subsequent Xcode finalisation did not exit within 180 seconds; the guarded runner terminated its owned process group. Job status remains `failed`, exit -15, with `drained:true`, no remaining group PIDs or terminated host PIDs. Do not claim runner `observed-red`, a finalized xcresult, normal exit or full feature acceptance. No automatic rerun is needed solely to normalize teardown.++Independent source/evidence review distinguishes fifteen meaningful scaffold-path failing cases from four fixture-only failures. Valid initial/replay/snapshot/scoped/capacity/expired-family requests reached the common preparation paths backed by the explicit `notImplemented` owner helpers: summary paths produced plain generic failure text, and task snapshot/cursor paths produced QUERY_FAILED/storage_failure instead of required retained-family errors. These demonstrate the missing handler behavior. Later semantic assertions blocked by that first failure remain obligations for GREEN acceptance. The four passing declarations establish descriptor/schema advertisement and scalar/snapshot-option validation before helpers.++The ordinary compatibility case and three capture-failure category cases instead omitted required ordinary `detailLevel`, `includeComments` and `limit`, so INVALID_INPUT occurred before capture. The producer-fault loop aborted before its summary arm. The mixed cursor-family declaration additionally used an invalid ordinary warmup after its real reusable-cursor scaffold failure. These incidental expectations require narrow own-fixture correction; they do not establish a T-63 payload or metadata defect. Capture-failure metadata remains unverified by this original run and must be observed with valid requests in the next coordinated GREEN verification.++Parent explicitly authorized completing the meaningful RED boundary with this limitation and proceeding after independent review. Task 10 is complete on actual compilation/registration evidence; task 11 is complete as the reviewed missing-handler RED boundary, with incidental fixture and finalisation limits preserved. Task 12 is in progress as a delegated source implementation; no further heavy run starts without the next parent slot grant. No live mutations occurred. Original evidence and exact console line references are in `handler-preparation/red-cd20767.../reviewed-runtime-classification.json`, the test log and failed job record.++Own fixture correction `af2deed` supplies the required ordinary arguments at the four invalid callsites, preserving results/status/order/policy/metadata expectations and 18/23 source counts. Syntax and focused lint pass; corrected fixture execution remains unverified. The detailed case-by-case original console audit is retained locally as `handler-red-oracle-classification-cd207.json` and `.md`; no routine phone delivery or progress attachment is performed.++## Task 12 delegated source checkpoint++Delegated own implementation `8478b17f554e9d7e93a3dd5b76fd1396f4295d07` changes six own source files: both handlers, reusable-store seams, summary encoding, capture charging and scalar read-pin/composite declarations. Initial summaries prepare immutable pages and charge original metadata plus encoded backing evidence before reserving. Retained replies preserve their original payload and metadata without capture; atomic pins bind lookup identity and original expiry through the final gate. Page appends combine the original pin and mutation. Guards compact outside the lock to at most eight distinct roots, validate original identity/deadline and nested domain ownership, and make no charge or swap for guard-only replies. Rollback ownership is retained until publication attachment.++Swift syntax and targeted strict lint pass. Independent wire/charge review and store-race review found no remaining own-source blocker after their refinements. No compilation or runtime GREEN is claimed for this implementation; task 12 stays in progress and task 13 remains blocked. The new guard behavior also needs runtime regression coverage. No heavy slot is held.++A source-proven T-63 selector mapper follow-up is required before GREEN. Capture-builder lines 202-203 throw `MCPReadCaptureError.projectNotFound` / `.ambiguousProject` before the owner helper. Shared portfolio preparation catches only `MCPPortfolioRequestError`, then its generic service mapper classifies these as storage failure and plain summary text. The accepted `normalizedNameResolutionAndMissingSelectorsHaveExplicitOutcomes` assertions require structured `PROJECT_NOT_FOUND` / `AMBIGUOUS_PROJECT`. Add the two narrow shared catch cases using the existing `portfolioInputFailure` before the generic mapper; preserve genuine read/coherence/serialization metadata. This is independently reviewed source proof, not a selector runtime result: the original valid-name scaffold failure blocked those later assertions. Owner helpers cannot correct a fault thrown before invocation; no common file was modified here. Local `t63-selector-fault-handoff.json` preserves exact source/assertion references.++## Integrated focused GREEN readiness++The parent-delivered sole common selector mapping `eb3d9ddc556da44c964b3e6aa2dbb4c832a04de7` was inspected with `selector-mapping.patch` and consumed as `f60c43b`. It adds only four lines: the two provider selector faults return existing structured machine errors before the generic mapper. Genuine capture-failure handling is unchanged. Source review confirms the accepted selector and three capture-category cases are reachable with the corrected request fixtures; their execution is still pending.++Own unit preparation `d67c09a` adds nine standalone `MCPReusableSnapshotReadPinTests` cases: no-charge/no-swap guard, coordinator expiry rejection and physical drain, invalidation/recreation, unrelated create/append tolerance, composite rollback, pin compaction bounds, conflicting identities and domain/store rejection. These use actual stores/domain/participant gates and existing saved fixtures. Syntax, focused lint and independent source review pass; no app compile or runtime is claimed.++Focused GREEN selects exactly `TransitTests/MCPPortfolioHandlerTests`, `TransitTests/MCPReusableSnapshotStoreTests` and `TransitTests/MCPReusableSnapshotReadPinTests`. The new external `handler_green_runner.py` preserves reviewed source/isolation/signing/startup/absolute-launch/cleanup guards, uses fresh revision-specific GREEN paths and captures summary/failure details even on incidental exit 65. Only exit zero, actual fully passed cases and passing console evidence for all three suites can establish GREEN; cleanup must drain before status passes. Runner SHA-256 is `90c3c7cfb1890c8c1213efc70b0198735a5511b216537d50273b173b35a2a9d3`; fourteen offline fake checks and independent source review pass. Original GREEN/RED runners and earlier evidence remain unchanged. No runner phase has executed. Parent reports T-1734 owns the heavy slot; await the next explicit exclusive grant. Task 12 remains in progress.
specs/portfolio-summaries/requirements-review.md Added
diff --git a/specs/portfolio-summaries/requirements-review.md b/specs/portfolio-summaries/requirements-review.mdnew file mode 100644index 00000000..91b64367--- /dev/null+++ b/specs/portfolio-summaries/requirements-review.md@@ -0,0 +1,38 @@+# Portfolio summaries: requirements review++Status: sequential critic and two-peer validation complete, including final response-bound delta; requirements await user approval.++## Design critic++Independent read-only critic ran the local `design-critic` skill after reading the complete requirements, decisions, scope, and T-63 context.++| Priority | Finding | Disposition |+| --- | --- | --- |+| P1 | Reusable cross-tool views expand existing encoded-page snapshots and need explicit user choice. | Resolved by user approval Sentinel_5479ed38c0cc8191a7c47a6487b6c0a1. T-63 owns capture/freshness; T-2382 owns externally reusable API/lifecycle. |+| P1 | Undefined shared read budget is not testable. | Shared approved contract: produce encoded response and make it available to transport within five seconds for individual reads and entire read-only batches; explicit mixed-write-batch exception. |+| P2 | Capture consistency needs an observable guarantee across project/task/milestone/comment data. | Require one immutable internally consistent view. |+| P2 | Identity diagnostic detail can grow with every task. | Recommend exact diagnostic counts with bounded identity samples and explicit sampling labels. |+| P2 | Unrelated identity corruption could unnecessarily fail scoped requests. | Fail scoped requests only when ambiguity affects scope or attribution into it. |+| P2 | Equivalent query filters need definition. | Specify project UUID/effective status reconciliation, distinct from completion-window aggregation and malformed relationship buckets. |+| P3 | Empty scoped result wording is ambiguous. | Clarify existing project with zero tasks/milestones. |+| P3 | Scope approval record stale. | Recorded actual user approval reference. |++## Peer validation++Actual local agent definition was read at `/Users/arjen/.claude/agents/peer-review-validator.md`. `PERSONAL_PROJECTS=1`; external Codex/Kiro MCP review agents are not exposed. Installed CLI startup attempts failed under the sandbox; escalated attempts were rejected for missing disclosure authorization. Parent subsequently supplied user sharing approval Sentinel_7ba5dca061b4819183c1d6066aa1e949; the prescribed one-time retries were still rejected because automatic approval review did not recognize the delegated transcript as trusted direct user authorization. Parent informed the user; retries stopped, and no new approval request or bypass is pending here. The validator obtained two independent subagent perspectives using the definition's explicit fallback: technical correctness/edge cases and architecture/scope/maintainability. This was not distinct external-model consultation.++Technical peer verified that existing `MCPQueryFilters.matches` uses raw stored status, while the task model maps unknown values to idea. Requirements now explicitly propose model-effective status for summaries and snapshot-bound queries, with malformed-status diagnostic counts. Architecture peer requested protection of ordinary task-query behavior and fail-closed handling of unsupported snapshot options; both are explicit in the draft.++Consensus: preserve approved reuse and compatibility decisions; original capture/freshness must remain immutable; no silent data truncation or live-data substitution; five-second hard deadline needs design evidence beyond a main-actor timer. No peer reopened user-approved reuse. Remaining choices and feasibility constraints are surfaced for requirements approval and the later design gate.++Further peer findings addressed: explicitly retain descriptions/metadata for full snapshot-bound task detail, reject comment-body requests rather than reading live bodies, and expose raw and effective milestone status for unknown values. The interim success-admission proposal was not approved and has been removed. The final draft preserves the approved actual five-second encoded-response/transport-availability bound and mixed-write exception.++T-63 supplied source-backed feasibility evidence: the Hummingbird/NIO router and response formatting are nonisolated before awaiting the MainActor handler, and response/request value types are nonisolated Sendable. A separate response coordinator can arbitrate timeout without waiting for noncooperative worker completion, cap lingering operations, and reject late snapshot publication. This is a design hypothesis requiring a prototype, not an implemented or tested guarantee; a timer on the blocked actor or a structured task group waiting for its child would not suffice.++## Approval questions++Legacy activeTaskCount compatibility, separate idea/in-progress counts, real shared-view reconciliation, and the actual five-second response bound with mixed-write exception are approved. Requirements approval must settle their detailed contract, current-record completion semantics, recorded activity scope, extra combined totals, five-minute retention and refresh policy, sampled diagnostics, scoped failure isolation, effective-status rules, and full-detail/comment restrictions. Design and tasks remain separate gates.++The final critic reviewed the response-bound alignment and reported no must-fix contradiction. Both independent peers subsequently reread that final delta and passed it. The actual five-second encoded-response availability guarantee, whole-read-only-batch scope, mixed-write exception, and late-publication prohibition are consistent throughout the packet. Timeout arbitration and bounded lingering work still require prototype evidence at the design gate.++**Next parent approval prompt:** Do the requirements look good or do you want additional changes? Approval covers the remaining proposed completion/activity definitions, workflow/nonterminal totals, five-minute retained-view lifetime, refresh-if-needed policy and evidence thresholds, sampled identity diagnostics, scoped failure isolation, effective-status rules, and full-detail/comment restrictions. It does not approve design, tasks, or implementation.
specs/portfolio-summaries/requirements.md Added
diff --git a/specs/portfolio-summaries/requirements.md b/specs/portfolio-summaries/requirements.mdnew file mode 100644index 00000000..1f12054b--- /dev/null+++ b/specs/portfolio-summaries/requirements.md@@ -0,0 +1,94 @@+# Portfolio summaries++Approved in full, including review decisions, in parent conversation: Sentinel_fa39017e21a08191abdcd0b7ae6c9e8e. Design, tasks, and implementation have separate approval gates.++## Introduction++Portfolio summaries expose recorded project workload without requiring an agent to download every task. Explicit status buckets, completion windows, activity evidence, and local freshness let callers describe the portfolio without mistaking backlog counts for work underway or release completion.++## Non-Goals++- Inferring product readiness, release completion, or milestone completion from task counts.+- Historical completion-event reporting or general modification tracking beyond existing recorded timestamps.+- UI dashboards, App Intent summaries, identity repair, or persisted schema migrations.+- Proving CloudKit-wide completeness or remote freshness from a local read.++### 1. Portfolio and scoped project summaries++**User Story:** As an agent, I want compact project summaries, so that I can inspect workload without transferring every task.++**Acceptance Criteria:**++1. <a name="1.1"></a>WHEN a portfolio summary is requested, the system SHALL return one summary for each captured project, including projects with zero tasks and zero milestones, with its project UUID and name.+2. <a name="1.2"></a>WHEN a project summary is requested by UUID or name, the system SHALL return only that project's summary; unknown, ambiguous, malformed, or conflicting selectors SHALL produce an explicit error rather than a successful empty portfolio or arbitrary selection.+3. <a name="1.3"></a>The summary SHALL contain aggregate counts, project/milestone identities, activity evidence, and consistency diagnostics without individual task descriptions, metadata, or comment bodies.++### 2. Status definitions and compatibility++**User Story:** As an agent, I want explicit status counts, so that I can distinguish ideas from workflow stages.++**Acceptance Criteria:**++1. <a name="2.1"></a>Each project and milestone summary SHALL include a count for each effective task status (`idea`, `planning`, `spec`, `ready-for-implementation`, `in-progress`, `ready-for-review`, `done`, `abandoned`), including zeros, and a total equal to the sum of those buckets.+2. <a name="2.2"></a>The summary SHALL expose idea count equal to the `idea` bucket, in-progress count equal to the `in-progress` bucket, workflow count equal to the sum of planning/spec/ready-for-implementation/in-progress/ready-for-review, and nonterminal count equal to idea plus workflow count; it SHALL describe these as recorded stage membership, without claiming that every workflow task is currently being worked on.+3. <a name="2.3"></a>The existing `get_projects.activeTaskCount` SHALL retain its meaning of all nonterminal tasks, including ideas, and the documentation SHALL state that meaning alongside the explicit new counts.+4. <a name="2.4"></a>WHEN stored status values are unrecognized, summaries and snapshot-bound task queries SHALL interpret those records as `idea`, matching the task model's effective status, and the summary SHALL explicitly report their count; snapshot-bound status filters and returned effective statuses SHALL apply this same rule.+5. <a name="2.5"></a>WHEN a task query does not request a reusable captured view, its existing stored-status filtering, result fields, ordering, and frozen cursor behavior SHALL remain compatible; documentation SHALL distinguish its stored-status semantics from snapshot-bound effective-status queries.++### 3. Explicit completion windows++**User Story:** As an agent, I want a defined recent-completion window, so that I can compare recorded completions over a stated interval.++**Acceptance Criteria:**++1. <a name="3.1"></a>WHEN requesting summaries, the caller SHALL provide start and end instants with explicit timezone offsets; malformed timestamps, missing endpoints, or start greater than or equal to end SHALL produce an explicit validation error, and successful responses SHALL echo the normalized UTC interval.+2. <a name="3.2"></a>The summary SHALL report separate counts of currently done and currently abandoned tasks whose recorded `completionDate` is greater than or equal to start and less than end, at project and milestone level.+3. <a name="3.3"></a>WHEN a terminal task has no recorded completion date, the summary SHALL include it in its status bucket and an explicit missing-date count but SHALL exclude it from window counts; restored nonterminal tasks SHALL be excluded from terminal window counts even if a date remains.+4. <a name="3.4"></a>The documentation SHALL identify window counts as current-record counts rather than counts of historical completion transitions, and SHALL state the start-inclusive/end-exclusive rule and timestamp formats.++### 4. Last recorded activity++**User Story:** As an agent, I want dated activity evidence, so that I can report the most recent recorded activity without inventing modification history.++**Acceptance Criteria:**++1. <a name="4.1"></a>Each project summary SHALL return the maximum timestamp from its tasks' creation/status-change dates, their comments' creation dates, and its milestones' creation/status-change dates, together with the contributing evidence kind and identity; WHEN no such evidence exists it SHALL return null.+2. <a name="4.2"></a>WHEN activity evidence timestamps tie, the system SHALL select evidence deterministically, and the documentation SHALL specify the tie-break rule and excluded evidence, including arbitrary task/project edits without recorded modification timestamps.++### 5. Milestones and identity diagnostics++**User Story:** As an agent, I want faithful milestone and identity reporting, so that inconsistent records cannot silently change portfolio conclusions.++**Acceptance Criteria:**++1. <a name="5.1"></a>Each project summary SHALL include all its captured milestones, including empty, open, done, and abandoned milestones, with raw recorded status, effective status, UUID, optional display ID, and task buckets; unrecognized raw status SHALL be flagged and interpreted as effective `open`, and terminal tasks SHALL NOT alter the milestone's reported status.+2. <a name="5.2"></a>Project totals SHALL count each captured task record assigned to that project exactly once; tasks with no milestone and tasks with invalid milestone relationships SHALL have separate breakdowns so valid milestone totals plus those breakdowns reconcile to the project totals.+3. <a name="5.3"></a>WHEN tasks have missing/unresolved project references, a portfolio response SHALL report their status counts separately from project totals; WHEN milestone links refer outside a task's project or to unresolved milestones, the summary SHALL report those task counts as invalid associations rather than crediting the referenced milestone.+4. <a name="5.4"></a>WHEN project names or task/milestone display IDs collide, the summary SHALL report exact affected-record counts and at most ten deterministic identity samples per diagnostic category with an explicit sample-completeness indicator; it SHALL NOT merge records by name or display ID, and missing permanent display IDs SHALL remain explicitly absent.+5. <a name="5.5"></a>IF duplicate UUID records make identity-based attribution ambiguous within the requested scope or into it, the system SHALL return an explicit identity-ambiguity error rather than arbitrarily choosing or merging records; ambiguity unrelated to a scoped project's attribution SHALL NOT fail that project's summary.++### 6. Snapshot reconciliation and freshness++**User Story:** As an agent, I want counts and freshness tied to one captured view, so that comparisons remain valid while records change.++**Acceptance Criteria:**++1. <a name="6.1"></a>A successful summary SHALL aggregate one immutable internally consistent captured view of saved project/task/milestone/activity evidence, excluding unsaved UI edits, identified by `snapshotId`, `asOf`, and shared T-63 freshness evidence; these fields SHALL describe the original local capture and SHALL NOT imply that all remote changes have arrived.+2. <a name="6.2"></a>WHEN task queries are requested against the summary's captured view using the same project UUID and effective-status filters before expiry, their result counts SHALL equal the corresponding summary buckets across all pages; intervening task/project/milestone/comment changes SHALL NOT alter that comparison, and documentation SHALL distinguish this from completion-window and invalid-association breakdowns.+3. <a name="6.3"></a>WHEN continuing or replaying a summary result, the system SHALL preserve original counts, identities, activity evidence, completion-window endpoints, `asOf`, and freshness metadata without extending snapshot lifetime; an expired or lost view SHALL produce an explicit restart-required error rather than current-data substitution.+4. <a name="6.4"></a>A portfolio with no projects and an existing scoped project with zero tasks/milestones SHALL carry the same capture/freshness metadata as populated results, and documentation SHALL distinguish capture time, freshness evidence time, completion interval, and expiry.+5. <a name="6.5"></a>The captured view SHALL remain reusable for five minutes from creation unless the server lifecycle invalidates it; its expiry SHALL be explicit, and a retained view SHALL NOT be evicted silently to admit another request.+6. <a name="6.6"></a>WHEN a caller requests a captured view with incompatible scope or unsupported filters/options, the system SHALL return an explicit typed compatibility error rather than recapturing live data, silently broadening scope, or ignoring options; the schema SHALL list supported snapshot-bound options.+7. <a name="6.7"></a>Snapshot-bound task queries SHALL support summary and full task detail, including captured task descriptions and metadata for full detail, with comment bodies excluded; requests for comment bodies SHALL return an explicit unsupported-option error rather than reading live comments.++### 7. Bounded outcomes and discoverability++**User Story:** As an agent, I want explicit bounded-read outcomes, so that failures and incomplete data cannot be mistaken for a valid empty portfolio.++**Acceptance Criteria:**++1. <a name="7.1"></a>The system SHALL produce and make the encoded response available to the transport within five seconds from request admission for an individual summary submitted as one JSON-RPC object per POST, including queueing, freshness evaluation, capture, aggregation, and serialization; WHEN work cannot finish within that deadline it SHALL make a typed timeout available within the same deadline without publishing a late snapshot. IF response/snapshot capacity is exceeded, the system SHALL return a typed capacity error; neither case SHALL return truncated or partial counts as a complete success.+2. <a name="7.2"></a>WHEN required project/task/milestone/activity evidence cannot be read, the system SHALL return a typed read failure distinguishable from validation, timeout, capacity, and valid zero-result outcomes.+3. <a name="7.3"></a>The MCP tool schema and documentation SHALL describe selectors, all count definitions, completion-window rules, activity evidence, diagnostics, snapshot use/expiry, freshness limitations, and bounded failure outcomes.+4. <a name="7.4"></a>WHEN requesting a new summary, the caller SHALL be able to select cached local data or refresh-if-needed behavior; the default SHALL be refresh-if-needed, with at most two seconds waiting for import evidence, and freshness SHALL use the shared T-63 thirty-second recent-import threshold with an explicit refresh outcome rather than treating waiting as proof of completeness.+5. <a name="7.5"></a>The production transport SHALL reject JSON-RPC arrays under the user-approved latest-only, single-object POST contract. Application-level `mutate_tasks` batching remains one `tools/call`; summary read handling SHALL preserve its write receipts and SHALL NOT claim a read-only five-second guarantee for a mutating call.
specs/portfolio-summaries/scope-assessment.md Added
diff --git a/specs/portfolio-summaries/scope-assessment.md b/specs/portfolio-summaries/scope-assessment.mdnew file mode 100644index 00000000..4afacc65--- /dev/null+++ b/specs/portfolio-summaries/scope-assessment.md@@ -0,0 +1,59 @@+# T-2382: Portfolio summaries — scope review++Status: scope, full-spec workflow, and feature name approved in parent conversation (Sentinel_3ccdbb1152c88191b673f3dde9f76e60). Behavioral proposals below are inputs to the requirements review; requirements, design, and tasks are not approved or implemented.++Transit agents currently download tasks to construct project summaries. This feature would expose compact project and portfolio counts with explicit status, time, identity, and freshness semantics, so agents can describe recorded work without interpreting counts as a release verdict.++## Scope approval record++The user approved the **full spec workflow** and feature name **portfolio-summaries**. Requirements approval, design approval, and task approval remain separate gates.++Full spec is appropriate because this adds a public MCP contract and requires decisions about compatibility, activity evidence, time windows, and inconsistent identities. The user also explicitly requested the full process. The local creating-spec skill requires scope approval before requirements; the requirements skill requires a confirmed feature name before drafting requirements.++## Verified baseline++- Canonical repository: `/Users/arjen/projects/personal/transit`; origin `ArjenSchwarz/transit`.+- Dedicated branch: `T-2382/portfolio-summaries`.+- Worktree: `/Users/arjen/Documents/Codex/2026-10-03/task-2/transit`.+- Base and locally observed origin/main: `0db453bba3b1da3b8958723947dc41c165ecf0dd` (merged T-2379 bounded batch queries).+- T-2380 remains `ef29b2b` on its existing worktree and does not contain this base. It is outside this task.+- No repository AGENTS.md or `.agents/skills` was found. Repository `CLAUDE.md` and local Transit/Starwave skills were inspected.+- `get_projects.activeTaskCount` currently counts every nonterminal task, including ideas. Its existing semantics must remain compatible unless explicitly approved otherwise.+- Tasks record creation, last status change, and optional completion dates; comments record creation dates. There is no general task/project edit timestamp. Milestones record creation/status/completion dates.+- T-2379 pagination retains serialized pages for five minutes. Continuations read the original result; they cannot recapture freshness or extend its lifetime.++## Proposed scope for requirements discussion++| Concern | Proposed behavior to approve during requirements |+| --- | --- |+| Portfolio and project scope | Return all projects, including empty projects; support project UUID and existing unambiguous name resolution. Unknown/ambiguous selectors produce explicit errors. |+| Counts | Include all eight status keys, including zero values, total task count, idea count, nonterminal count, and workflow count. Workflow count excludes ideas and both terminal statuses, and includes planning, spec, ready-for-implementation, in-progress, and ready-for-review. These are stage counts, not a claim that every included task is currently being worked on. |+| Compatibility | Preserve `get_projects.activeTaskCount` as the existing nonterminal count. Document it precisely; provide explicit new summary fields instead of silently changing existing consumers. Final field/tool names belong to the design gate. |+| Recent completions | Require an explicit UTC start/end window, with start inclusive and end exclusive. Count currently done tasks with completionDate inside that window; report abandoned tasks separately if included. This is a current-record view, not a historical transition/event count. Missing dates are reported separately rather than inferred. |+| Recorded activity | Return nullable last recorded activity with evidence kind. Proposed evidence is task creation/status change, comment creation, and milestone creation/status change. Do not label this general last modification; arbitrary edits have no recorded timestamp. |+| Milestones | Include open, done, and abandoned milestones, their recorded status, and all task status buckets. Open milestones can contain done/abandoned tasks without changing the milestone status or implying release completion. Show tasks without a milestone separately. |+| Identity problems | Preserve project UUID identity even when names duplicate. Explicitly flag duplicate display IDs, missing project references, and milestone/project mismatches; never collapse tasks solely by display ID or silently omit unresolved records. Exact diagnostic shape and reconciliation invariants need requirements discussion. |+| Reconciliation | Counts derive from one captured local view and agree with equivalent status/project filters over that same view. Independent live requests cannot promise equality across intervening changes. Design must define whether snapshot identity is informational or reusable for task queries. |+| Compactness | Return aggregate data and identity diagnostics without task descriptions/comments. Response size depends on projects/milestones/diagnostics, not ordinary task payloads. Bounds and pagination integrate with T-63; no successful silent truncation. |++## Shared contract needs sent to parent++T-63 owns bounded reads and freshness. Its preliminary contract is unapproved: `asOf` is local immutable capture time; `snapshotId` identifies the materialized view; freshness expresses locally observed import evidence and cannot prove remote completeness. Original capture metadata must be preserved across pages.++Portfolio aggregation needs one shared metadata envelope covering project, task, milestone, and any comment evidence captured for the result. Completion-window endpoints must be distinct from `asOf`. Empty and scoped results need the same envelope. Timeout/storage failure must be distinguishable from a valid empty project. Identity diagnostics and partial/incomplete outcomes must not be presented as exact reconciled totals. A snapshot identifier alone cannot establish comparison with separately captured task-query pages; requirements must settle the intended reconciliation guarantee before interfaces are bound.++T-2382 owns aggregation semantics and a dedicated summary service. T-63 owns freshness/read-budget services. Shared MCP handler/schema registration and read-only classification need a parent-coordinated owner in the design phase. No shared files will be edited before that agreement.++## Questions for the parent to surface++1. Full spec and `portfolio-summaries` name: approved.+2. Legacy `activeTaskCount` compatibility and separate idea/in-progress counts: approved in parent Sentinel_5479ed38c0cc8191a7c47a6487b6c0a1; extra combined counts remain requirements proposals.+3. Is the proposed currently-done completion-window definition sufficient, or is historical completion-event reporting needed? The latter needs new evidence/history beyond current records.+4. Use recorded status/comment/milestone activity (recommended), or narrow activity to task status changes? General edit activity requires additional persisted evidence.+5. Real externally reusable summary/task-query snapshots: approved in parent Sentinel_5479ed38c0cc8191a7c47a6487b6c0a1. Detailed retention/filter/error semantics remain requirements proposals.++## Capabilities and remaining gates++Per-command `require_escalated` is supported with automatic approval review; the isolated worktree creation succeeded. No global permission settings were changed. Xcode 27.0 build 27A266a is installed; no Xcode MCP tools are exposed. No builds/tests or simulator work were started. `send-md-to-phone` is available and will be run for this document. Local Codex memories directory is empty; no memory was changed.++Next: requirements approval after sequential critic/peer validation. The actual local peer-review-validator definition was found and its documented two-subagent fallback used; external CLI startup failed and escalated external disclosure was rejected by automatic approval review. See requirements-review.md for review evidence and the parent's disclosure approval request. Design and task planning follow only their preceding approvals. Implementation remains unauthorized at this gate. Full pre-push-review, including its Pulsar step, is required after implementation; no merge or deployment is authorized.
specs/portfolio-summaries/t63-module-handoff.md Added
diff --git a/specs/portfolio-summaries/t63-module-handoff.md b/specs/portfolio-summaries/t63-module-handoff.mdnew file mode 100644index 00000000..e2a621c2--- /dev/null+++ b/specs/portfolio-summaries/t63-module-handoff.md@@ -0,0 +1,136 @@+# T-2382 verified module handoff to T-63++## Verified source and isolation boundary++Ticket branch: `T-2382/portfolio-summaries`; worktree: `/Users/arjen/Documents/Codex/2026-10-03/task-2/transit`.++Pure projection/parser source is `4e1bfd38dc6562d3e70178babf5e6bb51bd9e1c9`. The exact approved isolation component `870a4baf6bf6d2d117e1c9c3a4446fd3fc431524` was cherry-picked as `0aef5c4a5bc0c5f2ae2a6c87a65e42ee455c3b5c`, with no MCP diff. On that clean checkpoint, signed development-host preflight plus isolated projection GREEN passed 45 cases, zero failures/skips. Task-9 evidence and completion are committed in `36a8000`. Earlier focused aggregation/window passed 54/54; corrected retention passed 29/29. These are focused module proofs, not final combined handler/transport acceptance.++Preserve the approved development isolation boundary when consuming MCP files. Do not merge an alternate App/project component, launch production, or perform live Transit mutations. T-2382 holds no heavy test slot after this checkpoint.++## Delivered module seams++- `PortfolioSummaryService.summarize(view: CapturedReadView, window: CompletionWindow) throws -> PortfolioSummary` aggregates complete declared scope from physical identities without live model access.+- `MCPPortfolioSummaryRequest.parse(_:)` supplies initial window/limit/selector/policy, snapshotId-only replay, and cursor/policy continuation.+- `MCPSnapshotTaskQueryRequest.parse(_:)` supplies strict captured snapshot options or reusable continuation; no project names, comments, arbitrary filters, scope expansion or policy override on initial task projection.+- `MCPPortfolioProjection.query(root: RetainedView, request: MCPSnapshotTaskQueryRequest) throws -> EncodedSnapshotTaskPages` returns private first/continuation page bytes, cursors, original metadata bytes, snapshot identity and original retention deadline. Status filtering uses effective status; full output retains canonical captured r1 while omitting comment bodies.+- `RetainedView` retains the shared `CapturedReadView`, exact `frozenMetadataBytes`, original window/request and encoded first summary page. `MCPReusableSnapshotStore` participates in the existing sole publication domain, supports staged create/append and aggregate publication, and preserves requested-root identity across unrelated updates. Its encoded capture charge must include frozen metadata and retained encoded backing.++## Shared preparation and next binding++The confirmed proposed tool-level own entrypoints are:++```swift+handlePortfolioSummary(request: MCPPortfolioSummaryRequest,+                       view: CapturedReadView,+                       operation: MCPReadOperation) throws -> MCPPreparedToolRead+handleSnapshotTaskQuery(request: MCPSnapshotTaskQueryRequest,+                        view: CapturedReadView,+                        operation: MCPReadOperation) throws -> MCPPreparedToolRead+```++Those task-12 helpers are not delivered yet: current own handler files remain explicit scaffold errors with old signatures. Do not wire them as implemented handlers or claim public integration. T-63 must supply the exact approved `MCPReadCapturedPreparing`/`MCPPreparedReadCapture`/`MCPPreparedToolRead` and generic reusable-validation revision before T-2382 binds these interfaces. Previously inspected `0ff9876` and corrected `dc85eab` have not been consumed here.++Initial capture preparation must pass the complete declared-scope immutable view, original frozen metadata bytes and the same admitted operation through private aggregation/encoding/staged retention. T-63 retains and validates its observation through that transform under the original budget, then encodes the actual-request-ID outer envelope and selects publication/result together. Replay and continuation bypass live capture and reuse original bytes/identity/expiry. Do not broaden selected project scope because foreign identity closure exists; minimal foreign milestone selected JSON remains `{milestoneId,name}` with full typed identity/relationships/status/timestamps.++T-2383's agreed ordered/validated metadata-fragment boundary still needs its exact delivered revision before final binding. Preserve unknown metadata bytes without dictionary/Double round trips; charge all retained encoded backing. Shared registry/dispatch/read-only classification/lifecycle changes belong only to T-63. Final combined acceptance, full regression and pre-push review/Pulsar remain pending.++## Descriptor delivery++Source checkpoint `0b730577d5aac2f3d63705a2d0c7ac0a1ffdc0d3` plus reviewed wording correction `11502863f9e749a12aea0563041b408694a5d67f` delivers `MCPPortfolioToolDefinitions` in its own file:++- `queryProjectSummaries: MCPToolDefinition` for `query_project_summaries`, with mutually exclusive no-selector/projectId/project initial branches, snapshotId-only replay and continuation. Every branch rejects additional properties.+- `snapshotTaskQueryInitialSchema: JSONSchema` for the deliberately restricted retained-snapshot `query_tasks` branch.+- `reusableContinuationSchema: JSONSchema`; merge/replace the common query_tasks cursor branch rather than appending an overlapping oneOf alternative. Preserve ordinary cursor dispatch/family behavior.+- `snapshotTaskQueryDescription: String` to append to the existing ordinary tool description while retaining ordinary raw-status filtering and existing field/order behavior.++Lint passed with zero violations in 447 files; strict Swift 6 typechecking used the full actual MCPTypes.swift and MCPReadMetadata.swift, without extraction or stubs. Peer review found no other concrete parser/schema mismatch after correcting advertised field spellings, failure-category case and response-availability wording. No app compilation or registration/route test was performed for this new descriptor.++Current shared JSONSchemaProperty lacks minimum/maximum, a boolean const and default. T-63 owns adding/binding `minimum:1`, `maximum:100` for limits, `const:false` for snapshot includeComments and `default:"refresh_if_needed"` for initial policy to encode these constraints machine-readably. Source currently states these constraints in descriptions and the already verified parsers enforce them. Do not claim full strict-schema registration complete until the shared owner resolves this limitation. Task 10 stays in progress; task-11 preparation cannot count as actual compiled behavioral RED before the dependency is delivered and a serialized test slot is granted.++## Initial-helper frozen-byte binding requirement++The proposed view/operation signatures above predate delivery of the frozen-metadata capsule. A typed view alone does not carry the capsule's original metadata bytes. Before binding task 12, coordinate an exact initial-summary entrypoint that also receives `MCPPreparedReadCapture` or explicit `frozenMetadataBytes: Data`; do not re-encode `view.metadata` to manufacture retained bytes. The agreed transform already receives the capsule and same operation, so the bridge must forward its bytes into the own helper. Snapshot replay/query can obtain original bytes from the existing retained root and must bypass live capture. No signature change or shared binding has been applied at this checkpoint.++## Task-11 source preparation++`c02987bbdfc1a6724e3726c6f383db5ff809f84f` adds only `MCPPortfolioHandlerTests.swift`: 15 public-dispatch test declarations covering advertised schemas, strict arguments/selectors, empty/populated metadata, frozen replay/continuation, snapshot effective-status/revision reconciliation, captured scope, cursor families, policy, fallback read classification and ordinary query compatibility. Task 11 stays pending because task 10 is not complete. Syntax and full lint pass (zero violations across 448 files); peer review found no concrete fixture/API or false-expectation defect. Standalone typechecking against the earlier isolated compiled app module stopped before checking the source at missing `_AtomicsShims`; app compilation and behavioral RED remain unverified.++Required fetch/coherence/serialization fault-injection assertions await a delivered public preparation seam; no mock shared API was invented. Exact opaque metadata-byte preservation at the wire likewise needs the delivered T-2383 fragment boundary/capsule fixture. Focused target after dependency delivery and a new isolated test slot: `TransitTests/MCPPortfolioHandlerTests`. Do not use one-step app-host testing without attesting the signed host, generated xctestrun and startup guard. No heavy job ran for this preparation.++## Agreed ABI and real-source binding checkpoint++This section supersedes the earlier view-only and case-specific proposals. Parent/T-63 agreed, and own source `166752b30ca2d4ad33d5a420fff774caa046a205` now declares exactly:++```swift+nonisolated func handlePortfolioSummary(+    request: MCPPortfolioSummaryRequest, capture: MCPPreparedReadCapture?,+    operation: MCPReadOperation+) throws -> MCPPreparedToolRead+nonisolated func handleSnapshotTaskQuery(+    request: MCPSnapshotTaskQueryRequest, operation: MCPReadOperation+) throws -> MCPPreparedToolRead+```++Initial summary receives the direct capsule from `prepareCapturedRead`; replay/continuation receive nil and must read their own retained root, original bytes, identity and expiry. Snapshot tasks obtain that retained root themselves. All bodies still throw `notImplemented`: this is the task-10 interface seam, not task-12 GREEN. There is no separate retained-summary helper.++The verified shared preparation at `b500543` was consumed as the MCP-only 19-file delta from the existing `a694c27` shared base, committed `8e8d855`. The exact schema definition `f4e29556feb36dec62e8ebeb7f20b5110a5b6f4b` was cherry-picked as `591555f`, and exact internal failure mapper `1b2e813f154b8dbfd542cb63d4bb66bdac669e1c` as `346ceda`. No App/project/isolation source was imported. Descriptor `166752b` now encodes both limit ranges, includeComments const false and the initial policy default using the sole shared schema definition; continuation has no default. Actual shared-type descriptor typecheck, helper parsing and lint passed.++Updated own tests `ebaa0448ba023210ca7b8992bfd1536b66efad1e` contain 16 declarations / 18 expanded source cases. Covered calls use actual `MCPBoundedReadDispatcher.classify`/`response` and authoritative Data; they require common classification instead of inventing it. Direct handler.handle bypasses admitted preparation in b500543 and is used only for noncovered tools/list. Test-local memory fixture binds the real saved capture builder, inactive monitor, ordinary snapshot store, service and coordinator sharing one publication domain. Typed storage/serialization/coherence source failures are tested inside the admitted worker. Nonquery failure text is plain message; assertions use the external actual category and never assume unencoded READ_FAILED or outer-encoding fallback. Machine schema constraints are asserted. Syntax, lint (zero/460) and peer source review pass; no app compilation/runtime proof is claimed.++Task 10 still awaits the owner's portfolio registration, shared dispatch/reusable-store constructor and lifecycle component. Task 11 remains pending; this bound source is preparation only until that dependency and an explicit isolated test grant arrive. Modern/API15 fragments remain a final integration dependency, not fabricated runtime coverage. The prepared runner under `t2382-review-evidence/handler-preparation/handler_runner.py` accepts an explicitly reviewed full source revision, fresh revision-specific artifacts and only the handler suite; it attests isolation-critical files against 0aef5c4, signing, mode, exact host and startup guards before launch. No runner phase was executed.++## Verified implemented helper handoff — 2026-10-04++This checkpoint supersedes every earlier scaffold/not-implemented, pending-task-10/11, and proposed view-only ABI instruction above. Tasks 10–12 are complete; final task-13 HTTP/API15 acceptance and task-15 full regression remain pending.++Exact tested source: `a3c2a705a2dc73958c12c9ce0ff6dc2355b80794`. The unchanged reviewed runner SHA256 is `90c3c7cfb1890c8c1213efc70b0198735a5511b216537d50273b173b35a2a9d3`. Fresh signed development host and restricted xctestrun preflight passed. Build and test exited zero. All three selected suites passed: 54 declarations, 61 expanded device cases, zero failures/skips/expected failures. Physical host and process group drained normally. Independent requirements-critic review verified evidence, ownership and exact ABI; no remaining own-source blocker was found. Previous `b31841c` assertion failure and teardown timeout remain preserved as failed evidence, without a GREEN claim or inferred timeout cause.++### Consume only this new portfolio-owned production component++`8478b17f554e9d7e93a3dd5b76fd1396f4295d07` changes exactly these six source files and can be consumed independently of shared T-63 registration and App/project isolation changes:++- `Transit/Transit/MCP/MCPToolHandler+PortfolioSummary.swift`+- `Transit/Transit/MCP/MCPToolHandler+SnapshotTaskQuery.swift`+- `Transit/Transit/MCP/MCPReusableSnapshotStore.swift`+- `Transit/Transit/MCP/MCPPortfolioReadEncoding.swift` (new)+- `Transit/Transit/MCP/MCPPortfolioCaptureCharge.swift` (new)+- `Transit/Transit/MCP/MCPReusableSnapshotReadPin.swift` (new)++The actual agreed entrypoints remain:++```swift+nonisolated func handlePortfolioSummary(+    request: MCPPortfolioSummaryRequest, capture: MCPPreparedReadCapture?,+    operation: MCPReadOperation+) throws -> MCPPreparedToolRead+nonisolated func handleSnapshotTaskQuery(+    request: MCPSnapshotTaskQueryRequest, operation: MCPReadOperation+) throws -> MCPPreparedToolRead+```++Initial summaries consume the direct immutable capsule with authoritative frozen metadata bytes. Replay, continuation and snapshot task projection use retained values without live capture. Encoding and all retained backing are charged before staged publication. Identity/deadline pins survive through the final sole-domain gate; pins and append mutations compact together without a guard-only store swap. Existing T-63 wiring constructs the reusable store in the same publication domain and forwards these signatures; no shared wiring edit belongs in this component.++T-63 already contains its own `226db40` bridge, `1100799` expiry-family mapper, `7a2f4de` test compile correction, and `eb3d9dd` selector-category correction, consumed locally as `e13fa6f`, `deead79`, `cd20767`, and `f60c43b` respectively. Do not cherry-pick these shared dependencies back into T-63. Descriptor `42d2d82` wording is already consumed there as `6de04f6`; its source bytes match. The earlier pure modules are already present through T-63's `990391c` module import.++Owner tests may be consumed separately: exact `a3c2a705` version of `MCPPortfolioHandlerTests.swift` (requires `MCPPortfolioFixture.swift` and earlier owner fixtures), and `d67c09a` adds `MCPReusableSnapshotReadPinTests.swift`. Reuse existing store regressions. The final ordinary-query assertion correction `a3c2a705` changes only `idea` to raw `legacy-status`; canonical baseline `201205bd` and requirements 2.4–2.5 independently verify this oracle. It does not change ordinary production behavior.++Local result evidence: `../t2382-review-evidence/handler-preparation/green-a3c2a705a2dc73958c12c9ce0ff6dc2355b80794/`. A source/hash/dependency manifest is prepared beside it for parent-directed selective integration. No routine external delivery, live writes, push, merge or deployment is authorized. The heavy slot is released; T-1734 owns it. Task-13 source preparation can proceed, but execution requires parent scheduling and final combined transport acceptance requires API15.++## Corrected actual-router fixture handoff — 2026-10-04++Current-foundation router evidence is exact `b4c104e76a482562bc8eae2ae9f54a6e5712ffc5`: fresh guarded build and signed development preflight passed; `MCPPortfolioIntegrationTests` passed 4/4, zero failures/skips, normal exit 0, owned host/process group fully drained. Independent review verified the evidence and source correction. This is not final modern/API15 acceptance.++The test-only handoff consists of `c8e7ebb6ed168881b00f3d2d38d9943b7e6434fa` (new integration test file) followed by `b4c104e76a482562bc8eae2ae9f54a6e5712ffc5` (only `import HTTPTypes` and explicit `@MainActor` on nested Environment; assertions unchanged). Alternatively take the exact tested version of `Transit/TransitTests/MCPPortfolioIntegrationTests.swift`. Also supply `Transit/TransitTests/MCPPortfolioFixture.swift` from the same revision if missing; T-63's inspected worktree did not yet contain that fixture. Existing central in-memory TestModelContainer, MCPHTTPTestHelpers/MCPTestHelpers and FallbackOutcomeFixture remain dependencies. No App/project, shared-source or spec-doc changes are required for this test handoff.++Runner SHA256: `10e02c5f2223b40f330546299a54d85961811a455e975266715f536e91f68f8f`. Local evidence lives under `../t2382-review-evidence/handler-preparation/green-b4c104e76a482562bc8eae2ae9f54a6e5712ffc5/`; a `verified-router-fixture-handoff-b4c104e76a482562bc8eae2ae9f54a6e5712ffc5.json` manifest alongside it contains exact source hashes and dependency identity. The initial compile-failed c8e7 attempt is preserved separately and executed zero tests. The volume assertion accepts complete reconciliation or approved typed timeout/capacity; its outcome branch was not separately logged, so this evidence does not independently establish that the large fixture returned full success.++Task 13 remains in progress: saved-only reads, mutation-frozen reconciliation, lifecycle invalidation and bounded volume behavior now have actual-router baseline PASS evidence. Expiry boundary preparation can proceed independently. Actual portfolio-router lingering/busy/late publication, final encoding/publication faults, restart/write-receipt integration, opaque metadata bytes and final API15 transport/session/security acceptance remain outstanding as applicable. Task 14 stays pending: the four tests revealed fixture compile issues but no owned production defect; its combined acceptance prerequisite remains unmet. Task 15/full pre-push/Pulsar also remain pending. No completion is inferred from the current-foundation pass.++## Verified actual-router expiry handoff — 2026-10-04++Consume only `ee053269f83153d136a4613db296bd735b9c2ffc`, adding `Transit/TransitTests/MCPPortfolioRouterExpiryTests.swift`. Source SHA256 `5720cf238e5150214b69f8c6551210c2ac3b0a2de0c37dd11405c04294618746`. It depends on the earlier fixture/helpers handoff, leaves the four verified integration tests unchanged, and includes no shared or App/project source. Fresh guarded build and signed development preflight passed; restricted serial execution passed 2/2, zero failures/skips, normal exit 0, all owned processes physically drained.++The two tests verify original frozen root/cursor responses just before the exact five-minute deadline, `INVALID_SNAPSHOT`/`INVALID_CURSOR` at expiry, no live recapture and accounting after physical worker drain. They use existing pin-only replies at the advanced retention clock, so they do not invent admission time or stage an append against a simulated future operation deadline. Local evidence: `../t2382-review-evidence/handler-preparation/green-ee053269f83153d136a4613db296bd735b9c2ffc/`; exact manifest `verified-expiry-handoff-ee053269f83153d136a4613db296bd735b9c2ffc.json` is beside the run directory. Runner SHA256 `79318c12e60320ad440bd6008908dd0981f941028a27da8aa2652953531e9fce` preserves the reviewed isolation/cleanup guards with only the suite selector changed.++Task 13 remains in progress and task 14 remains pending. This extends current-foundation coverage and does not establish final modern/API15 transport, opaque metadata, restart/write receipts or actual portfolio-router lingering/busy/late-publication acceptance. The heavy slot is released; no further heavy execution is authorized without parent scheduling.
specs/portfolio-summaries/tasks-review.md Added
diff --git a/specs/portfolio-summaries/tasks-review.md b/specs/portfolio-summaries/tasks-review.mdnew file mode 100644index 00000000..ca86893d--- /dev/null+++ b/specs/portfolio-summaries/tasks-review.md@@ -0,0 +1,39 @@+# Portfolio summaries: task approval review++Status: tasks approved by parent user Sentinel_c2e9343628948191b921868234aaf409; implementation authorized under the approved dependency graph. Requirements and final aligned design are approved; no production implementation has started.++Design approval: parent user “Both 63 and 2382 are approved without required changes”, Sentinel_541ceb19e7c8819193d04d23c5263041. This includes T-2382 3932e88 and T-63 5639c40 scope/publication contracts. The dedicated branch remains rooted in merged T-2380 201205bd; other worktrees are preserved.++## Execution plan and two-way handoff++Fifteen Rune-managed tasks form six adjacent test/implementation pairs, plus interfaces/schema wiring and final testing. T-63 first proves its foundation through actual admission/capture/router/transport using a synthetic read descriptor and minimal prepared-result/publication test doubles. That proof does not require T-2382 modules or T-63's remaining ordinary-read conversions. Parent supplies the foundation revision; T-2382 tasks2/3 reuse its harness and add saved-only/coherence and 2,375-task/comment-revision capture assertions before aggregation exists.++After the foundation gate passes, aggregation and retention occupy independent files/streams while T-63 completes remaining read paths. Tasks10/12 hand T-2382 descriptor/store/helpers to T-63 for shared registration and lifecycle wiring. Task13 is full cross-ticket acceptance and waits for both completed paths. It does not block the earlier foundation proof.++T-63 is sole writer of shared routing/schema/capture/freshness/deadline/publication/lifecycle files. T-2382 owns its dedicated service/store/request/projection/handler/descriptor modules and portfolio assertions. Existing passing foundation assertions are verified baseline, not manufactured failures. Design commits alone do not imply production interfaces already exist.++No scoped read claims whole-portfolio evidence. Saved-only capture never saves or rolls back pending UI edits. Retained metadata/revisions/expiry remain frozen. Selected same-store batch changes combine into one candidate/reservation and one swap; all stores validate before any commit; large retirement occurs after unlock.++## Self-check++- Rune list parses all 15 numbered pending tasks without warnings; streams and dependency references render.+- All 31 granular acceptance criteria have task references. Every GREEN item follows its paired RED item and directly depends on it.+- The dependency graph is acyclic; independent branches join into final integration. The two-ticket foundation/final handoffs avoid a mutual gate.+- Task1 supplies nonfunctional typed service/store/handler seams so RED assertions compile and fail behaviorally. Tasks7/12 replace store/handler seams. Types/schema/wiring are the skill's TDD exemptions.+- All three design risks map to executable task2/3 gates, and dependent aggregation/store work is blocked by them. App-level evidence is required; standalone timing probes remain supporting evidence.+- Parallel aggregation/store streams have separate files. Shared heavy Xcode27/simulator runs are serialized through parent. Makefile failures use Xcode MCP when available; none is currently callable, and downgrade is prohibited.+- Non-goals remain excluded: UI/App Intents, historical reporting, identity repair, persisted schema migration and deployment. No manual prerequisite is introduced by this code-only feature. T-2380 CloudKit receipt deployment remains its owner's release prerequisite.++## Review findings++Critic and two peers found registration before handler definitions; task1 now includes nonfunctional typed store/publication/handler seams. Peer feedback clarified harness reuse, verified baseline passes and foundation capture/encoding before aggregation. Final reviews passed these corrections. Parent's two-handoff clarification passed final critic and peer dependency rechecks: no circular gate or remaining must-fix.++External Codex/Kiro retries remain stopped after automatic approval review rejected delegated disclosure authorization. The permitted two-peer subagent fallback was used; no external model review is claimed.++## Subsequent workflows and approval++After implementation, run the full local pre-push-review skill including Pulsar, resolving any otherwise unauthorized publication through parent first. Frequent branch/worktree commits are authorized. Push, merge and deployment are not authorized by task approval.++The local [task skill](/Users/arjen/.codex/skills/starwave-tasks/SKILL.md) requires explicit task approval and states: “The model MUST NOT attempt to implement the feature as part of this workflow.” The parent therefore receives the next gate before production edits.++Task approval received; the planning gate is complete.
specs/portfolio-summaries/tasks.md Added
diff --git a/specs/portfolio-summaries/tasks.md b/specs/portfolio-summaries/tasks.mdnew file mode 100644index 00000000..e00545d5--- /dev/null+++ b/specs/portfolio-summaries/tasks.md@@ -0,0 +1,150 @@+---+references:+    - specs/portfolio-summaries/requirements.md+    - specs/portfolio-summaries/design.md+    - specs/portfolio-summaries/decision_log.md+---+# Portfolio summaries implementation tasks++- [x] 1. Define portfolio interfaces and deterministic captured-view fixture types <!-- id:tn4py0x -->+  - Types/interfaces only: add portfolio result/window/request/projection interfaces in Transit/Transit/MCP and Services/PortfolioSummaryService.swift, nonfunctional typed store/publication interfaces in MCPReusableSnapshotStore.swift and handler entry points in MCPToolHandler+PortfolioSummary.swift/+SnapshotTaskQuery.swift, plus Transit/TransitTests/MCPPortfolioFixture.swift. Use signatures/test seams and explicit not-implemented outcomes so tests compile and fail behaviorally; no aggregation/store/handler logic in scaffolding.+  - Consume T-63 CapturedReadView, ReadCaptureMetadata, ReadCaptureScope.wholePortfolio/projects([LocalRecordKey])/selectedQuery, completePortfolio completeness, MCPRetainedViewSource and MCPReadPublicationDomain; no duplicate DTO/fence/timer. Reusable views reject selectedQuery and retain the same typed scope.+  - Parent supplies the T-63 FOUNDATION revision rooted in merged T-2380 201205bd and implementing approved T-63 5639c40 contracts. T-63 proves admission/capture/transport/publication seams with minimal fixture adapters/test doubles before T-2382 modules; this foundation handoff must not wait for T-2382 final integration. T-63 alone edits MCPServer.swift/lifecycle, MCPToolHandler.swift, MCPToolDefinitions.swift, MCPTypes.swift, shared capture/freshness/publication/read paths. No T-2380 worktree edits.+  - Fixture carries physical relationships, raw/effective statuses, canonical comment-covered r1 tokens/full task JSON and comment evidence. Agree fixture/protocol sketches through parent before binding shared interfaces.+  - Task7 replaces store seams and task12 replaces handler seams; task10 can compile registered signatures before handler RED assertions. No unreachable helper or shared-file edits; T-63 only registers these agreed signatures.+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [6.1](requirements.md#6.1), [6.6](requirements.md#6.6), [6.7](requirements.md#6.7)+  - References: design.md++- [x] 2. RED: add saved-capture and real transport deadline risk-gate tests <!-- id:tn4py0y -->+  - Add Transit/TransitTests/MCPPortfolioReadFoundationTests.swift reusing T-63’s app-router/capture harness and adding portfolio-specific assertions: assert saved multi-entity capture, exclusion/preservation of pending UI edits, import/history mutation rejection, empty-store sentinel, foreign/unavailable fence failure and unknown freshness when store correlation is unproven.+  - Write automated Hummingbird admission-to-encoded-transport-availability assertions <=5s for individual POSTs including slow encode and blocked MainActor; generic component aggregation coverage remains internal and application-level write receipts remain protected. Test cached/default refresh, <=2s wait and 30s recent threshold.+  - Automated 2,375-task fixture with comment-covered revisions tests complete declared-scope capture and canonical revision encoding or typed deadline/capacity failure before aggregation exists; task13 adds actual summary totals/reconciliation, with no partial-success counts. Eight lingering physical workers across restart, ninth busy, exactly-once outcomes/no late publications. New missing-behavior assertions must demonstrate RED before correction; already implemented T-63 assertions may pass and must be recorded as verified baseline, never intentionally broken; standalone prototype is supporting evidence only.+  - All three design risk verification paths are this executable gate. Reserve Xcode27/shared simulator slot through parent; no concurrent heavy run. Test code may be prepared before slot, execution waits.+  - Use foundation-only synthetic read descriptor and minimal prepared-result/publication test double in the reused T-63 harness. It exercises real admission/capture/final encoding/transport availability without depending on summary handlers, reusable store or T-63 remaining ordinary-read conversions. This is the early risk gate, not final cross-ticket acceptance.+  - Blocked-by: tn4py0x (Define portfolio interfaces and deterministic captured-view fixture types)+  - Stream: 1+  - Requirements: [6.1](requirements.md#6.1), [6.4](requirements.md#6.4), [7.1](requirements.md#7.1), [7.2](requirements.md#7.2), [7.4](requirements.md#7.4), [7.5](requirements.md#7.5)+  - References: design.md++- [x] 3. GREEN: integrate T-63 read foundation into the risk harness and pass the gate <!-- id:tn4py0z -->+  - Wire task2 portfolio-specific fixtures to the actual T-63 foundation router/coordinator/capture provider using minimal test adapters; add only T-2382 fixture/harness adapters. T-63 supplies this foundation revision after its own independent risk proof; it does not await tasks7/12. Route any shared production fix to T-63 through parent; do not bypass failed assertions.+  - Run task-2 automated tests in coordinated Xcode27 slot, verify encoded responses and saved-only behavior with canonical r1 capture. If make fails, use available Xcode MCP; currently none exposed, report exact blocker and retain Xcode27 rather than downgrade.+  - Do not complete this gate without actual app-level passes. If fence/timing/volume risk invalidates approved design, stop dependent work, prepare concrete correction and surface new approval through parent. No partial-success or relaxed five-second guarantee.+  - After this foundation gate passes, tasks4/6 proceed while T-63 completes remaining read paths in parallel. Return T-2382 descriptor/store/helper integration handoff at tasks10/12; full two-ticket acceptance waits both at task13. No circular dependency between foundational proof and final integration.+  - Blocked-by: tn4py0y (RED: add saved-capture and real transport deadline risk-gate tests)+  - Stream: 1+  - Requirements: [6.1](requirements.md#6.1), [6.4](requirements.md#6.4), [7.1](requirements.md#7.1), [7.2](requirements.md#7.2), [7.4](requirements.md#7.4), [7.5](requirements.md#7.5)+  - References: design.md++- [x] 4. RED: add aggregation, window and identity property tests <!-- id:tn4py10 -->+  - Add Transit/TransitTests/PortfolioSummaryServiceTests.swift with all eight zero buckets/derived totals, empty projects/milestones, terminal and unknown raw milestone statuses, idea fallback, [start,end) edges, offsets/0–3 fractional digits and strict invalid timestamps, restored terminals/missing dates.+  - Use deterministic seeded generated fixtures and independent reference filters: sums equal physical records, valid milestone+unassigned+invalid partitions reconcile, duplicate names/display IDs never merge, <=10 stable diagnostic samples/exact completeness, orphan counts and UUID ambiguity into scope vs unrelated corruption.+  - Assert all five activity kinds, null evidence, lexical tie-break and milestone-only activity; summary payload never contains task descriptions/metadata/comment bodies. Tests initially fail against interface-only service.+  - Blocked-by: tn4py0x (Define portfolio interfaces and deterministic captured-view fixture types), tn4py0z (GREEN: integrate T-63 read foundation into the risk harness and pass the gate)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5)+  - References: design.md++- [x] 5. GREEN: implement dedicated summary service and completion-window parser <!-- id:tn4py11 -->+  - Implement Transit/Transit/Services/PortfolioSummaryService.swift and MCP/MCPPortfolioSummaryRequest.swift window value/parser to pass task4; pure Sendable captured-value computation, deterministic physical-key indexes, effective statuses and exact bounded diagnostics.+  - Validate project selector/scalar syntax in parser but require selector resolution inside T-63 fenced capture; do not resolve live names before capture. No store fetch, identity repair, mutation or actor-dependent aggregation.+  - Check cancellation/deadline between chunks without treating cooperative cancellation as deadline guarantee; preserve declared physical scope and required identity closure. Complete task4 property suite before handler integration.+  - Blocked-by: tn4py10 (RED: add aggregation, window and identity property tests)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5)+  - References: design.md++- [x] 6. RED: add reusable retention and aggregate publication race tests <!-- id:tn4py12 -->+  - Add Transit/TransitTests/MCPReusableSnapshotStoreTests.swift with injected monotonic clock, publication domain and retirement probes: eight views/16MiB charged root+pages, pending reservation accounting, append bytes only, no live eviction, five-minute original expiry/no extension.+  - Test two same-store creates/appends in one internal aggregate preserve both under ONE candidate/version/reservation and one swap; all stores validate before any commit. Stale CAS, capacity/root expiry/lifecycle/encoding/deadline rejection roll back once and error bytes contain no unpublished IDs.+  - Race simultaneous append/expiry/restart and collision in published/reserved v8 cursor tokens; out-of-scope lookups cannot widen. Prove displaced/discarded bundles last-reference release outside lock and timed-out workers cannot publish. Tests compile against task1 store interfaces and fail behaviorally against nonfunctional seams.+  - Blocked-by: tn4py0x (Define portfolio interfaces and deterministic captured-view fixture types), tn4py0z (GREEN: integrate T-63 read foundation into the risk harness and pass the gate)+  - Stream: 2+  - Requirements: [6.1](requirements.md#6.1), [6.3](requirements.md#6.3), [6.5](requirements.md#6.5), [6.6](requirements.md#6.6), [7.1](requirements.md#7.1), [7.2](requirements.md#7.2)+  - References: design.md++- [x] 7. GREEN: implement bounded reusable snapshot store and staged per-store publication <!-- id:tn4py13 -->+  - Implement Transit/Transit/MCP/MCPReusableSnapshotStore.swift to pass task6; immutable root/page/index bundles, complete captured values/options/metadata, pinning, reservations, lifecycle generation and monotonic expiry.+  - Keep separate eight/16MiB budget from ordinary pages (up to32MiB combined logical bytes plus heap overhead). Prepare combined selected changes per store outside domain; validate all candidates before nonthrowing one-swap/store commit; preencoded failures replace success.+  - Use sole T-63 MCPReadPublicationDomain lock, bounded bookkeeping, no nested independent commit lock. Carry retirement bundles through unlock before ARC release on success/rejection/timeout/purge/teardown; retained work remains charged by T-63 until physical completion.+  - Expose retained-view source and store lifecycle hooks for T-63 registration, without editing shared initialization/server files.+  - Blocked-by: tn4py12 (RED: add reusable retention and aggregate publication race tests)+  - Stream: 2+  - Requirements: [6.1](requirements.md#6.1), [6.3](requirements.md#6.3), [6.5](requirements.md#6.5), [6.6](requirements.md#6.6), [7.1](requirements.md#7.1), [7.2](requirements.md#7.2)+  - References: design.md++- [x] 8. RED: add snapshot task projection and reconciliation tests <!-- id:tn4py14 -->+  - Add Transit/TransitTests/MCPPortfolioProjectionTests.swift: summary/full captured description/metadata, omitted comment bodies but original comment-covered r1, effective status/storedStatus, supported project/status filters, duplicate status dedup and empty-array semantics.+  - Assert summary status buckets equal filtered task counts across all pages after live mutation/deletion/import; original window/asOf/freshness/expiry never change. Declared scoped keys constrain closure endpoints; incompatible options, selectedQuery capture or outside scope fail without live recapture.+  - Test stable task UUID/physical ordering, summary normalized-name/UUID/physical and milestone ordering; v8 continuation routing remains distinct from expired ordinary v4 cursors.+  - Blocked-by: tn4py11 (GREEN: implement dedicated summary service and completion-window parser), tn4py13 (GREEN: implement bounded reusable snapshot store and staged per-store publication)+  - Stream: 1+  - Requirements: [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.6](requirements.md#6.6), [6.7](requirements.md#6.7)+  - References: design.md++- [x] 9. GREEN: implement captured task projection and strict snapshot query parser <!-- id:tn4py15 -->+  - Implement Transit/Transit/MCP/MCPPortfolioProjection.swift and MCPSnapshotTaskQueryRequest.swift to pass task8; consume immutable retained capture only and preserve canonical revisions before derived output transformations.+  - Require snapshotId/detailLevel/includeComments:false/limit1–100, optional projectId/status array; reject unsupported fields/filter/scope/policy overrides. Project names are not accepted in snapshot task mode.+  - Return new pages sharing original metadata, typed scope and deadline through staged append reservations; no lifetime extension or live model/comment fetch.+  - Blocked-by: tn4py14 (RED: add snapshot task projection and reconciliation tests)+  - Stream: 1+  - Requirements: [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.6](requirements.md#6.6), [6.7](requirements.md#6.7)+  - References: design.md++- [x] 10. Define registry descriptor and integrate shared dispatch wiring through T-63 <!-- id:tn4py16 -->+  - Types/schema/wiring exemption: implement Transit/Transit/MCP/MCPPortfolioToolDefinitions.swift descriptor. Encode strict initial/replay/continuation branches, readPolicy default, count/window/activity/diagnostic/freshness/expiry/failure semantics and single-object POST transport restriction in tool descriptions/schema strings.+  - Explicitly document legacyactiveTaskCount nonterminal meaning, ordinary stored-status vs snapshot effective-status filtering, current-record rather than historical completion counts, timestamps and excluded arbitrary edits. No standalone documentation task in this code list.+  - T-63 alone wires descriptor, dependencies, readOnlyToolNames/fallback storage classification, dispatch before ordinary parser, retained-view source and lifecycle invalidation in shared files. Ordinary task text/schema behavior remains compatible; schema permits deliberate snapshot mode only.+  - Use schema/route assertions in subsequent handler test pair; compile integration in coordinated Xcode27 slot. Do not add App Intents/report UI/schema migrations.+  - Second handoff: parent gives T-63 the T-2382 module revision and agreed entrypoint signatures; T-63 supplies its registration/lifecycle integration revision. This is later than the foundation handoff and does not retroactively block task3.+  - Blocked-by: tn4py11 (GREEN: implement dedicated summary service and completion-window parser), tn4py13 (GREEN: implement bounded reusable snapshot store and staged per-store publication), tn4py15 (GREEN: implement captured task projection and strict snapshot query parser)+  - Stream: 1+  - Requirements: [2.3](requirements.md#2.3), [2.5](requirements.md#2.5), [3.4](requirements.md#3.4), [4.2](requirements.md#4.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.6](requirements.md#6.6), [7.3](requirements.md#7.3), [7.4](requirements.md#7.4), [7.5](requirements.md#7.5)+  - References: design.md++- [x] 11. RED: add portfolio handler wire, validation and error tests <!-- id:tn4py17 -->+  - Add Transit/TransitTests/MCPPortfolioHandlerTests.swift against tool-call dispatch: strict wrong/missing/unknown types, exclusive selectors, normalized-name ambiguity, window precision, limit, initial vs snapshotId-only replay vs cursor branches and policy precedence.+  - Verify _meta[me.nore.ig.transit/read] frozen capture identity/asOf/freshness/read for populated/empty/replay/continuation; required read/coherence/serialization failure distinguished from zero results and no metadata invented before capture.+  - Assert advertised schema/description semantics and fallback classification; existing query_tasks ordinary raw status/order/fields/v4 frozen metadata and get_projects.activeTaskCount remain unchanged. New handlers initially fail.+  - Blocked-by: tn4py16 (Define registry descriptor and integrate shared dispatch wiring through T-63)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [2.3](requirements.md#2.3), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.4](requirements.md#3.4), [4.2](requirements.md#4.2), [6.1](requirements.md#6.1), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.6](requirements.md#6.6), [6.7](requirements.md#6.7), [7.2](requirements.md#7.2), [7.3](requirements.md#7.3), [7.4](requirements.md#7.4), [7.5](requirements.md#7.5)+  - References: design.md++- [x] 12. GREEN: implement isolated portfolio and snapshot task handlers <!-- id:tn4py18 -->+  - Implement Transit/Transit/MCP/MCPToolHandler+PortfolioSummary.swift and +SnapshotTaskQuery.swift to pass task11, orchestrating T-63 admitted capture, pure aggregation/projection, private encoding and staged store publication.+  - Scalar validate before capture; resolve selectors within provider fence; require complete declared-scope evidence/full canonical r1/comment evidence. Replay/continuation never refetch or refresh and return original encoded values/metadata.+  - Return PreparedReadResult bytes + staged publication to enclosing individual permit; generic internal aggregate publication remains supported. Never publish IDs before complete encoding/gate success; expose typed validation/identity/compatibility/read/capacity errors with T-63 timeout/busy semantics.+  - Blocked-by: tn4py17 (RED: add portfolio handler wire, validation and error tests)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [2.3](requirements.md#2.3), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.4](requirements.md#3.4), [4.2](requirements.md#4.2), [6.1](requirements.md#6.1), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.6](requirements.md#6.6), [6.7](requirements.md#6.7), [7.2](requirements.md#7.2), [7.3](requirements.md#7.3), [7.4](requirements.md#7.4), [7.5](requirements.md#7.5)+  - References: design.md++- [x] 13. RED: add integrated publication, reconciliation and lifecycle regressions <!-- id:tn4py19 -->+  - Add Transit/TransitTests/MCPPortfolioIntegrationTests.swift exercising actual Hummingbird/router/store integration for individual POSTs: reconciliation, saved-only capture, expiry/lifecycle, bounded reads, deadline/encoding/publication failure and no unreachable IDs. Preserve two selected same-store changes, multi-store rejection, ready/blocked children and aggregate encoding/cutoff coverage at the internal coordinator boundary; do not introduce production JSON-RPC arrays.+  - Cover actual saved-only context/import fence, post-capture edits and full r1/body omission, five-minute expiry/restart/late-worker racing append, eight unfinished reads/ninth busy and unchanged application-level mutate_tasks receipt handling.+  - Repeat generated reconciliation and 2,375-task/comment fixtures at app boundary, assert transport availability <=5s without claiming hard real-time OS guarantees. Reserve parent-coordinated Xcode27 slot; no shared build concurrency.+  - Final cross-ticket acceptance requires both T-2382 modules and T-63 remaining covered-read conversions/registration on parent-approved combined revision. This final acceptance is separate from task3 foundation proof; parent schedules one integrated heavy test slot.+  - Blocked-by: tn4py18 (GREEN: implement isolated portfolio and snapshot task handlers)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.5](requirements.md#6.5), [6.6](requirements.md#6.6), [6.7](requirements.md#6.7), [7.1](requirements.md#7.1), [7.2](requirements.md#7.2), [7.3](requirements.md#7.3), [7.4](requirements.md#7.4), [7.5](requirements.md#7.5)+  - References: design.md++- [x] 14. GREEN: fix integrated portfolio path to pass end-to-end regression suite <!-- id:tn4py1a -->+  - Correct only T-2382 service/store/parser/projection/handler files revealed by task13; T-63 owns common coordinator/capture/schema/server fixes through parent. Re-run changed targeted tests in the same coordinated slot.+  - Reject any fix that saves unrelated UI work, broadens scope, changes ordinary pagination, releases lingering admission early, publishes before final enclosing response encoding or relaxes response limit. Material approved-contract change returns to parent approval gate.+  - Keep all modules reachable via common registry/dispatch/lifecycle; remove temporary interface scaffolding and ensure no orphan code. Verify requirement matrix before completing integration.+  - Blocked-by: tn4py19 (RED: add integrated publication, reconciliation and lifecycle regressions)+  - Stream: 1+  - Requirements: [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.5](requirements.md#6.5), [6.6](requirements.md#6.6), [6.7](requirements.md#6.7), [7.1](requirements.md#7.1), [7.2](requirements.md#7.2), [7.4](requirements.md#7.4), [7.5](requirements.md#7.5)+  - References: design.md++- [x] 15. Run required code checks and serialized Xcode27 regression tests <!-- id:tn4py1b -->+  - Run make lint and repository validation guards, then make test-quick and required macOS/iOS build/test coverage appropriate to shared MCP changes in parent-coordinated Xcode27 slots; no simultaneous heavy Xcode/simulator runs with T-63/other worker.+  - If Makefile fails, inspect failure and use Xcode MCP when available; no downgrade. Record exact unavailable MCP/build/permission blocker rather than claiming a pass. Re-run only after changed code/new evidence.+  - This is a testing-only task: fix findings through paired owning tasks and re-run affected tests; preserve T-2380 write/read guard regression coverage. Full pre-push-review plus Pulsar follows as separate authorized workflow, with publication permission resolved through parent before any unauthorized external publish.+  - Blocked-by: tn4py1a (GREEN: fix integrated portfolio path to pass end-to-end regression suite)+  - Stream: 1+  - Requirements: [2.3](requirements.md#2.3), [2.5](requirements.md#2.5), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.5](requirements.md#6.5), [7.1](requirements.md#7.1), [7.3](requirements.md#7.3), [7.5](requirements.md#7.5)+  - References: design.md

Things to double-check

Client compatibility Actual installed-client validation remains deferred post-merge to the user’s MacBook; no activation is claimed.
Native evidence Read integration-acceptance.md and the finalized native evidence for exact current counts, qualified union reuse, historical overlap and baseline warnings.