Production is already merged through PR250. This 41-file delta contains only unique T63 tests, fixture repairs and caller/spec documentation. All 537 compiled inputs match the finalized verified artifact byte-for-byte.
Five-second server preparation budget; eight unfinished physical operations, retained after timeout and restart.
Saved-only captures and frozen replay retain original identity, policy and freshness. Current unsupported import applicability yields unknown/null/unavailable.
Task15 finalized 11 declarations/19 bodies. Task16: 23 finalized groups,2,189 declarations / 2,425 bodies PASS; root independently queried actual native trees and rehashed 704 + 5,626 indexed artifacts plus 537 inputs.
Qualified reused iOS: 1310 declarations/1358 bodies, separate UI 21/24, supported by unchanged active-source/configuration proof.
Fixture-only repair dbf3355 aligns four detached task priorities; all 11 publication tests finalized without Thread Performance Checker messages. Original native-stall cause remains unproved.
Ready to push
Ready to push the remaining tests/docs. Four scoped reviewers found no material defect. All 537 compiled inputs are byte-identical to the verified source, supporting exact reuse of 2,189 declarations/2,425 finalized passing macOS executions and qualified iOS/UI evidence. Fresh lint passed532 files. Previous stalls and one post-body overlap qualification remain preserved. Explicit push and Claude-review approval is recorded.
f00e20c9 T-63: finalize bounded-read acceptance tests and caller contract Production bounded reads are already on main. This branch adds acceptance tests and a caller guide showing how saved-local capture differs from remote freshness and frozen replay.
New caller, diagnostics, catalog-fault and publication-expiry fixtures validate the shared contract. Existing route fixtures use modern transport helpers and bounded cleanup. The one QoS repair changes four detached priorities and preserves every assertion.
History reconciliation avoids replaying already-squashed shared modules. All 537 compiled inputs remain exactly equal to the verified source, so native 2189-declaration/2425-execution coverage remains applicable. Five unfinalized attempts are excluded; one finalized selection retains its post-body overlap qualification. Live import applicability and installed-client readiness remain explicitly unproved/deferred.
Transit/TransitTests/MCPReadCallerContractTests.swift
Why it matters. A new capture and frozen continuation have different caller meanings.
What to look at. initial versus cursor replay
Transit/TransitTests/MCPReadDiagnosticsTests.swift
Why it matters. Queue/phase diagnostics keep the original operation correlation.
What to look at. timeoutAndLateFinalizerKeepOriginalIdentityAndPhysicalCount
Transit/TransitTests/MCPReadCatalogFailureTests.swift
Why it matters. Required fetch/serialization/coherence faults cannot look like empty successes.
What to look at. executionFaultKeepsMachineCodeAndFailureEvidence
Transit/TransitTests/MCPReadPublicationDomainTests.swift
Why it matters. New warning-free finalized run verifies the actual fixture QoS repair.
What to look at. commitAndDiscardDestructionAllowConcurrentGate
Transit/TransitTests/MCPReadCoordinatorTests.swift
Why it matters. Failure and timeout paths retain cleanup and original errors.
What to look at. routerBodyFailurePreservesErrorAndAwaitsChannelCleanup
Parent-approved latest-only T2383 supersedes historical wire-array decisions; generic coordinator aggregation remains component evidence.
Continuations reuse the original records, metadata bytes and expiry; new initial calls make new captures.
There is no supported force-pull or provable current SwiftData import applicability; no heartbeat, notification or local save substitutes for that evidence.
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| minor | MCPReadPublicationFailureTests.swift:184 | MCPReadHookCaptureProbe overlaps MCPReadContractSource counting behavior. | Skipped optional test-only refactor under Phase4 constraint; no behavioral defect. |
| minor | MCPReadPublicationDomainTests fixture QoS | Two recorded Thread Performance Checker priority inversions in isolated actual runtime. | Four detached producers/gate tasks use userInitiated; assertions unchanged. Focused 11 native PASS with no warnings, then exact full-inventory reconciliation. Earlier unfinalized attempts remain excluded; causal link to their stalls unproved. |
Source: local run at 2026-10-04T15:21:37.365575+00:00 · snapshot f00e20c996b6b101c3fba501f00616d9177a7733
Baseline: none
Execution: passed · JUnit: none · Coverage: none · Baseline: absent
Coverage scope: as the project configures it
The test runner could not be detected.
Derived by declaration name, from the diff (no baseline run).
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 e6bde03631b2d4198e9ceff13b49ec56b62b64c3.
41 files: 16 code · 25 docs. Click to expand.
diff --git a/Transit/TransitTests/MCPBoundedReadRouteTests.swift b/Transit/TransitTests/MCPBoundedReadRouteTests.swiftindex c18a2fcc..454bdedb 100644--- a/Transit/TransitTests/MCPBoundedReadRouteTests.swift+++ b/Transit/TransitTests/MCPBoundedReadRouteTests.swift@@ -23,7 +23,8 @@ nonisolated struct MCPBoundedReadRouteTests { let id = String(repeating: "rpc-id-", count: 128) let response = try await MCPTestHelpers.respond(handler: fixture.handler, contentType: "application/json", accept: "application/json, text/event-stream",- protocolVersion: "2026-07-28", body: Self.body(id: id), loggerLabel: "bounded-read-route")+ protocolVersion: "2026-07-28", orderedHeaders: Self.modernHeaders,+ body: Self.body(id: id), loggerLabel: "bounded-read-route") #expect(response.status == .ok) let frame = try #require(response.json as? [String: Any]) #expect(frame["jsonrpc"] as? String == "2.0" && frame["id"] as? String == id)@@ -40,7 +41,8 @@ nonisolated struct MCPBoundedReadRouteTests { let fixture = try await Self.fixture(twoTasks: true) let first = try await MCPTestHelpers.respond(handler: fixture.handler, contentType: "application/json", accept: "application/json, text/event-stream",- protocolVersion: "2026-07-28", body: Self.body(id: "first"), loggerLabel: "bounded-read-cursor")+ protocolVersion: "2026-07-28", orderedHeaders: Self.modernHeaders,+ body: Self.body(id: "first"), loggerLabel: "bounded-read-cursor") let frame = try #require(first.json as? [String: Any]) let result = try #require(frame["result"] as? [String: Any]) let payload = try Self.payload(result)@@ -52,7 +54,8 @@ nonisolated struct MCPBoundedReadRouteTests { await MainActor.run { fixture.savedTask.name = "Changed after capture" } let replay = try await MCPTestHelpers.respond(handler: fixture.handler, contentType: "application/json", accept: "application/json, text/event-stream",- protocolVersion: "2026-07-28", body: Self.body(id: "replay", arguments: ["cursor": cursor]),+ protocolVersion: "2026-07-28", orderedHeaders: Self.modernHeaders,+ body: Self.body(id: "replay", arguments: ["cursor": cursor]), loggerLabel: "bounded-read-cursor") let replayFrame = try #require(replay.json as? [String: Any]) let replayResult = try #require(replayFrame["result"] as? [String: Any])@@ -69,8 +72,15 @@ nonisolated struct MCPBoundedReadRouteTests { func actualRouterDeadlineCoversValidAndInvalidToolArguments(invalid: Bool) async throws { let fixture = try await Self.fixture(twoTasks: true) let started = DispatchSemaphore(value: 0)- let blocker = Task { @MainActor in Self.blockMainActor(started) }- Self.waitForStart(started)+ let finished = DispatchSemaphore(value: 0)+ let blocker = Task { @MainActor in Self.blockMainActor(started, finished: finished) }+ let didStart = Self.waitForStart(started)+ if !didStart {+ blocker.cancel()+ #expect(Self.waitForFinish(finished),+ "Cancelled blocker did not signal physical completion within 8 seconds")+ }+ try #require(didStart, "MainActor blocker did not start within 2 seconds; request was not dispatched") let start = ContinuousClock.now var args: [String: Any] = ["detailLevel": "summary", "includeComments": false, "limit": 1] if invalid { args["status"] = true }@@ -78,16 +88,18 @@ nonisolated struct MCPBoundedReadRouteTests { do { response = try await MCPTestHelpers.respond(handler: fixture.handler, contentType: "application/json", accept: "application/json, text/event-stream",- protocolVersion: "2026-07-28", body: Self.body(id: "bounded", arguments: args),+ protocolVersion: "2026-07-28", orderedHeaders: Self.modernHeaders,+ body: Self.body(id: "bounded", arguments: args), loggerLabel: "bounded-read-deadline") } catch {- await blocker.value+ blocker.cancel()+ #expect(Self.waitForFinish(finished), "Throwing request blocker did not finish within 8 seconds") throw error } let elapsed = start.duration(to: .now) print("T63_ROUTE invalid_tool_arguments=\(invalid) encoded_body_elapsed=\(elapsed)") #expect(elapsed < .seconds(5))- await blocker.value+ try #require(Self.waitForFinish(finished), "Started blocker did not finish within 8 seconds") let accounting = try await MainActor.run { let store = fixture.service.snapshots return try store.domain.accounting(for: store.publicationStoreID)@@ -101,12 +113,20 @@ nonisolated struct MCPBoundedReadRouteTests { #expect(meta["snapshotId"] == nil && meta["asOf"] == nil) } - @MainActor private static func blockMainActor(_ signal: DispatchSemaphore) {+ @MainActor private static func blockMainActor(_ signal: DispatchSemaphore, finished: DispatchSemaphore) {+ defer { finished.signal() }+ guard !Task.isCancelled else { return } signal.signal() Thread.sleep(forTimeInterval: 6) } - private static func waitForStart(_ signal: DispatchSemaphore) { signal.wait() }+ private static func waitForStart(_ signal: DispatchSemaphore) -> Bool {+ signal.wait(timeout: .now() + .seconds(2)) == .success+ }++ private static func waitForFinish(_ signal: DispatchSemaphore) -> Bool {+ signal.wait(timeout: .now() + .seconds(8)) == .success+ } @MainActor private static func fixture(twoTasks: Bool = false) throws -> Fixture { let owner = try TestModelContainer()@@ -137,10 +157,17 @@ nonisolated struct MCPBoundedReadRouteTests { return Fixture(owner: owner, handler: handler, service: service, savedTask: task) } + private static var modernHeaders: [HTTPField] {+ [HTTPField(name: HTTPField.Name("Mcp-Method")!, value: "tools/call"),+ HTTPField(name: HTTPField.Name("Mcp-Name")!, value: "query_tasks")]+ }+ private static func body(id: String, arguments: [String: Any]? = nil) throws -> String { let args = arguments ?? ["detailLevel": "summary", "includeComments": false, "limit": 1] let bytes = try JSONSerialization.data(withJSONObject: ["jsonrpc": "2.0", "id": id,- "method": "tools/call", "params": ["name": "query_tasks", "arguments": args]])+ "method": "tools/call", "params": ["name": "query_tasks", "arguments": args, "_meta": [+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",+ "io.modelcontextprotocol/clientCapabilities": [:] as [String: Any]]]]) return try #require(String(data: bytes, encoding: .utf8)) }
diff --git a/Transit/TransitTests/MCPMaintenanceHandlerTests.swift b/Transit/TransitTests/MCPMaintenanceHandlerTests.swiftindex 499aef8e..84171506 100644--- a/Transit/TransitTests/MCPMaintenanceHandlerTests.swift+++ b/Transit/TransitTests/MCPMaintenanceHandlerTests.swift@@ -21,7 +21,10 @@ struct MCPMaintenanceHandlerTests { #expect(!names.contains("reassign_duplicate_display_ids")) // Core tools still present. #expect(names.contains("create_task"))- #expect(names.count == 11)+ #expect(names.count == 12)+ #expect(Set(names) == Set(["create_task", "update_task_status", "query_tasks", "update_task", "add_comment",+ "get_projects", "create_project", "create_milestone", "query_milestones", "update_milestone",+ "delete_milestone", "query_project_summaries"])) } @Test func toolsListWithMaintenanceOnIncludesBothMaintenanceTools() async throws {@@ -33,7 +36,12 @@ struct MCPMaintenanceHandlerTests { #expect(names.contains("scan_duplicate_display_ids")) #expect(names.contains("reassign_duplicate_display_ids"))- #expect(names.count == 13)+ #expect(names.count == 14)+ #expect(Set(names) == Set(["create_task", "update_task_status", "query_tasks", "update_task", "add_comment",+ "get_projects", "create_project", "create_milestone", "query_milestones", "update_milestone",+ "delete_milestone", "query_project_summaries"] + [+ "scan_duplicate_display_ids", "reassign_duplicate_display_ids"+ ])) } @Test func toggleFlipReflectsImmediatelyInToolsList() async throws {
diff --git a/Transit/TransitTests/MCPMilestoneToolTests.swift b/Transit/TransitTests/MCPMilestoneToolTests.swiftindex 85cff8e9..2271ef07 100644--- a/Transit/TransitTests/MCPMilestoneToolTests.swift+++ b/Transit/TransitTests/MCPMilestoneToolTests.swift@@ -21,12 +21,15 @@ struct MCPMilestoneToolTests { let tools = try #require(result["tools"] as? [[String: Any]]) let names = tools.compactMap { $0["name"] as? String }+ #expect(Set(names) == Set(["create_task", "update_task_status", "query_tasks", "update_task", "add_comment",+ "get_projects", "create_project", "create_milestone", "query_milestones", "update_milestone",+ "delete_milestone", "query_project_summaries"])) #expect(names.contains("create_milestone")) #expect(names.contains("query_milestones")) #expect(names.contains("update_milestone")) #expect(names.contains("delete_milestone")) #expect(names.contains("update_task"))- #expect(tools.count == 11)+ #expect(tools.count == 12) } // MARK: - create_milestone
diff --git a/Transit/TransitTests/MCPReadCallerContractTests.swift b/Transit/TransitTests/MCPReadCallerContractTests.swiftnew file mode 100644index 00000000..145bb4b4--- /dev/null+++ b/Transit/TransitTests/MCPReadCallerContractTests.swift@@ -0,0 +1,132 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPReadCallerContractTests {+ private var initial: [String: Any] { ["detailLevel": "summary", "includeComments": false, "limit": 1] }++ @Test func newQueryCreatesCaptureWhileCursorRetainsExactMetadata() async throws {+ let fixture = try MCPReadContractFixture()+ let first = try await fixture.execute(arguments: initial)+ await fixture.drain()+ let payload = try MCPReadContractFixture.payload(first)+ let cursor = try #require(payload["nextCursor"] as? String)+ let retained = try fixture.store.retainedPage(for: cursor)+ let original = try #require(retained.metadataBytes)+ fixture.source.failure = .storageFailure+ let replay = try await fixture.execute(arguments: ["cursor": cursor])+ await fixture.drain()+ #expect(try fixture.store.retainedPage(for: cursor).metadataBytes == original)+ #expect(try MCPReadContractFixture.metadata(replay)["snapshotId"] as? String+ == MCPReadContractFixture.metadata(first)["snapshotId"] as? String)+ #expect(fixture.source.calls == 1)+ fixture.source.failure = nil+ let fresh = try await fixture.execute(arguments: initial)+ await fixture.drain()+ #expect(fixture.source.calls == 2)+ #expect(try MCPReadContractFixture.metadata(fresh)["snapshotId"] as? String+ != MCPReadContractFixture.metadata(first)["snapshotId"] as? String)+ }++ @Test(arguments: 0..<4)+ func cachedAndDefaultPoliciesDoNotInventImportProof(mode: Int) async throws {+ let active = mode < 2+ let cached = mode % 2 == 0+ let fixture = try MCPReadContractFixture(syncActive: active)+ var arguments = initial+ if cached { arguments["readPolicy"] = "cached" }+ let bytes = try await fixture.execute(arguments: arguments)+ await fixture.drain()+ let metadata = try MCPReadContractFixture.metadata(bytes)+ let freshness = try #require(metadata["freshness"] as? [String: Any])+ let read = try #require(metadata["read"] as? [String: Any])+ #expect(read["policy"] as? String == (cached ? "cached" : "refresh_if_needed"))+ #expect(read["refreshOutcome"] as? String == (active && !cached ? "unavailable" : "not_requested"))+ #expect(freshness["assessment"] as? String == (active ? "unknown" : "not_applicable"))+ #expect(freshness["lastImportedAt"] is NSNull)+ #expect(freshness["evidence"] as? String == "none")+ #expect(metadata["asOf"] as? String == freshness["assessedAt"] as? String)+ #expect(fixture.source.calls == 1)+ }++ @Test func failingCaptureHasOneAttemptAndRequiresExplicitRetry() async throws {+ let fixture = try MCPReadContractFixture()+ fixture.source.failure = .storageFailure+ let failed = try await fixture.execute(arguments: initial)+ await fixture.drain()+ let payload = try MCPReadContractFixture.payload(failed)+ #expect((payload["error"] as? [String: Any])?["code"] as? String == "QUERY_FAILED")+ #expect(fixture.source.calls == 1)+ let metadata = try MCPReadContractFixture.metadata(failed)+ #expect(metadata["category"] as? String == "storage_failure")+ #expect(metadata["snapshotId"] == nil && metadata["asOf"] == nil)+ fixture.source.failure = nil+ let retry = try await fixture.execute(arguments: initial)+ await fixture.drain()+ #expect(try MCPReadContractFixture.result(retry)["isError"] as? Bool != true)+ #expect(fixture.source.calls == 2)+ }++ @Test func timedOutPhysicalWorkRequiresBackoffBeforeExplicitRetry() async throws {+ let coordinator = MCPReadCoordinator(cutoff: .milliseconds(30), maxOperations: 1)+ let started = DispatchSemaphore(value: 0)+ let release = DispatchSemaphore(value: 0)+ defer { release.signal() }+ let originalID = UUID()+ let timeout = try MCPReadContractFixture.failure("READ_TIMEOUT", id: originalID)+ let busy = try MCPReadContractFixture.failure("READ_BUSY", id: originalID)+ let call = Task.detached {+ await coordinator.execute(timeout: timeout, busy: busy,+ admission: MCPReadAdmission(operationID: originalID), diagnosticTool: "query_tasks") { _ in+ started.signal()+ let gate = await Task.detached { MCPReadContractFixture.wait(release, seconds: 2) }.value+ #expect(gate == .success)+ return Self.prepared(Data("late-success".utf8))+ }+ }+ let began = await Task.detached { MCPReadContractFixture.wait(started, seconds: 1) }.value+ #expect(began == .success)+ let response = await call.value+ #expect(response == timeout && coordinator.unfinishedCount == 1)+ let refused = await coordinator.execute(timeout: timeout, busy: busy) { _ in+ Issue.record("Busy call started another physical attempt")+ return Self.prepared(Data())+ }+ #expect(refused == busy)+ // The caller waits for capacity recovery, rather than spinning automatic read attempts.+ release.signal()+ let drainDeadline = ContinuousClock.now + .seconds(1)+ while coordinator.unfinishedCount != 0 && .now < drainDeadline { await Task.yield() }+ #expect(coordinator.unfinishedCount == 0)+ let retried = await coordinator.execute(timeout: timeout, busy: busy) { _ in+ Self.prepared(Data("explicit-retry".utf8))+ }+ #expect(retried == Data("explicit-retry".utf8))+ let finalDeadline = ContinuousClock.now + .seconds(1)+ while coordinator.unfinishedCount != 0 && .now < finalDeadline { await Task.yield() }+ #expect(coordinator.unfinishedCount == 0)+ }++ @Test func advertisedReadDescriptionsExplainPolicyEvidenceAndRetryBoundary() {+ let tools = [MCPToolDefinitions.queryTasks, MCPToolDefinitions.getProjects, MCPToolDefinitions.queryMilestones]+ for tool in tools {+ #expect(tool.description.contains("refresh_if_needed"))+ #expect(tool.description.contains("cached"))+ #expect(tool.description.contains("unknown"))+ #expect(tool.description.contains("five seconds"))+ #expect(tool.description.contains("backoff"))+ #expect(tool.description.contains("READ_BUSY") && tool.description.contains("READ_TIMEOUT"))+ }+ #expect(MCPToolDefinitions.queryTasks.description.contains("new capture"))+ #expect(MCPToolDefinitions.queryTasks.description.contains("cursor"))+ #expect(MCPToolDefinitions.queryTasks.description.contains("automatic retry"))+ }++ nonisolated private static func prepared(_ bytes: Data) -> PreparedReadResult {+ PreparedReadResult(encodedResponse: bytes, publications: [],+ publicationErrors: .init(busy: Data(), expired: Data(), capacity: Data()))+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadCatalogFailureTests.swift b/Transit/TransitTests/MCPReadCatalogFailureTests.swiftnew file mode 100644index 00000000..83a9fc09--- /dev/null+++ b/Transit/TransitTests/MCPReadCatalogFailureTests.swift@@ -0,0 +1,124 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPReadCatalogFailureTests {+ @Test(arguments: ["get_projects", "query_milestones"],+ ["storage_failure", "serialization_failure", "incoherent_capture"])+ func executionFaultKeepsMachineCodeAndFailureEvidence(tool: String, category: String) async throws {+ let source = Source(category: category)+ let store = MCPTaskQuerySnapshotStore()+ let service = MCPReadService(source: source,+ monitor: MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil), snapshots: store,+ pagePreparer: { pages, tool, operation in+ try MCPModernProviderBinding.prepareReadPages(pages, tool: tool, operation: operation)+ })+ let coordinator = MCPReadCoordinator(domain: store.domain)+ let operationID = UUID()+ let rpcID = JSONRPCId.string(operationID.uuidString)+ let receipt = DispatchSemaphore(value: 0)+ let request = MCPReadToolRequest(tool: tool, arguments: ["readPolicy": AnyCodable("cached")])+ let timeout = try Self.fallback("READ_TIMEOUT", tool: tool, id: rpcID)+ let busy = try Self.fallback("READ_BUSY", tool: tool, id: rpcID)+ let errors = try MCPBoundedReadDispatcher.publicationErrors(for: request, id: rpcID, busy: busy,+ encodeConstantToolFailure: { prepared, id in+ try MCPModernProviderBinding.read(prepared, id: id, tool: tool)+ })+ let response = await coordinator.execute(timeout: timeout, busy: busy,+ admission: MCPReadAdmission(operationID: operationID, physicalCompletion: { receipt.signal() }),+ diagnosticTool: tool) { operation in+ do {+ let prepared = try await service.prepare(tool: tool, arguments: ["readPolicy": "cached"],+ operation: operation)+ #expect(prepared.publications.isEmpty)+ let owners = try MCPModernProviderBinding.prepareReadPages([prepared], tool: tool,+ operation: operation)+ let owner = try #require(owners.first)+ #expect(owner.source.originalIsError == true)+ let bytes = try MCPBoundedReadDispatcher.encodeMeasured(prepared, id: rpcID,+ operation: operation) { prepared, id, operation in+ try MCPModernProviderBinding.read(prepared, id: id, tool: tool, operation: operation)+ }+ return PreparedReadResult(encodedResponse: bytes, publications: prepared.publications,+ publicationErrors: errors, diagnosticOutcome: .failure)+ } catch {+ Issue.record("Unexpected catalog failure preparation/encoding fault: \(error)")+ return PreparedReadResult(encodedResponse: timeout, publications: [], publicationErrors: errors)+ }+ }+ let completed = await Task.detached { Self.waitForReceipt(receipt) }.value+ #expect(completed == .success)+ #expect(coordinator.unfinishedCount == 0)+ #expect(source.calls == 1)+ let accounting = try store.domain.accounting(for: store.publicationStoreID)+ #expect(accounting.visibleEntries == 0 && accounting.pendingEntries == 0)+ #expect(accounting.visibleBytes == 0 && accounting.pendingBytes == 0)++ try Self.assertFailure(response, operationID: operationID, category: category)+ }++ private static func assertFailure(_ response: Data, operationID: UUID, category: String) throws {+ let decoded = try JSONSerialization.jsonObject(with: response)+ let frame = try #require(decoded as? [String: Any])+ #expect(frame["id"] as? String == operationID.uuidString)+ #expect(frame["error"] == nil)+ let result = try #require(frame["result"] as? [String: Any])+ #expect(result["isError"] as? Bool == true)+ let content = try #require(result["content"] as? [[String: Any]])+ let text = try #require(content.first?["text"] as? String)+ // Current baseline is valid plain text: absent JSON is a missing-code assertion,+ // never a thrown JSON parse/setup failure that could masquerade as behavioral RED.+ let logical = (try? JSONSerialization.jsonObject(with: Data(text.utf8))) as? [String: Any]+ #expect((logical?["error"] as? [String: Any])?["code"] as? String == "READ_FAILED")+ #expect(logical?["projects"] == nil && logical?["milestones"] == nil)++ let metadata = try #require((result["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any])+ #expect(metadata["category"] as? String == category)+ #expect(metadata["requestId"] as? String == operationID.uuidString)+ #expect(metadata["snapshotId"] == nil && metadata["asOf"] == nil)+ let read = try #require(metadata["read"] as? [String: Any])+ #expect(read["policy"] as? String == "cached")+ #expect(read["budgetMs"] as? Int == 5_000)+ let structured = try #require(result["structuredContent"] as? [String: Any])+ let presentation = try #require(structured["presentation"] as? [String: Any])+ #expect(presentation["errorCategory"] as? String == category)+ let provider = try #require(structured["source"] as? [String: Any])+ if (logical?["error"] as? [String: Any])?["code"] as? String == "READ_FAILED" {+ #expect(provider["kind"] as? String == "json")+ }+ if provider["kind"] as? String == "text" {+ #expect(provider["payload"] as? String == text)+ } else {+ #expect(provider["kind"] as? String == "json")+ let payload = try #require(provider["payload"] as? [String: Any])+ #expect((payload["error"] as? [String: Any])?["code"] as? String == "READ_FAILED")+ #expect(payload["projects"] == nil && payload["milestones"] == nil)+ }+ }++ nonisolated private static func waitForReceipt(_ receipt: DispatchSemaphore) -> DispatchTimeoutResult {+ receipt.wait(timeout: .now() + 2)+ }++ nonisolated private static func fallback(_ code: String, tool: String, id: JSONRPCId) throws -> Data {+ let prepared = try MCPPreparedToolRead(text: IntentHelpers.encodeJSON(["error": ["code": code]]), isError: true)+ return try MCPModernProviderBinding.read(prepared, id: id, tool: tool)+ }++ @MainActor private final class Source: MCPReadCaptureSource {+ let category: String+ var calls = 0+ init(category: String) { self.category = category }+ func capture(_ request: ReadCaptureRequest) throws -> CapturedReadView {+ calls += 1+ switch category {+ case "serialization_failure": throw MCPReadCaptureError.serializationFailure+ case "incoherent_capture": throw MCPReadCaptureError.incoherentCapture+ default: throw MCPReadCaptureError.storageFailure+ }+ }+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadContractTestSupport.swift b/Transit/TransitTests/MCPReadContractTestSupport.swiftnew file mode 100644index 00000000..c5982a88--- /dev/null+++ b/Transit/TransitTests/MCPReadContractTestSupport.swift@@ -0,0 +1,130 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor final class MCPReadContractSource: MCPReadCaptureSource {+ let builder: MCPReadCaptureBuilder+ var calls = 0+ var failure: MCPReadCaptureError?+ init(owner: TestModelContainer) {+ builder = MCPReadCaptureBuilder(container: owner.container, fence: .actorOnlyTestFixture)+ }+ func capture(_ request: ReadCaptureRequest) throws -> CapturedReadView {+ calls += 1+ if let failure { throw failure }+ return try builder.capture(request)+ }+}++@MainActor struct MCPReadContractFixture {+ let owner: TestModelContainer+ let source: MCPReadContractSource+ let store: MCPTaskQuerySnapshotStore+ let service: MCPReadService+ let coordinator: MCPReadCoordinator++ init(syncActive: Bool = false, diagnostics: MCPReadDiagnosticSink = .disabled) throws {+ owner = try TestModelContainer()+ owner.context.autosaveEnabled = false+ let project = Project(name: "Contract", description: "", gitRepo: nil, colorHex: "blue")+ owner.context.insert(project)+ for number in 1...2 {+ owner.context.insert(TransitTask(name: "Saved \(number)", type: .feature,+ project: project, displayID: .permanent(number)))+ }+ try owner.context.save()+ source = MCPReadContractSource(owner: owner)+ store = MCPTaskQuerySnapshotStore()+ service = MCPReadService(source: source, monitor: MCPImportEvidenceMonitor(+ syncActive: syncActive, storeIdentifier: syncActive ? "unproved-fixture" : nil),+ snapshots: store, diagnostics: diagnostics, pagePreparer: { pages, tool, operation in+ try MCPModernProviderBinding.prepareReadPages(pages, tool: tool, operation: operation)+ })+ coordinator = MCPReadCoordinator(domain: store.domain, diagnostics: diagnostics)+ }++ func execute(arguments: [String: Any], operationID: UUID = UUID()) async throws -> Data {+ let request = MCPReadToolRequest(tool: "query_tasks", arguments: arguments.mapValues(AnyCodable.init))+ let timeout = try Self.failure("READ_TIMEOUT", id: operationID)+ let busy = try Self.failure("READ_BUSY", id: operationID)+ let errors = try MCPBoundedReadDispatcher.publicationErrors(+ for: request, id: .string(operationID.uuidString), busy: busy,+ encodeConstantToolFailure: { tool, id in+ try MCPModernProviderBinding.read(tool, id: id, tool: request.tool)+ })+ return await coordinator.execute(timeout: timeout, busy: busy,+ admission: MCPReadAdmission(operationID: operationID), diagnosticTool: request.tool) { operation in+ do {+ operation.beginActorQueue()+ let tool = try await self.prepare(request, operation: operation)+ let bytes = try MCPBoundedReadDispatcher.encodeMeasured(tool,+ id: .string(operationID.uuidString), operation: operation) { prepared, id, operation in+ try MCPModernProviderBinding.read(prepared, id: id, tool: request.tool, operation: operation)+ }+ return PreparedReadResult(encodedResponse: bytes, publications: tool.publications,+ publicationErrors: errors, diagnosticOutcome: tool.result.isError == true ? .failure : .success)+ } catch {+ Issue.record("Caller fixture preparation failed: \(error)")+ return PreparedReadResult(encodedResponse: timeout, publications: [], publicationErrors: errors)+ }+ }+ }++ private func prepare(_ request: MCPReadToolRequest,+ operation: MCPReadOperation) async throws -> MCPPreparedToolRead {+ try await service.prepare(tool: request.tool,+ arguments: request.arguments.mapValues(\.value), operation: operation)+ }++ /// Synchronous bounded wait invoked on a detached worker, never on MainActor.+ nonisolated static func wait(_ semaphore: DispatchSemaphore, seconds: Double) -> DispatchTimeoutResult {+ semaphore.wait(timeout: .now() + seconds)+ }++ static func failure(_ code: String, id: UUID) throws -> Data {+ let tool = try MCPPreparedToolRead(text: IntentHelpers.encodeJSON(["error": ["code": code]]), isError: true)+ return try MCPModernProviderBinding.read(tool, id: .string(id.uuidString), tool: "query_tasks")+ }++ static func result(_ bytes: Data) throws -> [String: Any] {+ let decoded = try JSONSerialization.jsonObject(with: bytes)+ let frame = try #require(decoded as? [String: Any])+ return try #require(frame["result"] as? [String: Any])+ }++ static func payload(_ bytes: Data) throws -> [String: Any] {+ let decoded = try JSONSerialization.jsonObject(with: bytes)+ let frame = try #require(decoded as? [String: Any])+ return try MCPTestHelpers.decodeHTTPToolResult(frame)+ }++ static func metadata(_ bytes: Data) throws -> [String: Any] {+ let tool = try result(bytes)+ return try #require((tool["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any])+ }++ func drain() async {+ let limit = ContinuousClock.now + .seconds(2)+ while coordinator.unfinishedCount != 0 && .now < limit { await Task.yield() }+ #expect(coordinator.unfinishedCount == 0)+ withExtendedLifetime(owner) {}+ }+}++nonisolated final class MCPReadDiagnosticRecorder: @unchecked Sendable {+ private let lock = NSLock()+ private var stored: [MCPReadDiagnosticEvent] = []+ func append(_ event: MCPReadDiagnosticEvent) {+ lock.lock()+ stored.append(event)+ lock.unlock()+ }+ var events: [MCPReadDiagnosticEvent] {+ lock.lock()+ defer { lock.unlock() }+ return stored+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadCoordinatorTests.swift b/Transit/TransitTests/MCPReadCoordinatorTests.swiftindex 0344f8c2..be1ca4ec 100644--- a/Transit/TransitTests/MCPReadCoordinatorTests.swift+++ b/Transit/TransitTests/MCPReadCoordinatorTests.swift@@ -15,10 +15,16 @@ nonisolated struct MCPReadCoordinatorTests { @Test @concurrent func actualRouterReturnsTimeoutWhileMainActorIsBlocked() async throws { let coordinator = MCPReadCoordinator() let started = DispatchSemaphore(value: 0)- let blocker = Task { @MainActor in- Self.blockMainActor(started)+ let finished = DispatchSemaphore(value: 0)+ let blocker = Task { @MainActor in Self.blockMainActor(started, finished: finished) }+ let didStart = Self.waitForStart(started)+ if !didStart {+ #expect(coordinator.unfinishedCount == 0)+ blocker.cancel()+ #expect(Self.waitForFinish(finished),+ "Cancelled blocker did not signal physical completion within 8 seconds") }- Self.waitForStart(started)+ try #require(didStart, "MainActor blocker did not start within 2 seconds; request was not dispatched") let router = Router(context: MCPRequestContext.self) router.post("/read") { _, _ in await MCPReadTransportAdapter.response(coordinator: coordinator,@@ -26,24 +32,28 @@ nonisolated struct MCPReadCoordinatorTests { await MainActor.run { Self.result("success") } } }- let channel = EmbeddedChannel()- defer { _ = try? channel.finish() }- let context = MCPRequestContext(source: ApplicationRequestContextSource(- channel: channel, logger: Logger(label: "read-deadline-fixture"))) let request = Request(head: HTTPRequest(method: .post, scheme: "http", authority: "localhost", path: "/read"), body: RequestBody(buffer: ByteBuffer())) let start = ContinuousClock.now- let response = try await router.buildResponder().respond(to: request, context: context)- let writer = ReadResponseWriter()- try await response.body.write(writer)+ let output: (Response, Data)+ do {+ output = try await Self.respond(router: router, request: request)+ } catch {+ blocker.cancel()+ #expect(Self.waitForFinish(finished), "Throwing request blocker did not finish within 8 seconds")+ await Self.waitForPhysicalDrain(coordinator)+ #expect(coordinator.unfinishedCount == 0)+ throw error+ }+ let (response, bytes) = output let elapsed = start.duration(to: .now)- #expect(Data(buffer: writer.bytes.withLockedValue { $0 }) == Data("timeout".utf8))+ #expect(bytes == Data("timeout".utf8)) print("READ_DEADLINE router_and_body_elapsed=\(elapsed) blocked_main_actor=6s") #expect(elapsed < .seconds(5)) #expect(response.status == .ok) #expect(coordinator.unfinishedCount == 1)- await blocker.value- try await Task.sleep(for: .milliseconds(30))+ try #require(Self.waitForFinish(finished), "Started blocker did not finish within 8 seconds")+ await Self.waitForPhysicalDrain(coordinator) #expect(coordinator.unfinishedCount == 0) } @@ -139,6 +149,7 @@ nonisolated struct MCPReadCoordinatorTests { } } + // Synthetic /read adapter measures internal aggregate budgeting; production MCP rejects arrays. @Test @concurrent func nearBodyCeilingRouterBatchAccountsForFallbackPreparation() async throws { let coordinator = MCPReadCoordinator() let input = try Self.largeBatchInput()@@ -167,18 +178,11 @@ nonisolated struct MCPReadCoordinatorTests { print("READ_BATCH admission_to_encoded=\(elapsed) request_bytes=\(input.count)") return Response(status: .ok, body: .init(byteBuffer: ByteBuffer(data: response ?? Data()))) }- let channel = EmbeddedChannel()- defer { _ = try? channel.finish() }- let context = MCPRequestContext(source: ApplicationRequestContextSource(- channel: channel, logger: Logger(label: "large-read-batch-fixture"))) let request = Request(head: HTTPRequest(method: .post, scheme: "http", authority: "localhost", path: "/read"), body: RequestBody(buffer: ByteBuffer(data: input))) let start = ContinuousClock.now- let response = try await router.buildResponder().respond(to: request, context: context)- let writer = ReadResponseWriter()- try await response.body.write(writer)+ let (_, bytes) = try await Self.respond(router: router, request: request) let elapsed = start.duration(to: .now)- let bytes = Data(buffer: writer.bytes.withLockedValue { $0 }) let outcomes = try #require(try JSONSerialization.jsonObject(with: bytes) as? [[String: String]]) #expect(elapsed < .seconds(5)) #expect(outcomes.count == 80)@@ -229,6 +233,33 @@ nonisolated struct MCPReadCoordinatorTests { #expect(coordinator.unfinishedCount == 0) } + @Test @concurrent func routerBodyFailurePreservesErrorAndAwaitsChannelCleanup() async throws {+ let router = Router(context: MCPRequestContext.self)+ router.post("/throw") { _, _ in+ Response(status: .ok, body: .init { writer in+ try await writer.write(ByteBuffer(string: "partial body"))+ throw ReadBodyFailure.intentional+ })+ }+ router.post("/clean") { _, _ in+ Response(status: .ok, body: .init(byteBuffer: ByteBuffer(string: "next clean response")))+ }+ let started = ContinuousClock.now+ let request = Request(head: HTTPRequest(method: .post, scheme: "http", authority: "localhost", path: "/throw"),+ body: RequestBody(buffer: ByteBuffer()))+ do {+ _ = try await Self.respond(router: router, request: request)+ Issue.record("Throwing response body unexpectedly succeeded")+ } catch let error as ReadBodyFailure {+ #expect(error == .intentional)+ }+ #expect(started.duration(to: .now) <= .seconds(5))+ let next = Request(head: HTTPRequest(method: .post, scheme: "http", authority: "localhost", path: "/clean"),+ body: RequestBody(buffer: ByteBuffer()))+ let (_, bytes) = try await Self.respond(router: router, request: next)+ #expect(bytes == Data("next clean response".utf8))+ }+ private static func largeBatchInput() throws -> Data { let longID = String(repeating: "x", count: 30_000) let requests = (0..<32).map { ["jsonrpc": "2.0", "id": "\($0)-\(longID)", "method": "read"] }@@ -237,24 +268,70 @@ nonisolated struct MCPReadCoordinatorTests { return try JSONSerialization.data(withJSONObject: requests) } + private static func result(_ text: String) -> PreparedReadResult {+ PreparedReadResult(encodedResponse: Data(text.utf8), publications: [],+ publicationErrors: PreencodedPublicationErrors(+ busy: Data("busy".utf8), expired: Data("expired".utf8), capacity: Data("capacity".utf8)))+ }+}++extension MCPReadCoordinatorTests {+ private enum ReadBodyFailure: Error, Equatable { case intentional } private static func frame(id: String?, outcome: String) throws -> Data { try JSONSerialization.data(withJSONObject: ["id": id ?? "notification", "outcome": outcome]) } private static func blockAssembly() { Thread.sleep(forTimeInterval: 0.5) } - @MainActor private static func blockMainActor(_ semaphore: DispatchSemaphore) {+ @MainActor private static func blockMainActor(_ semaphore: DispatchSemaphore, finished: DispatchSemaphore) {+ defer { finished.signal() }+ guard !Task.isCancelled else { return } semaphore.signal() Thread.sleep(forTimeInterval: 6) } - private static func waitForStart(_ semaphore: DispatchSemaphore) { semaphore.wait() }+ private static func waitForStart(_ semaphore: DispatchSemaphore) -> Bool {+ semaphore.wait(timeout: .now() + .seconds(2)) == .success+ } - private static func result(_ text: String) -> PreparedReadResult {- PreparedReadResult(encodedResponse: Data(text.utf8), publications: [],- publicationErrors: PreencodedPublicationErrors(- busy: Data("busy".utf8), expired: Data("expired".utf8), capacity: Data("capacity".utf8)))+ private static func waitForFinish(_ semaphore: DispatchSemaphore) -> Bool {+ semaphore.wait(timeout: .now() + .seconds(8)) == .success+ }++ private static func waitForPhysicalDrain(_ coordinator: MCPReadCoordinator) async {+ for _ in 0..<100 where coordinator.unfinishedCount != 0 {+ try? await Task.sleep(for: .milliseconds(5))+ }+ }++ private static func respond(router: Router<MCPRequestContext>, request: Request) async throws -> (Response, Data) {+ 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: "bounded-read-component")))+ let response = try await router.buildResponder().respond(to: request, context: context)+ let writer = ReadResponseWriter()+ try await response.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 (response, bytes)+ } catch {+ if let channel = ownedChannel {+ do {+ let leftovers = try await channel.finish(acceptAlreadyClosed: true)+ #expect(leftovers.isClean)+ } catch { Issue.record("Read test channel cleanup failed: \(error)") }+ }+ await loop.shutdownGracefully()+ throw error+ } }+ } private nonisolated final class ReadRecordingPublication: MCPPreparedPublication, @unchecked Sendable {
diff --git a/Transit/TransitTests/MCPReadDiagnosticsTests.swift b/Transit/TransitTests/MCPReadDiagnosticsTests.swiftnew file mode 100644index 00000000..69a54050--- /dev/null+++ b/Transit/TransitTests/MCPReadDiagnosticsTests.swift@@ -0,0 +1,173 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++/// Independent task 14 preparation. No runtime RED or task 15 instrumentation is supplied yet.+@MainActor @Suite(.serialized)+struct MCPReadDiagnosticsTests {+ @Test func disabledSinkDoesNoWork() {+ let recorder = MCPReadDiagnosticRecorder()+ let sink = MCPReadDiagnosticSink(capacity: 0, writer: { recorder.append($0) })+ #expect(!sink.enqueue(event()))+ #expect(sink.pendingCount == 0 && recorder.events.isEmpty)+ }++ @Test func savedReadReportsActualPhasesWithOriginalCorrelation() async throws {+ let recorder = MCPReadDiagnosticRecorder()+ let sink = MCPReadDiagnosticSink(writer: { recorder.append($0) })+ let fixture = try MCPReadContractFixture(diagnostics: sink)+ let id = UUID()+ _ = try await fixture.execute(arguments: ["detailLevel": "summary", "includeComments": false,+ "limit": 1], operationID: id)+ await fixture.drain()+ let events = await waitForEvents(recorder, phase: .physicalFinish)+ for phase in [MCPReadDiagnosticPhase.queue, .refresh, .capture, .transform, .serialization, .terminal] {+ #expect(events.contains { $0.phase == phase })+ }+ for value in events {+ #expect(value.context.operationID == id && value.context.tool == "query_tasks")+ #expect(value.context.generation > 0)+ #expect(value.context.responseDeadline == value.context.admittedAt + .seconds(5))+ #expect(value.context.internalCutoff == value.context.admittedAt + .milliseconds(4_850))+ #expect(value.startedAt >= value.context.admittedAt && value.finishedAt >= value.startedAt)+ #expect(value.unfinishedPhysicalCount >= 0 && value.unfinishedPhysicalCount <= 8)+ }+ #expect(events.contains { $0.phase == .physicalFinish && $0.unfinishedPhysicalCount == 0 })+ // A single request must not invent an aggregation measurement for nonexistent wire-array work.+ #expect(!events.contains { $0.phase == .aggregation })+ }++ @Test func blockedWriterKeepsQueueBoundedAndCannotDelayTimerOrHoldDomain() async {+ let entered = DispatchSemaphore(value: 0)+ let loggingRelease = DispatchSemaphore(value: 0)+ let workerRelease = DispatchSemaphore(value: 0)+ let workerStarted = DispatchSemaphore(value: 0)+ let recorded = MCPReadDiagnosticRecorder()+ defer { loggingRelease.signal(); workerRelease.signal() }+ let sink = MCPReadDiagnosticSink(capacity: 2) { value in+ recorded.append(value)+ guard recorded.events.count == 1 else { return }+ entered.signal()+ let released = loggingRelease.wait(timeout: .now() + 2)+ #expect(released == .success)+ }+ let before = ContinuousClock.now+ #expect(sink.enqueue(event()))+ #expect(before.duration(to: .now) < .milliseconds(100))+ let loggingStarted = await Task.detached { MCPReadContractFixture.wait(entered, seconds: 0.2) }.value+ #expect(loggingStarted == .success)+ #expect(sink.enqueue(event()))+ #expect(!sink.enqueue(event()))+ #expect(sink.pendingCount <= 2)+ let domain = MCPReadPublicationDomain()+ let coordinator = MCPReadCoordinator(domain: domain, cutoff: .milliseconds(30), diagnostics: sink)+ let start = ContinuousClock.now+ let call = Task.detached {+ await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8),+ diagnosticTool: "query_tasks") { _ in+ workerStarted.signal()+ let released = await Task.detached { MCPReadContractFixture.wait(workerRelease, seconds: 2) }.value+ #expect(released == .success)+ return Self.prepared(Data("late".utf8))+ }+ }+ let started = await Task.detached { MCPReadContractFixture.wait(workerStarted, seconds: 1) }.value+ #expect(started == .success)+ let bytes = await call.value+ #expect(bytes == Data("timeout".utf8) && start.duration(to: .now) < .milliseconds(200))+ let lockStart = ContinuousClock.now+ #expect(coordinator.unfinishedCount == 1)+ #expect(lockStart.duration(to: .now) < .milliseconds(100))+ workerRelease.signal()+ loggingRelease.signal()+ await drain(coordinator)+ let sinkDeadline = ContinuousClock.now + .seconds(1)+ while sink.pendingCount != 0 && .now < sinkDeadline { await Task.yield() }+ #expect(sink.pendingCount == 0)+ }++ @Test func timeoutAndLateFinalizerKeepOriginalIdentityAndPhysicalCount() async {+ let recorder = MCPReadDiagnosticRecorder()+ let sink = MCPReadDiagnosticSink(writer: { recorder.append($0) })+ let coordinator = MCPReadCoordinator(cutoff: .milliseconds(30), maxOperations: 1, diagnostics: sink)+ let gate = DispatchSemaphore(value: 0)+ let workerStarted = DispatchSemaphore(value: 0)+ defer { gate.signal() }+ let id = UUID()+ let call = Task.detached {+ await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8),+ admission: MCPReadAdmission(operationID: id), diagnosticTool: "query_tasks") { _ in+ workerStarted.signal()+ let released = await Task.detached { MCPReadContractFixture.wait(gate, seconds: 2) }.value+ #expect(released == .success)+ return Self.prepared(Data("discarded-late-result".utf8))+ }+ }+ let started = await Task.detached { MCPReadContractFixture.wait(workerStarted, seconds: 1) }.value+ #expect(started == .success)+ let bytes = await call.value+ #expect(bytes == Data("timeout".utf8) && coordinator.unfinishedCount == 1)+ gate.signal()+ await drain(coordinator)+ let events = await waitForEvents(recorder, phase: .physicalFinish)+ #expect(events.contains { $0.phase == .terminal && $0.outcome == .timeout+ && $0.unfinishedPhysicalCount == 1 })+ #expect(events.contains { $0.outcome == .discarded || $0.outcome == .lateCompletion })+ #expect(events.contains { $0.phase == .physicalFinish && $0.unfinishedPhysicalCount == 0 })+ #expect(events.allSatisfy { $0.context.operationID == id && $0.context.tool == "query_tasks" })+ }++ /// Historical coordinator assembly proof only; modern production rejects wire arrays.+ @Test func historicalComponentAggregationReportsItsMeasuredInterval() async throws {+ let recorder = MCPReadDiagnosticRecorder()+ let sink = MCPReadDiagnosticSink(writer: { recorder.append($0) })+ let coordinator = MCPReadCoordinator(diagnostics: sink)+ let admittedAt = ContinuousClock.now+ let elements = [1, 2].map { number in+ MCPReadBatchElement.read(MCPReadBatchWork(timeout: Data("timeout".utf8),+ busy: Data("busy".utf8), responds: true) { _ in+ Self.prepared(Data("\(number)".utf8))+ })+ }+ let bytes = await coordinator.executeBatch(elements, admittedAt: admittedAt) { values in+ Self.prepared(MCPReadBatchEncoding.array(values.map { $0?.encodedResponse }) ?? Data())+ }+ #expect(bytes == Data("[1,2]".utf8))+ await drain(coordinator)+ let values = await waitForEvents(recorder, phase: .aggregation)+ let intervals = values.filter { $0.phase == .aggregation }+ #expect(intervals.count == 1)+ for interval in intervals {+ #expect(interval.context.admittedAt == admittedAt)+ #expect(interval.startedAt >= admittedAt && interval.finishedAt >= interval.startedAt)+ }+ }++ private func event() -> MCPReadDiagnosticEvent {+ let start = ContinuousClock.now+ return MCPReadDiagnosticEvent(context: MCPReadDiagnosticContext(operationID: UUID(), tool: "query_tasks",+ generation: 1, admittedAt: start, responseDeadline: start + .seconds(5),+ internalCutoff: start + .milliseconds(4_850)), phase: .queue,+ startedAt: start, finishedAt: .now, outcome: nil, unfinishedPhysicalCount: 1)+ }++ private func waitForEvents(_ recorder: MCPReadDiagnosticRecorder,+ phase: MCPReadDiagnosticPhase) async -> [MCPReadDiagnosticEvent] {+ let deadline = ContinuousClock.now + .seconds(1)+ while !recorder.events.contains(where: { $0.phase == phase }) && .now < deadline { await Task.yield() }+ return recorder.events+ }++ private func drain(_ coordinator: MCPReadCoordinator) async {+ let deadline = ContinuousClock.now + .seconds(1)+ while coordinator.unfinishedCount != 0 && .now < deadline { await Task.yield() }+ #expect(coordinator.unfinishedCount == 0)+ }++ nonisolated private static func prepared(_ bytes: Data) -> PreparedReadResult {+ PreparedReadResult(encodedResponse: bytes, publications: [],+ publicationErrors: .init(busy: Data(), expired: Data(), capacity: Data()))+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadPublicationDomainTests.swift b/Transit/TransitTests/MCPReadPublicationDomainTests.swiftindex 2773cd7b..90f37383 100644--- a/Transit/TransitTests/MCPReadPublicationDomainTests.swift+++ b/Transit/TransitTests/MCPReadPublicationDomainTests.swift@@ -205,7 +205,7 @@ extension MCPReadPublicationDomainTests { started: started, release: release), chargeEntries: 1, chargeBytes: 1, newTokens: ["a"], deadline: deadline) }- let finalizer = Task.detached {+ let finalizer = Task.detached(priority: .userInitiated) { domain.withLock { if let pending = domain.stores[store]?.pending.values.first { if commit { pending.commitLocked(in: domain) } else { pending.discardLocked(in: domain) }@@ -214,7 +214,7 @@ extension MCPReadPublicationDomainTests { } #expect(wait(started) == .success) let gateStart = ContinuousClock.now- let gate = Task.detached { domain.withLock { 42 } }+ let gate = Task.detached(priority: .userInitiated) { domain.withLock { 42 } } #expect(await gate.value == 42) #expect(gateStart.duration(to: .now) < .seconds(1)) release.signal()@@ -260,11 +260,11 @@ extension MCPReadPublicationDomainTests { index: PublicationDestructionIndex(descriptor: try MCPPublicationIndexDescriptor(roots: []), started: started, release: release), maxEntries: 8, maxBytes: 100) let empty = try index()- let retirement = Task.detached {+ let retirement = Task.detached(priority: .userInitiated) { try domain.retire(storeID: store, expectedVersion: 0, replacementIndex: empty) } #expect(wait(started) == .success)- let gate = Task.detached { domain.withLock { 42 } }+ let gate = Task.detached(priority: .userInitiated) { domain.withLock { 42 } } #expect(await gate.value == 42) release.signal() try await retirement.value
diff --git a/Transit/TransitTests/MCPReadPublicationExpiryTests.swift b/Transit/TransitTests/MCPReadPublicationExpiryTests.swiftnew file mode 100644index 00000000..82527677--- /dev/null+++ b/Transit/TransitTests/MCPReadPublicationExpiryTests.swift@@ -0,0 +1,111 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++/// Common gate proof with real store reservations; owner helper implementation remains separate acceptance.+@MainActor @Suite(.serialized)+struct MCPReadPublicationExpiryTests {+ private let snapshotID = "11111111-1111-4111-8111-111111111111"+ private let reusableCursor = "22222222-2222-8222-8222-222222222222"++ @Test(arguments: 0..<6)+ func expiredPublicationSelectsFamilyErrorAndDiscardsCandidate(mode: Int) async throws {+ let request = request(mode: mode)+ let id = JSONRPCId.string("expiry-\"\\-\(mode)")+ let busy = Data("busy-sentinel".utf8)+ let errors = try MCPBoundedReadDispatcher.publicationErrors(for: request, id: id, busy: busy)+ #expect(errors.busy == busy)+ #expect(try errorCode(errors.capacity) == "QUERY_CAPACITY_EXCEEDED")+ let start = ContinuousClock.now+ let expiry = start + .seconds(300)+ let domain = MCPReadPublicationDomain(testingInstant: start)+ let coordinator = MCPReadCoordinator(domain: domain)+ let prepared = try candidate(mode: mode, domain: domain, start: start)+ let publication = prepared.publication+ let storeID = publication.publicationStoreID+ let before = try domain.accounting(for: storeID)+ #expect(before.visibleEntries == 0 && before.visibleBytes == 0)+ #expect(before.pendingEntries == 1 && before.pendingBytes > 0)+ let bytes = await coordinator.execute(timeout: Data("timeout".utf8), busy: busy) { _ in+ domain.setTestingInstant(expiry)+ return PreparedReadResult(encodedResponse: Data("unpublished-success".utf8),+ publications: [publication], publicationErrors: errors)+ }+ let drainDeadline = ContinuousClock.now + .seconds(1)+ while coordinator.unfinishedCount != 0 && .now < drainDeadline { await Task.yield() }+ #expect(coordinator.unfinishedCount == 0)+ let after = try domain.accounting(for: storeID)+ #expect(after.visibleEntries == 0 && after.visibleBytes == 0)+ #expect(after.pendingEntries == 0 && after.pendingBytes == 0)+ let frame = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any])+ #expect(frame["id"] as? String == "expiry-\"\\-\(mode)")+ let result = try #require(frame["result"] as? [String: Any])+ #expect(result["isError"] as? Bool == true)+ #expect(result["_meta"] == nil)+ let expected = mode == 0 ? "QUERY_EXPIRED" : (mode == 2 || mode == 5 ? "INVALID_CURSOR" : "INVALID_SNAPSHOT")+ #expect(try errorCode(bytes) == expected)+ // Store ownership stays alive through final accounting and outside-lock retirement.+ withExtendedLifetime(prepared.store) {}+ }++ private func request(mode: Int) -> MCPReadToolRequest {+ let tool = mode < 3 ? "query_tasks" : "query_project_summaries"+ let arguments: [String: AnyCodable]+ switch mode {+ case 0: arguments = ["detailLevel": AnyCodable("summary"), "includeComments": AnyCodable(false),+ "limit": AnyCodable(1)]+ case 1: arguments = ["snapshotId": AnyCodable(snapshotID)]+ case 2, 5: arguments = ["cursor": AnyCodable(reusableCursor)]+ case 3: arguments = ["start": AnyCodable("2026-01-01T00:00:00Z"),+ "end": AnyCodable("2026-02-01T00:00:00Z"), "limit": AnyCodable(1)]+ default: arguments = ["snapshotId": AnyCodable(snapshotID)]+ }+ return MCPReadToolRequest(tool: tool, arguments: arguments)+ }++ private func candidate(mode: Int, domain: MCPReadPublicationDomain, start: ContinuousClock.Instant)+ throws -> Candidate {+ let expiry = start + .seconds(300)+ if mode == 0 {+ let store = MCPTaskQuerySnapshotStore(domain: domain)+ let candidate = try store.prepare(pages: ["first", "second"],+ cursors: [store.makeCursor()], deadline: expiry, operationID: UUID())+ let publication = try #require(candidate)+ return Candidate(store: store, publication: publication)+ }+ let store = try MCPReusableSnapshotStore(domain: domain)+ let metadata = ReadCaptureMetadata(asOf: "2026-01-01T00:00:00.000Z", snapshotId: snapshotID,+ freshness: ReadFreshness(syncState: .inactive, assessment: .notApplicable,+ assessedAt: "2026-01-01T00:00:00.000Z", lastImportedAt: nil, evidence: .none,+ recentImportThresholdMs: 60_000),+ read: ReadExecutionMetadata(policy: .cached, refreshOutcome: .notRequested, budgetMs: 5_000))+ let view = CapturedReadView(completeness: .completePortfolio, captureScope: .wholePortfolio,+ metadata: metadata, createdAt: start, retentionDeadline: expiry,+ projects: [], tasks: [], milestones: [], comments: [])+ let window = CompletionWindow(start: Date(timeIntervalSince1970: 0), end: Date(timeIntervalSince1970: 1))+ let frozenMetadata = try JSONEncoder().encode(metadata)+ let root = RetainedView(capture: view, frozenMetadataBytes: frozenMetadata,+ window: window, initialRequest: .initial(window: window, limit: 1, project: nil, policy: .cached),+ firstPage: Data("first".utf8))+ let reservation = try store.reserveCreate(bundle: EncodedViewBundle(root: root,+ pages: [Data("next".utf8)], cursors: [reusableCursor],+ encodedCaptureByteCount: frozenMetadata.count), publicationDeadline: expiry + .seconds(1))+ // The domain clock expires the retained root while the reservation deadline remains live.+ #expect(reservation.publication.deadline > expiry)+ return Candidate(store: store, publication: try store.prepare(reservation: reservation))+ }++ private func errorCode(_ bytes: Data) throws -> String {+ let frame = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any])+ let payload = try MCPTestHelpers.decodeHTTPToolResult(frame)+ let error = try #require(payload["error"] as? [String: Any])+ return try #require(error["code"] as? String)+ }++ private struct Candidate {+ let store: AnyObject+ let publication: any MCPPreparedPublication+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadPublicationFailureTests.swift b/Transit/TransitTests/MCPReadPublicationFailureTests.swiftindex 9e1c28e5..7d7dcf72 100644--- a/Transit/TransitTests/MCPReadPublicationFailureTests.swift+++ b/Transit/TransitTests/MCPReadPublicationFailureTests.swift@@ -8,7 +8,9 @@ import Testing struct MCPReadPublicationFailureTests { nonisolated private enum EncodingFailure: Error { case injected } - @Test func outerEncodingFailureDiscardsActualPrivateOrdinaryCandidate() async throws {+ @Test(arguments: [false, true])+ // swiftlint:disable:next function_body_length+ func outerEncodingFailureDiscardsActualPrivateOrdinaryCandidate(operationAware: Bool) async throws { let fixture = try TestModelContainer() let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue") fixture.context.insert(project)@@ -31,13 +33,29 @@ struct MCPReadPublicationFailureTests { let read = try #require(MCPBoundedReadDispatcher.classify(rpc)) let domain = store.domain let storeID = store.publicationStoreID+ let failingEncoder: @Sendable (MCPPreparedToolRead, JSONRPCId) throws -> Data = { tool, id in+ #expect(id == rpc.id)+ #expect(tool.publications.count == 1)+ let privateState = try domain.accounting(for: storeID)+ #expect(privateState.visibleEntries == 0 && privateState.pendingEntries == 1)+ #expect(privateState.pendingBytes > 0)+ throw EncodingFailure.injected+ }+ let operationEncoder: (@Sendable (MCPPreparedToolRead, JSONRPCId, MCPReadOperation) throws -> Data)?+ if operationAware {+ operationEncoder = { tool, id, operation in+ #expect(operation.shouldContinue())+ return try failingEncoder(tool, id)+ }+ } else { operationEncoder = nil } let bytes = try await MCPBoundedReadDispatcher.response(for: read, rpc: rpc, handler: handler,- coordinator: handler.readCoordinator, admittedAt: .now, encode: { tool, _ in- #expect(tool.publications.count == 1)- let privateState = try domain.accounting(for: storeID)- #expect(privateState.visibleEntries == 0 && privateState.pendingEntries == 1)- #expect(privateState.pendingBytes > 0)- throw EncodingFailure.injected+ coordinator: handler.readCoordinator, admittedAt: .now, encode: { tool, id in+ #expect(!operationAware, "Operation-aware encoding must supersede the normal encoder")+ return try failingEncoder(tool, id)+ }, encodeWithOperation: operationEncoder, encodeConstantToolFailure: { tool, id in+ #expect(id == rpc.id)+ #expect(tool.publications.isEmpty && tool.result.isError == true)+ return try MCPBoundedReadDispatcher.encodeResult(tool, id: id) }) let deadline = ContinuousClock.now + .seconds(1) while handler.readCoordinator.unfinishedCount != 0 && .now < deadline { await Task.yield() }@@ -45,7 +63,8 @@ struct MCPReadPublicationFailureTests { let after = try domain.accounting(for: storeID) #expect(after.visibleEntries == 0 && after.visibleBytes == 0) #expect(after.pendingEntries == 0 && after.pendingBytes == 0)- let response = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any])+ let decoded = try JSONSerialization.jsonObject(with: bytes)+ let response = try #require(decoded as? [String: Any]) #expect(response["id"] as? String == "outer-encoding-\"\\failure") let tool = try #require(response["result"] as? [String: Any]) let metadata = try #require((tool["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any])@@ -54,5 +73,123 @@ struct MCPReadPublicationFailureTests { #expect(try MCPTestHelpers.decodeHTTPToolResult(response)["error"] as? [String: String] == ["code": "QUERY_FAILED", "message": "QUERY_FAILED"]) }++ @Test(arguments: [false, true])+ func normalEncoderReturnsFullBytesWithOriginalIdentity(operationAware: Bool) async throws {+ let owner = try TestModelContainer()+ let (handler, store) = try makeHandler(owner)+ let rpc = request(arguments: [:])+ let read = try #require(MCPBoundedReadDispatcher.classify(rpc))+ let id = try #require(rpc.id)+ let encoder: @Sendable (MCPPreparedToolRead, JSONRPCId) throws -> Data = { tool, receivedID in+ #expect(receivedID == id)+ #expect(tool.frozenMetadataBytes != nil)+ var bytes = try MCPBoundedReadDispatcher.encodeResult(tool, id: receivedID)+ bytes.append(Data("\n".utf8))+ return bytes+ }+ let operationEncoder: (@Sendable (MCPPreparedToolRead, JSONRPCId, MCPReadOperation) throws -> Data)?+ if operationAware {+ operationEncoder = { tool, receivedID, operation in+ #expect(operation.shouldContinue())+ return try encoder(tool, receivedID)+ }+ } else { operationEncoder = nil }+ let bytes = try await MCPBoundedReadDispatcher.response(for: read, rpc: rpc, handler: handler,+ coordinator: handler.readCoordinator, admittedAt: .now, encode: { tool, receivedID in+ #expect(!operationAware)+ return try encoder(tool, receivedID)+ }, encodeWithOperation: operationEncoder)+ await drain(handler.readCoordinator)+ #expect(bytes.last == 10, "The exact full response bytes from the selected encoder must survive")+ let decoded = try JSONSerialization.jsonObject(with: bytes)+ let frame = try #require(decoded as? [String: Any])+ #expect(frame["id"] as? String == "encoder-hook")+ let tool = try #require(frame["result"] as? [String: Any])+ #expect(tool["_meta"] != nil)+ #expect(try store.domain.accounting(for: store.publicationStoreID).pendingEntries == 0)+ withExtendedLifetime(owner) {}+ }++ @Test func constantEncoderFailurePreventsCaptureAndAdmission() async throws {+ let owner = try TestModelContainer()+ let source = MCPReadHookCaptureProbe(owner: owner)+ let (handler, store) = try makeHandler(owner, source: source)+ let rpc = request(arguments: [:])+ let read = try #require(MCPBoundedReadDispatcher.classify(rpc))+ do {+ _ = try await MCPBoundedReadDispatcher.response(for: read, rpc: rpc, handler: handler,+ coordinator: handler.readCoordinator, admittedAt: .now, encode: { _, _ in+ Issue.record("Normal encoder ran after constant preparation failed")+ return Data()+ }, encodeConstantToolFailure: { _, id in+ #expect(id == rpc.id)+ throw EncodingFailure.injected+ })+ Issue.record("Constant encoder failure did not propagate before admission")+ } catch EncodingFailure.injected { } catch { Issue.record("Unexpected error: \(error)") }+ #expect(handler.readCoordinator.unfinishedCount == 0 && source.calls == 0)+ let state = try store.domain.accounting(for: store.publicationStoreID)+ #expect(state.pendingEntries == 0 && state.visibleEntries == 0)+ withExtendedLifetime(owner) {}+ }++ @Test func malformedArgumentsKeepSeparateProtocolFailure() async throws {+ let owner = try TestModelContainer()+ let (handler, _) = try makeHandler(owner)+ let rpc = request(arguments: "malformed")+ let read = try #require(MCPBoundedReadDispatcher.classify(rpc))+ let bytes = try await MCPBoundedReadDispatcher.response(for: read, rpc: rpc, handler: handler,+ coordinator: handler.readCoordinator, admittedAt: .now, encodeWithOperation: { _, _, _ in+ Issue.record("Malformed protocol parameters reached normal tool encoding")+ return Data()+ }, encodeConstantToolFailure: { tool, id in+ #expect(tool.result.isError == true)+ return try MCPBoundedReadDispatcher.encodeResult(tool, id: id)+ })+ await drain(handler.readCoordinator)+ let decoded = try JSONSerialization.jsonObject(with: bytes)+ let frame = try #require(decoded as? [String: Any])+ #expect(frame["id"] as? String == "encoder-hook" && frame["result"] == nil)+ #expect((frame["error"] as? [String: Any])?["code"] as? Int == JSONRPCErrorCode.invalidParams)+ withExtendedLifetime(owner) {}+ }++ private func request(arguments: Any) -> JSONRPCRequest {+ JSONRPCRequest(jsonrpc: "2.0", id: .string("encoder-hook"), method: "tools/call",+ params: AnyCodable(["name": "get_projects", "arguments": arguments]))+ }++ private func makeHandler(_ owner: TestModelContainer, source: (any MCPReadCaptureSource)? = nil) throws+ -> (MCPToolHandler, MCPTaskQuerySnapshotStore) {+ let env = try MCPTestHelpers.makeEnv()+ let store = MCPTaskQuerySnapshotStore()+ let service = MCPReadService(source: source ?? MCPReadCaptureBuilder(container: owner.container,+ fence: .actorOnlyTestFixture), monitor: MCPImportEvidenceMonitor(syncActive: false,+ storeIdentifier: nil), snapshots: store)+ let handler = MCPToolHandler(taskService: env.taskService, projectService: env.projectService,+ commentService: env.commentService, milestoneService: env.milestoneService,+ maintenanceService: env.maintenanceService, settings: env.mcpSettings, readService: service)+ return (handler, store)+ }++ private func drain(_ coordinator: MCPReadCoordinator) async {+ let deadline = ContinuousClock.now + .seconds(1)+ while coordinator.unfinishedCount != 0 && .now < deadline { await Task.yield() }+ #expect(coordinator.unfinishedCount == 0)+ }++}++@MainActor private final class MCPReadHookCaptureProbe: MCPReadCaptureSource {+ let builder: MCPReadCaptureBuilder+ var calls = 0+ init(owner: TestModelContainer) {+ builder = MCPReadCaptureBuilder(container: owner.container, fence: .actorOnlyTestFixture)+ }+ func capture(_ request: ReadCaptureRequest) throws -> CapturedReadView {+ calls += 1+ return try builder.capture(request)+ } } #endif
diff --git a/Transit/TransitTests/MCPReadServerPreservationTests.swift b/Transit/TransitTests/MCPReadServerPreservationTests.swiftindex 69bf3043..ea08c020 100644--- a/Transit/TransitTests/MCPReadServerPreservationTests.swift+++ b/Transit/TransitTests/MCPReadServerPreservationTests.swift@@ -1,5 +1,6 @@ #if os(macOS) import Foundation+import HTTPTypes import SwiftData import Testing @testable import Transit@@ -12,7 +13,8 @@ struct MCPReadServerPreservationTests { let env = try MCPTestHelpers.makeEnv() let server = MCPServer(toolHandler: env.handler) await server.stop()- let response = try await call(env.handler, tool: tool, args: [:])+ let response = try await call(env.handler, tool: tool, args: tool == "query_tasks"+ ? ["detailLevel": "summary", "includeComments": false, "limit": 1] : [:]) let result = try #require(response["result"] as? [String: Any]) let meta = try #require((result["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any]) #expect(meta["category"] as? String == "READ_BUSY")@@ -102,11 +104,16 @@ struct MCPReadServerPreservationTests { private func call(_ handler: MCPToolHandler, tool: String, args: [String: Any]) async throws -> [String: Any] { let envelope: [String: Any] = ["jsonrpc": "2.0", "id": "preservation-id", "method": "tools/call",- "params": ["name": tool, "arguments": args]]+ "params": ["name": tool, "arguments": args, "_meta": [+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",+ "io.modelcontextprotocol/clientCapabilities": [:] as [String: Any]]]] let data = try JSONSerialization.data(withJSONObject: envelope) let response = try await MCPTestHelpers.respond(handler: handler, contentType: "application/json", accept: "application/json", protocolVersion: "2026-07-28",- body: try #require(String(data: data, encoding: .utf8)), loggerLabel: "read-server-preservation")+ orderedHeaders: [+ HTTPField(name: HTTPField.Name("Mcp-Method")!, value: "tools/call"),+ HTTPField(name: HTTPField.Name("Mcp-Name")!, value: tool)+ ], body: try #require(String(data: data, encoding: .utf8)), loggerLabel: "read-server-preservation") let object = try #require(response.json as? [String: Any]) #expect(object["id"] as? String == "preservation-id") #expect(object["jsonrpc"] as? String == "2.0")
diff --git a/Transit/TransitTests/MCPTaskQueryRequestTests.swift b/Transit/TransitTests/MCPTaskQueryRequestTests.swiftindex 9a127295..406167fa 100644--- a/Transit/TransitTests/MCPTaskQueryRequestTests.swift+++ b/Transit/TransitTests/MCPTaskQueryRequestTests.swift@@ -73,10 +73,22 @@ struct MCPTaskQueryRequestTests { let data = try JSONEncoder().encode(MCPToolDefinitions.queryTasks.inputSchema) let schema = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) let branches = try #require(schema["oneOf"] as? [[String: Any]])- #expect(branches.count == 2)+ #expect(branches.count == 3) #expect(branches.allSatisfy { $0["additionalProperties"] as? Bool == false }) #expect(branches[0]["required"] as? [String] == ["detailLevel", "includeComments", "limit"]) #expect(branches[1]["required"] as? [String] == ["cursor"])+ #expect(branches[2]["required"] as? [String] == ["snapshotId", "detailLevel", "includeComments", "limit"])+ let ordinary = try #require(branches[0]["properties"] as? [String: Any])+ let continuation = try #require(branches[1]["properties"] as? [String: Any])+ let snapshot = try #require(branches[2]["properties"] as? [String: Any])+ #expect(ordinary["cursor"] == nil && ordinary["snapshotId"] == nil)+ #expect(ordinary["detailLevel"] != nil && ordinary["includeComments"] != nil+ && ordinary["limit"] != nil)+ #expect(Set(continuation.keys) == Set(["cursor", "readPolicy"]))+ #expect(Set(snapshot.keys) == Set([+ "snapshotId", "detailLevel", "includeComments", "limit", "projectId", "status"+ ]))+ #expect((snapshot["includeComments"] as? [String: Any])?["const"] as? Bool == false) } } #endif
diff --git a/Transit/TransitTests/MCPToolHandlerTests.swift b/Transit/TransitTests/MCPToolHandlerTests.swiftindex b34360ba..a5968949 100644--- a/Transit/TransitTests/MCPToolHandlerTests.swift+++ b/Transit/TransitTests/MCPToolHandlerTests.swift@@ -43,8 +43,11 @@ struct MCPToolHandlerTests { let result = try #require(json["result"] as? [String: Any]) let tools = try #require(result["tools"] as? [[String: Any]]) - #expect(tools.count == 11)+ #expect(tools.count == 12) let names = tools.compactMap { $0["name"] as? String }+ #expect(Set(names) == Set(["create_task", "update_task_status", "query_tasks", "update_task", "add_comment",+ "get_projects", "create_project", "create_milestone", "query_milestones", "update_milestone",+ "delete_milestone", "query_project_summaries"])) #expect(names.contains("create_task")) #expect(names.contains("update_task_status")) #expect(names.contains("query_tasks"))
diff --git a/specs/bounded-read-freshness/modern-transfer-manifest.json b/specs/bounded-read-freshness/modern-transfer-manifest.jsonnew file mode 100644index 00000000..6fb98808--- /dev/null+++ b/specs/bounded-read-freshness/modern-transfer-manifest.json@@ -0,0 +1,183 @@+{+ "status": "prepared_not_transferred",+ "source_test_base": "b1f30256b4fb33270809188131d047a29807f162",+ "production_base": "90daf448f0e5c6ae14749bb575bcd4ba77e6e16e",+ "tested_owner_source": "b4c104e76a482562bc8eae2ae9f54a6e5712ffc5",+ "production_equivalence_files": 64,+ "production_deltas": [],+ "owner_router_counts": {+ "passed": 4,+ "failed": 0,+ "skipped": 0,+ "exit_code": 0,+ "drained": true+ },+ "local_router_runtime_green_claimed": false,+ "fixture_dependency_matches": 3,+ "fixture_dependency_total": 4,+ "fixture_delta": "MCPHTTPTestHelpers.swift: nonisolated respond, optional protocolVersion header, Sendable response; preserve current helper",+ "candidate_production_transfer": [+ {+ "path": "Transit/Transit/MCP/MCPServer.swift",+ "sha256": "204b78bc0d3d49a41b9b6ce422cd367b0e1b4d02f613cd7266946021c276ec11",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPServer+Routing.swift",+ "sha256": "a61923728971c1d1bf8c687884ea7e46213ad8d64e167c3ffb90f95ae00b2dde",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPServer+Responses.swift",+ "sha256": "c1da3a62420439cb6b7007a8871ff9ad2f45f4c06cabf4e7c7933a981b0e8bfb",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPServer+ToolListNotifications.swift",+ "sha256": "0a6ea616cb23d54f325f1ab82c7338ea46e8c6ae303dd5f7b65f1120ae25e3cc",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPServerDecodeTypes.swift",+ "sha256": "7d8243ee4e14ec1d4e8c4b7af5c29691ac3af9c592950fb43e696ba323d0edab",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPServerLifecycleConfiguration.swift",+ "sha256": "6cc4fddb83d78e9c6e86eb54ee074a7ba35f2473337212b7e017c50bb5057d86",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolListChangeBroadcaster.swift",+ "sha256": "8afa54367af4ded22a43acaca5f4692882d37511030a5d1430c4fe0c39dd4f66",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPTypes.swift",+ "sha256": "ed9a44ffb38bcbe98a37cc742a52850ecab3ab9334f395e2a70a30a1423e7f06",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler.swift",+ "sha256": "0749918c933b89f3e2aa4e1757bfd5243584ca1f559af54d7ac76cbc701581e2",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift",+ "sha256": "f46e9ca6386c3d7740654ac7d38ddb82a33c8dcde4a17ec569727ad3413ceb16",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ }+ ],+ "optional_separately_authorized_transport_fixture_transfer": [+ {+ "path": "Transit/TransitTests/MCPServerRouteTests.swift",+ "sha256": "dec881e0639a6aa982bcc2278af9b4d7fbaee32b42cd5d29f133b3be2ab1385b",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/TransitTests/MCPServerBatchRequestTests.swift",+ "sha256": "7829d17fd5cc64847ad99bc35cf9c800311fa62bb433a1c77acddc8acc47c3b6",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/TransitTests/MCPNotificationDispatchTests.swift",+ "sha256": "f76bf880acf144bbb72532640932d796ee8884f34bba5b808931073e74b3cb35",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/TransitTests/MCPToolListChangeNotificationTests.swift",+ "sha256": "ad451dda60e897143490a180e29654b2f560b2c76895c7e7e929f1bd1b8e9ab6",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/TransitTests/MCPServerOriginValidationTests.swift",+ "sha256": "bc6707ddde5869a796946e7703e4a30aee68239bc9aa034ae991876888202a89",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/TransitTests/MCPServerLifecycleTests.swift",+ "sha256": "dd2930d0dd5957ea30d3a507283e9987e5560be9679b57c6119db8d99b9525c5",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/TransitTests/MCPServerStartFailureTests.swift",+ "sha256": "19aaa3f72882cf85fadc2b33e70a1e7a6d559f5fea9fe2ca915eedd20abe39f8",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ }+ ],+ "retained_owners": {+ "T63": [+ "Transit/Transit/MCP/Reads/",+ "Transit/Transit/MCP/MCPTaskQuerySnapshotStore.swift",+ "Transit/Transit/MCP/MCPToolHandler+CapturedRead.swift",+ "Transit/Transit/MCP/MCPToolHandler+PortfolioReadPreparation.swift",+ "Transit/Transit/MCP/MCPToolDefinitions.swift",+ "Transit/TransitTests/MCPHTTPTestHelpers.swift",+ "Transit/TransitTests/MCPTestHelpers.swift",+ "read-specific tests"+ ],+ "T2382": [+ "portfolio/reusable source modules",+ "portfolio-owned tests"+ ],+ "T2384": [+ "MCP/Writes/MCPWriteCoordinator.swift",+ "write-specific tests"+ ],+ "containment_build_owner": [+ "App/project/signing/isolation/Makefile"+ ]+ },+ "entry_prerequisites": [+ "explicit parent record naming base and exact paths",+ "clean immutable source base and matching hashes",+ "old owner stops edits on transferred paths"+ ],+ "not_entry_prerequisites": [+ "T63 diagnostics and caller descriptions",+ "full platform checks",+ "pre-push review/Pulsar",+ "unrelated typed-link schema work",+ "duplicate legacy fixture rerun for bookkeeping"+ ],+ "post_transfer_acceptance_obligations": [+ "real fragment/schema ABI and owner-applied read/ordinary/reusable bindings",+ "complete actual-ID encoded bytes before publication; exact frozen metadata and retention accounting",+ "modern single-object POST and wire-array rejection",+ "portfolio request-header alignment and source/presentation/opaque-metadata assertions",+ "current HTTP-helper focused router verification with modern adapter",+ "include two verified owner router-expiry fixtures with current helper and modern adapter"+ ],+ "authorizes_heavy_run": false,+ "authorizes_live_operations": false,+ "owner_fixture_handoff_checkpoint": "040da36",+ "independent_modern_workflow_gate": "T2383 required RED/GREEN and execution permission; no bypass authorized",+ "verified_owner_router_expiry": {+ "revision": "ee053269",+ "passed": 2,+ "failed": 0,+ "normal_exit": true,+ "drained": true,+ "imported": false,+ "local_runtime_green_claimed": false+ },+ "external_stage_b_verified_cases": 6,+ "external_stage_b_combined_run_claimed": false+}
diff --git a/specs/bounded-read-freshness/owner-patches/modern-tool-definitions.patch b/specs/bounded-read-freshness/owner-patches/modern-tool-definitions.patchnew file mode 100644index 00000000..3b5e8538--- /dev/null+++ b/specs/bounded-read-freshness/owner-patches/modern-tool-definitions.patch@@ -0,0 +1,27 @@+--- a/Transit/Transit/MCP/MCPToolDefinitions.swift++++ b/Transit/Transit/MCP/MCPToolDefinitions.swift+@@ -1,4 +1,5 @@+ #if os(macOS)++import Foundation+ + // MARK: - Tool Definitions+ +@@ -20,6 +21,18 @@+ + static func tools(includingMaintenance: Bool) -> [MCPToolDefinition] {+ includingMaintenance ? coreTools + maintenanceTools : coreTools++ }++++ /// Uses the same selected definitions without altering their public input contracts.++ static func modernTools(includingMaintenance: Bool) throws -> [MCPModernToolDescriptor] {++ try tools(includingMaintenance: includingMaintenance).map { definition in++ MCPModernToolDescriptor(++ name: definition.name,++ description: definition.description,++ inputSchema: try MCPJSONDocument.parse(JSONEncoder().encode(definition.inputSchema)),++ resultSchema: try MCPResultSchemas.descriptor(++ tool: definition.name, description: definition.description))++ }+ }+ + /// Names of tools gated behind `MCPSettings.maintenanceToolsEnabled`,
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 73c1a6df..567151ec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +- 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. - T-2377: MCP `create_project` accepts a required name and six-digit colour, validates optional description/repository fields and case-insensitive name uniqueness, persists through `ProjectService`, and returns project ID and metadata for subsequent task creation. Regression tests cover discovery, validation, storage failures, fallback write rejection, and project-to-task creation.@@ -58,6 +59,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - T-1803: `UpdateStatusIntent` now includes a missing requested `displayId` in its `TASK_NOT_FOUND` hint (`No task with displayId N`), while missing UUIDs retain the existing generic lookup hint and malformed identifiers, duplicate IDs, status validation, and atomic mutation behavior remain unchanged. ### Fixed +- T-63: Align detached publication-test producers with their user-initiated semaphore waiters, eliminating observed fixture priority-inversion warnings while preserving publication, cleanup and timing assertions. - T-2380: Reuse validated guard bindings only within synchronous write phases, revalidate after suspension, and discard snapshots on mutation failure. Document safe recovery without deleting uncertain bindings or resetting local scope. - T-2380: Reconcile retry guards in one validated pass, reject incomplete saved outcomes before replay, and preserve exact integer validation. Added malformed-result regressions and corrected MCP safety examples. - T-2103: Task and milestone creation now revalidate the selected project after asynchronous display-ID allocation using live pending state plus a fresh committed-state probe. A peer deletion now returns the established project-not-found error before insertion instead of persisting an orphan task or reporting false milestone success; App Intent and MCP callers retain their deterministic project-not-found contracts, with two-context service and MCP regressions covering the race.
diff --git a/README.md b/README.mdindex f5e19728..fd1c7ed0 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. 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. Actual installed-client compatibility is deferred to post-merge MacBook validation and remains unverified. App Intent inputs are unchanged. ## Documentation
diff --git a/docs/mcp-read-contract.md b/docs/mcp-read-contract.mdnew file mode 100644index 00000000..2cde15a0--- /dev/null+++ b/docs/mcp-read-contract.md@@ -0,0 +1,85 @@+# MCP bounded reads and freshness++Covered macOS reads describe a completed capture of **saved local data**. A capture timestamp or recent import is not proof that every remote edit has arrived. Use the current advertised tool schema and the [modern transport/result contract](mcp-result-contract.md) for request metadata, headers and structured results.++The server allows five seconds from the read's original admission through complete response preparation. Import observation, store capture, transformation and encoding share that budget. An internal 4,850 ms selection cutoff reserves time for response completion. Client/network delivery time is outside this server budget. Eight unfinished physical reads are admitted per process; listener restart does not reset that count. A timeout ends delivery, while its physical work retains capacity until cleanup.++## Policy and import limits++New reads default to `readPolicy: "refresh_if_needed"`. This can observe positively applicable imports already in flight for at most two seconds within the remaining total budget. The current SwiftData integration has no supported force-pull or provable import-to-capture visibility mechanism; it reports `unavailable` refresh and honest `unknown` freshness when applicability cannot be established. Heartbeat writes and notification arrival are not import proof.++`readPolicy: "cached"` skips import waiting and reports `not_requested`. It still creates a new saved local capture. Inactive sync skips waiting under either policy and reports `syncState: "inactive"`, `assessment: "not_applicable"`, and `lastImportedAt: null`. A failed or unavailable refresh can accompany a successful complete local read. A refresh wait timing out is distinct from the entire read returning `READ_TIMEOUT`.++## Capture metadata++Read metadata is outside `structuredContent`, at `result._meta["me.nore.ig.transit/read"]`. A successful capture has:++```json+{+ "asOf": "2026-10-03T15:00:00.000Z",+ "snapshotId": "opaque-capture-id",+ "freshness": {+ "syncState": "active",+ "assessment": "unknown",+ "assessedAt": "2026-10-03T15:00:00.000Z",+ "lastImportedAt": null,+ "evidence": "none",+ "recentImportThresholdMs": 30000+ },+ "read": {+ "policy": "refresh_if_needed",+ "refreshOutcome": "unavailable",+ "budgetMs": 5000+ }+}+```++`asOf` is the completed local capture time, in UTC with millisecond precision; `assessedAt` is fixed to that same time. `snapshotId` is opaque. `recent_import` means a positively relevant successful import was visible to the selected capture within 30,000 ms; `stale` means older known evidence; `unknown` means absent, unreliable or unprovable evidence. `completed_import` is the evidence value for a proven relevant import; otherwise it is `none`. Later failed imports do not erase a valid prior success timestamp. None of these values promise global freshness.++Refresh outcomes are `not_requested`, `recent_import`, `import_observed`, `failed`, `timeout`, and `unavailable`. Successful empty selections still carry capture metadata. Failed required fetches and incoherent captures are errors, not empty success.++## New captures and frozen replay++These are **tool argument objects**, to be placed inside a valid modern `tools/call` request:++```json+{"detailLevel":"summary","includeComments":false,"limit":1}+```++A second initial `query_tasks` call creates a new capture, even with the same arguments. To skip import observation explicitly:++```json+{"detailLevel":"summary","includeComments":false,"limit":1,"readPolicy":"cached"}+```++To continue a returned ordinary page:++```json+{"cursor":"the-returned-nextCursor"}+```++Continuation reuses the original records, complete metadata bytes and expiry. It does not recapture, wait for an import, extend retention or update freshness. An optional continuation policy must match the retained policy; malformed policy is rejected before lookup. A new request has its own diagnostic correlation even when capture metadata is reused. Ordinary pages retain their five-minute/eight-snapshot/16-MiB limits. Reusable portfolio views have their separately advertised scope and retention contract; a shared capture retains the same identity and freshness evidence.++A cursor retry requests the same frozen capture. If a caller needs newer data, start a new initial query. Expired/unavailable cursors require a new query; incompatible snapshot scope requires a compatible selector/view rather than treating an incomplete view as complete.++## Errors and retries++Read failures set the original `isError` and preserve their error payload. Metadata contains request correlation, category and policy/budget, without invented successful `asOf` or `snapshotId`. The structured presentation also reports its supplemental category.++| Failure | Tool error code | Read metadata category | Structured presentation category |+| --- | --- | --- | --- |+| Required storage failure | `QUERY_FAILED` for query_tasks; `READ_FAILED` for get_projects/query_milestones | `storage_failure` | `storage_failure` |+| Required serialization failure | Same tool mapping | `serialization_failure` | `serialization_failure` |+| Capture cannot be proved coherent | Same tool mapping | `incoherent_capture` | `incoherent_capture` |+| Total read deadline | `READ_TIMEOUT` | `READ_TIMEOUT` | `deadline_exceeded` |+| Admission/publication busy | `READ_BUSY` | `READ_BUSY` | `admission_busy` |++Input, selector, cursor and capacity errors retain their specific advertised codes and precedence. Successful local reads with stale/unknown freshness are not storage failures.++There is no automatic retry. After `READ_BUSY` or `READ_TIMEOUT`, apply backoff before a bounded explicit retry; an immediate retry can still encounter unfinished physical work. Set a maximum attempt count appropriate to the caller and stop/report failure after that limit. Correct invalid input rather than repeating it. Reduce scope/comments or wait for retention expiry on capacity errors. Never retry a protected write as a fresh read or discard its existing receipt/revision safety requirements.++## Diagnostics and validation++The bounded diagnostic sink emits measured queue, refresh, capture, transform and serialization intervals, terminal outcomes and physical finish/discard with the original operation correlation and deadline. Historical aggregate tests also measure aggregation; production rejects JSON-RPC wire arrays. Excess log records are dropped rather than delaying a timeout. Use these measurements to investigate slow stages; unexplained delay must not be attributed to CloudKit.++Executable caller tests cover initial capture versus frozen replay, active/inactive policy defaults, failure followed by explicit retry, backoff while physical capacity is retained, and advertised guidance. Fault tests cover catalog storage/serialization/incoherence codes and metadata. See the [bounded-read spec](../specs/bounded-read-freshness/requirements.md) and its acceptance handoffs for exact source pins and supported/unsupported platform evidence.
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex f9f33b06..58fc12c9 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -37,7 +37,7 @@ | [Batch Task Queries](#batch-task-queries) | 2026-10-03 | Done | MCP task detail selection, batch lookup, and frozen cursor pagination | | [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 | In Progress | Bound MCP read completion and report immutable saved capture/import evidence |+| [Bounded Read Freshness](#bounded-read-freshness) | 2026-10-03 | Done | Bound MCP read completion and report immutable saved capture/import evidence | --- @@ -391,13 +391,24 @@ Immutable source/presentation results, supported-link availability and modern-on ## Bounded Read Freshness -**Created:** 2026-10-03 · **Status:** In Progress+**Created:** 2026-10-03 · **Status:** Done T-63 bounds MCP reads with saved-only coherent capture, explicit import evidence, independent deadlines and frozen pagination metadata. Shared capture/publication contracts support T2382 reusable portfolio views. +All implementation tasks and native validation are complete. The remaining unique tests/docs proceed through PR review on merged main with explicit publication/disclosure approval.+ - [Requirements](bounded-read-freshness/requirements.md) - [Design](bounded-read-freshness/design.md) - [Tasks](bounded-read-freshness/tasks.md) - [Decisions](bounded-read-freshness/decision_log.md) - [Task review](bounded-read-freshness/tasks-review.md) - [Foundation handoff](bounded-read-freshness/foundation-handoff.md)+- [Tasks12/13 acceptance and diagnostics readiness](bounded-read-freshness/task13-acceptance.md)+- [Task14 diagnostics RED handoff](bounded-read-freshness/task14-red-handoff.md)+- [Task15 source readiness and owner patches](bounded-read-freshness/task15-source-handoff.md)+- [Catalog READ_FAILED focused RED preparation and diagnostic import](bounded-read-freshness/catalog-read-failed-red-preparation.md)+- [Focused catalog RED evidence and fixture ports](bounded-read-freshness/catalog-read-failed-red-handoff.md) — historical six intended body failures; runtime result unfinalized; finalized GREEN recorded below.+- [Caller read contract](../docs/mcp-read-contract.md)+- [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)
diff --git a/specs/bounded-read-freshness/catalog-read-failed-red-handoff.md b/specs/bounded-read-freshness/catalog-read-failed-red-handoff.mdnew file mode 100644index 00000000..7c541b8a--- /dev/null+++ b/specs/bounded-read-freshness/catalog-read-failed-red-handoff.md@@ -0,0 +1,45 @@+# Focused catalog READ_FAILED RED and fixture-port handoff++Current acceptance: all six catalog fault cases and thirteen original diagnostics/caller bodies finalized GREEN at integrated b8c8194. See [task15-green-acceptance.md](task15-green-acceptance.md). The chronological RED/source handoffs below retain their original limitations.++Tested HEAD: `63d8dac9f7e76f2469b48895b7df1d7a54def1fd`, with approved test/production source `fc2096d6f1d7890fe6380300988740b2a6627cfd`. The HEAD delta consists only of documentation. No production change or GREEN patch was applied during the RED run.++## Actual focused RED++Xcode 27 build-for-testing, isolated development-host preflight and compiled enumeration passed. Enumeration enabled exactly one declaration, `MCPReadCatalogFailureTests.executionFaultKeepsMachineCodeAndFailureEvidence(tool:category:)`, expanding into six bodies: get_projects/query_milestones crossed with storage_failure/serialization_failure/incoherent_capture.++The console independently demonstrates all six bodies started and completed in 0.012 seconds. Each produced exactly the intended missing READ_FAILED machine-code assertion at line 74; there were six issues and no other observed assertion issues. Failure metadata, error flag, identity, policy, no successful snapshot/asOf, no publication and physical completion controls reached without observed issues. These are console observations, not finalized xcresult counts.++Runner finalization then stalled for more than 180 seconds. Exact owned runner and guarded host were sampled before scoped SIGTERM. Actual runtime exit was -15; the runtime xcresult lacks Info.plist and summary extraction exits 64. The cause remains unproved. Raw destination/AppIntents warnings are retained; no finalized runtime-warning, global-issue or skipped-test classification is claimed. Build exit and inventory exit were both zero.++The worker drained both owned runtime processes and released the heavy slot before extraction. An independent scoped process check also found all four recorded build/inventory/runner/host PIDs absent. No retry or GREEN was applied during that run. Parent accepted the meaningful six-body RED evidence with its finalization limitation and approved the narrow GREEN source repair. Runtime GREEN remains queued after the other workers; no heavy run is authorized by that source approval.++Evidence: `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/catalog-read-failed-red-fc2096d/manifest.json`; raw `catalog.log`, samples, cleanup receipts, extraction results and `root-postrun-review.json` are beside it. Root independently rehashed all 46 indexed artifacts and all 91 MCP plus 16 critical source entries against both disk and approved git objects.++## T2382 source-only fixture ports++Recipient pin: `a9ee19537c790b5d6103a54d0c8c70b17bdc6b5c`. Seven T63-owned fixtures are externally staged; no recipient worktree/index, production source or shared helper was changed. Their caller-local modern request metadata/headers, independent twelve/fourteen tool-name oracles, three query schema branches and coordinator async NIO cleanup preserve the original declarations and behavioral controls. One additional throwing-body test checks error preservation and bounded cleanup.++Packet: `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/t2382-owner-fixture-ports/handoff.md`. Combined patch SHA256: `b3823daf6b09835d65124efd6b3756244ed47234c2181736db1fffefc79dbe77`. Root independently verified all 21 indexed artifacts, seven recipient git-object prehashes, seven staged posthashes, and read-only application with whitespace errors rejected. Targeted lint/parse pass; no Swift typecheck or runtime acceptance is claimed. Actual focused selectors require compiled enumeration and parent slot coordination. The existing shared HTTP helper retains its EmbeddedChannel lifecycle; any observed diagnostics require a separately coordinated fix.++Parent assigned historical `Transit/TransitTests/MCPWriteLifecycleTests.swift` to T2383 for transport adaptation only; coordinator logic and test semantics retain T2384 consultation. Its modern notification/array migration, bounded accepted-cancellation rendezvous and unreached missingSafetyIsRejectedWithoutReservingAKey control are not changed by this packet.++Task15/Task16 remain incomplete. Original ten-declaration/thirteen-body diagnostics GREEN is still unexecuted. No full suite, iOS run, live preferences, installed-app activation, push, merge or deployment occurred.++## Approved source repair and integrated diagnostics review++Parent accepted this RED evidence with its finalization limitation. Narrow GREEN source is committed at `d2648f699a7ebb4426180ef3800f3f70fdf7c07d`: exactly MCPReadService.swift and MCPToolDefinitions+ReadGuidance.swift, matching the approved prospective posthashes. Only READ_FAILED of get_projects/query_milestones changes to JSON. Existing query_tasks errors, other text error declarations, metadata, error flag and original fixtures remain unchanged. Strict targeted lint, syntax parse and diff checks pass; runtime GREEN is unexecuted.++Root source review found no implementation blocker: nil provider sidecar follows the existing generatedJSON default, while readOutcome and the provider adapter preserve the metadata-derived semantic category. Root independently rehashed all five evidence artifacts, both source git objects/disk posthashes and four unchanged fixture paths. Read-only application against T2383 recipient 0071ca4 passes. The recipient component SHA256 is `f3c3fc31297e0a2527e803827bd398bb74438831a00cab821bdd5a95a734ed6f`; exact manifest and root review are in `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/catalog-read-failed-green-source/`.++T2383 integrated the earlier diagnostic production component at bd5c42a. Root verified all twelve owned files remain exact fa58dc0 posthashes at observed recipient 0071ca4 and both approved Handler/App constructor hunks are present. Evidence: `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/task15-source-preparation/diagnostics-recipient-integration-root-review.json`. This is source verification, not runtime acceptance or installed-app activation.++Acceptance still requires actual six-case modern JSON/source/category GREEN and the original ten-declaration/thirteen-body diagnostics controls under a parent-granted exclusive slot, with finalized evidence, retained diagnostics and physical drain. No runtime job runs while T2384 task9 is active. Seven fixture ports are relayed through parent for T2382 integration/focused verification; historical transport adaptation belongs to T2383 with coordinator logic/test semantics consulting T2384.++## T2382 recipient-specific source follow-up++T2382 integrated the seven fixture ports at 4b4ecf3571972aef139154a5c50b5504931970d3. Its service lacks the surrounding diagnostic refactor and guidance file, so importing the prior two-file component would fail. Root verified its entire prepareFailure function is byte-identical to the accepted fc2096d RED function (SHA256 b29c9db546d13496fccb5ac919a773b740c3eca3ca68c5659c433e6b9b7cd873). The recipient-specific MCPReadService.patch contains only the same approved two-catalog READ_FAILED JSON/nil-sidecar logic, without diagnostics, guidance or unrelated fixtures. The surrounding service is preserved.++Packet directory: `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/t2382-focused-followup-4b4ecf35/`. Two owned fixture patches bound startup to two seconds and completion receipt to eight seconds. Cancellation is checked before a queued blocker enters the original six-second sleep; its defer signals completion. A missed start prevents dispatch and records cleanup failure explicitly. Successful cleanup is required before subsequent MainActor accounting. Coordinator response errors retain the original error after bounded blocker cleanup and bounded unfinished-permit polling. Existing five-second return bounds, invalid-argument ordering, publication and retained-permit assertions remain. Runtime acceptance is pending.++The shared HTTP helper is separately owned by T2383. Its existing 4ddbfc8774aa2bd95da545d14de8065bf12f16f9 component uses async NIO channels and awaited normal/error cleanup. Root verified its parent helper is byte-identical to T2382 4b4ecf35 and exported the exact single-file patch for parent coordination at `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/t2382-shared-helper-reference/manifest.json`; read-only apply check passes. No helper edit or recipient mutation was performed by T63. No runtime job launched while T1734 held the slot.
diff --git a/specs/bounded-read-freshness/catalog-read-failed-red-preparation.md b/specs/bounded-read-freshness/catalog-read-failed-red-preparation.mdnew file mode 100644index 00000000..4553ac1a--- /dev/null+++ b/specs/bounded-read-freshness/catalog-read-failed-red-preparation.md@@ -0,0 +1,17 @@+# Catalog READ_FAILED focused regression preparation++The approved error-contract gap has focused source preparation without broad replanning. Test source is `fc2096d6f1d7890fe6380300988740b2a6627cfd`, preserving earlier test-only checkpoints `2e993eb` and `8811069`. One declaration expands to six cases: `get_projects` and `query_milestones` across storage, serialization and incoherent-capture faults.++The fixture uses the actual service, coordinator, common modern binding and measured complete RPC encoder. Its primary response follows the production unattached failure path; an independent real private-page factory control checks the original error flag. Bounded physical completion and empty publication accounting are controls. Metadata category, request ID, cached policy and absence of successful snapshot/asOf are checked. The missing READ_FAILED code is a soft assertion after optional JSON parsing, so the anticipated baseline failure cannot be a thrown parser/setup error. When the code exists, the structured source must be JSON.++Strict targeted lint, syntax parsing and diff checks pass. Coordinator independently verified the test hash, eight artifact hashes, all twelve unchanged Task15 production files, and byte-identical original Task14 suites/helper. The focused actual RED is now recorded in [catalog-read-failed-red-handoff.md](catalog-read-failed-red-handoff.md). All six intended body failures were observed, but runner finalization stalled and the runtime result is unfinalized. The approved narrow GREEN source is committed at `d2648f6`; actual GREEN remains unexecuted. No installed-app activation occurred.++The narrow GREEN is now committed at `d2648f699a7ebb4426180ef3800f3f70fdf7c07d` and exported as a two-file recipient component. Only READ_FAILED for the two catalog tools becomes `{error:{code,message}}` JSON with the existing generatedJSON default; query_tasks, other textual errors, precedence, successful output and failure metadata remain unchanged. The paired guidance correction advertises READ_FAILED only after the wire repair. Existing current T2383 binding and adapter inspection confirms nil sidecar uses generatedJSON and preserves category-derived semantic failure; no common provider code change is required by inspection. Parent accepted the actual six-case RED evidence with the unfinalized-result limitation before authorizing this source repair.++Local regression manifest: `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/catalog-read-failed-red-preparation/manifest.json`. Next focused selector is `TransitTests/MCPReadCatalogFailureTests` (one declaration/six bodies). Existing diagnostics/caller GREEN remains ten declarations/thirteen bodies, independently queued. Task15 and Task16 remain incomplete.++## Exact diagnostic production import++The recipient-based twelve-file component patch is generated from immutable `fa58dc0d67aee5dd30e228f30b74ae89c8484953` against requested T2383 recipient `74cbabf`. It includes all missing diagnostic types and their owned callers; it excludes Settings, tests/helper, proposed wire GREEN, full App/Handler files and other owners' modules. The twelve owned immutable payloads are also retained, independently verified against source git objects; recipient prehashes were verified against pinned git objects.++Manifest: `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/task15-source-preparation/recipient-production-patch-74cbabf/manifest.json`. Read-only application checks pass for the component and both separate constructor patches. Parent has routed Handler ownership and granted the exact containment App hunk (SHA256 `59f12a521233808b4377990daa18a59e19cc17c1fa117a627876695e1d17dd51`). T2383 integrates the component before those constructor hunks, preserves all existing work, and returns the exact combined source commit/posthashes. No source import was applied by T63 to the recipient. Source wiring is distinct from installed-app activation; none is authorized or performed here.
diff --git a/specs/bounded-read-freshness/containment-handoff.md b/specs/bounded-read-freshness/containment-handoff.mdnew file mode 100644index 00000000..f0ecfa78--- /dev/null+++ b/specs/bounded-read-freshness/containment-handoff.md@@ -0,0 +1,41 @@+# T63 containment ownership handoff++Source checkpoint: `36f7ee328f53250413beff825af3ae826e25d3d0` on `T-63/bounded-read-freshness`. Source was clean before this document. Stage A is lint-clean but has not passed app compilation/runtime GREEN. Existing app-host and live-write holds remain until the parent explicitly clears them.++## Narrow ownership transfer++The containment worker may own `Transit/Transit/TransitApp.swift` and the development target's project, scheme, entitlement, and build/test selection changes. T63 has no active edits to those files and will not edit them concurrently. T63 retains its read coordinator, dispatcher, service, capture, retention, and read-test files. Any later app-construction change from T63 should be a narrow patch applied by the containment owner.++Pinned source blobs at the checkpoint:++- `Transit/Transit/TransitApp.swift`: `ac0ffa791047285c7526dba96bfa920733f0f734`.+- `Transit/Transit.xcodeproj/project.pbxproj`: `e9d10d37ee46aaa5bde17863b8692857c5ef846a` (T63 has not changed this project file).++Use a clean containment patch or commit chosen by the parent; do not replace the whole app file from an earlier branch. T63's app delta against `e3812b1` is the read construction below plus a mechanical move of the MCP-start methods to an extension.++## Preserve the T63 construction++After the final selected container and effective sync mode are known, preserve these relationships:++```swift+let reads = MCPReadAppDependencies.make(container: container, syncActive: cloudSyncActive)+let readCoordinator = MCPReadCoordinator(domain: reads.snapshots.domain)+// Handler construction retains its existing writeCoordinator and persistence inputs,+// and receives taskQuerySnapshots: reads.snapshots,+// readService: reads, readCoordinator: readCoordinator.+// MCPServer receives that SAME readCoordinator.+```++There is one coordinator per app lifetime; listener restart must not construct another. Ordinary retention and the coordinator share one publication domain. `MCPReadAppDependencies` reads public history and starts an observer; it does not save records or establish positive import visibility. In isolated development/test storage, effective sync must remain false. Keep the protected-write `MCPWriteReceipt` model in the app schema and keep receipt sidecars in the isolated storage policy.++## Containment acceptance boundary++The existing `NSClassFromString("XCTestCase")` test-host heuristic is not verified for the Swift Testing host processes. The new development/test target must select isolated storage deterministically and fail closed before live container creation or sidecar selection; runtime class detection alone cannot be the safety boundary. Development bundle identity, store URL, CloudKit entitlement/configuration, receipt sidecar, and automatic MCP startup must follow that target's explicit policy. Do not launch/reconnect the development MCP server as part of this handoff.++Synthetic disposable-store migration checks are owned by containment and must preserve UUID/display-ID and receipt/revision evidence. Seven rows imported in one CloudKit transaction and mixed model generations are evidence/hypothesis reported by the parent, not a cause established by T63. This document authorizes no live record correction, deletion, merge, reassignment, or guard reset.++App-host verification resumes only after the parent reviews the verified isolation result and explicitly clears the hold. The parent granted the isolated component integration and the six focused suites after containment's verified smoke checkpoint `9ba4297`. T63 integrated the component at `6806262`, retained the owned actor fix `46bec7c`, and added the missing fixture import at `c614a9b`.++The verified Stage A checkpoint is `b500543369ebbd53f01634fa829bf74a8fceabe5`. Its dedicated isolated smoke passed one test; the shared Transit Debug build passed, signed-host/xctestrun preflight passed, and six sequential suites passed fourteen methods / seventeen device executions with zero failures or skips. Both timed full-response cases completed below five seconds. Initial fixture assertion failures and the initial runner termination limitation are retained separately from the corrected passing results. All owned processes drained and the exclusive slot was released.++Evidence and exact commands are preserved outside Git at `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/stage-a-isolated/`. This grants no broader suite, production launch, live Transit write, or app MCP enablement. Final T2382 and modern protocol integration remain separate acceptance gates. Containment keeps App/project/isolation ownership; T63's future construction changes remain owner-applied narrow patches.
diff --git a/specs/bounded-read-freshness/decision_log.md b/specs/bounded-read-freshness/decision_log.mdindex e4bbc700..4a49412b 100644--- a/specs/bounded-read-freshness/decision_log.md+++ b/specs/bounded-read-freshness/decision_log.md@@ -1,5 +1,25 @@ # T-63 decision log +## Squash-main reconciliation and publication approval — 2026-10-04++Parent forwarded explicit user approval for all Transit pushes and sharing changes with the configured Claude reviewer (Sentinel_26fb7496284881918233b3670bb003c1), alongside overnight merge authorization. The previous disclosure gate is cleared. No deployment, client activation or live-data repair is authorized.++T2383 PR250 merged at `e6bde03631b2d4198e9ceff13b49ec56b62b64c3`. The old T63 head `ff6286a` is preserved at `T-63/pre-squash-ff6286a` and in existing native/Pulsar evidence. The dedicated branch is reconstructed on that squash commit with only its unique tests/docs; no already-merged foundation/common production commit is replayed. Newer T2383 breaking-change release notes are retained. All 537 compiled inputs remain byte-identical to verified `dbf3355`, so the exact native/iOS evidence and code reviews remain applicable; fresh lint and review check the reconciled scope. Native stall and overlap qualifications remain binding.++## Final local verification checkpoint — 2026-10-04++All 16 implementation tasks are complete at source `dbf3355d66ab51767fc97ef840dac2ead9c3573b`. Twenty-three finalized native selections cover 2,189 configured declarations exactly once, with 2,425 passing executions and no failures/skips/warnings/issues. Root independently queried actual bundles and verified source/artifact hashes. [Task16 acceptance](task16-green-acceptance.md) preserves five excluded stalled attempts, the Chunk05 post-body overlap qualification, and the adjacent fixture-only priority-inversion repair. The stall cause remains unproved. All heavy jobs are drained.++Parent conveyed overnight push/PR/merge authorization after checks (Sentinel_da18efb69dec819181f52a872520d2fb); deployment, live-data repair, client activation and CloudKit operations remain excluded. That authorization is distinct from external Claude disclosure approval, which is still pending parent forwarding. Creating a PR triggers the repository's automated Claude review and remains held. User-requested pre-push Pulsar publication is part of the authorized local review workflow. Actual installed-client compatibility is separately owner-approved deferred post-merge for T2383.++## Current integration decision — 2026-10-04++The parent confirmed that the already-approved latest-only T2383 contract takes one JSON-RPC object per POST and rejects wire arrays. The original wire-batch and mixed-delivery decisions recorded below are historical foundation context; generic coordinator aggregation evidence remains useful, but final production exposes no dual-era array path. This supersession updates execution guidance without reopening product approval. Identifier batches within `query_tasks` and `mutate_tasks` application batches are distinct.++Implemented portfolio source is consumed at `c123210`: exactly the six owned files from `8478b17`, matching the local owner hash/dependency handoff. The owner independently verified 54 declarations/61 expanded cases at `a3c2a705`; local integrated verification has not run. Stage B uses the confirmed direct `MCPPreparedReadCapture?` entrypoint and retained replay without recapture. Stage C still requires a stable verified integration checkpoint and explicit common-file transfer to T2383, including the extracted `MCPServer+Routing.swift`.++The user approved local builds and tests on the isolated development/test target (Sentinel_10e284fb472881918fb01fad1bde10d2). Heavy jobs still require coordinated exclusive grants. Routine reports remain local; phone/document delivery is limited to spec review or an explicit user request. No live-data write, client activation, merge or deployment is authorized by that testing approval.+ ## Quick decisions | Date | Decision | Rationale / authority |
diff --git a/specs/bounded-read-freshness/design.md b/specs/bounded-read-freshness/design.mdindex 9da10da0..373b142a 100644--- a/specs/bounded-read-freshness/design.md+++ b/specs/bounded-read-freshness/design.md@@ -2,6 +2,8 @@ Review status: approved unchanged by the user in the parent conversation (Sentinel_541ceb19e7c8819193d04d23c5263041), including final scope/publication amendments at 5639c40. Tasks and implementation are also approved (Sentinel_c2e9343628948191b921868234aaf409). +Current transport decision: the approved latest-only T2383 adapter accepts one JSON-RPC object per POST and rejects arrays. Wire-batch and mixed-delivery passages below preserve the historical foundation design and generic aggregation evidence only. Final routing must use the modern adapter; no dual-era production path is required. Identifier batches inside `query_tasks` and application batches such as `mutate_tasks` remain distinct from wire arrays.+ ## Architecture Place deadline/admission coordination between decoded Hummingbird requests and MainActor read dispatch. Store access remains MainActor isolated; encoded bytes, immutable captures, freshness evidence, and retention are safe to handle outside it. A caller timeout ends response delivery, not the physical operation's admission lifetime.
diff --git a/specs/bounded-read-freshness/foundation-handoff.md b/specs/bounded-read-freshness/foundation-handoff.mdindex 8e981dd3..d1ca9f67 100644--- a/specs/bounded-read-freshness/foundation-handoff.md+++ b/specs/bounded-read-freshness/foundation-handoff.md@@ -1,5 +1,7 @@ # T-63 fixture foundation handoff +Current acceptance: Tasks12/13 are complete after exact verified Task17 consumption. The earlier staged statements below retain their checkpoint provenance; [task13-acceptance.md](task13-acceptance.md) records the modern actual-module closure and queued Task14 RED readiness. No local runtime rerun is claimed.+ Tasks 2/3/6/7/8/9 are verified. The publication registry and ordinary retention are implemented and locally tested. T2382 may consume this shared API after parent review; actual cross-ticket routing acceptance remains tasks 13/16. ## Verified evidence
diff --git a/specs/bounded-read-freshness/implementation.md b/specs/bounded-read-freshness/implementation.mdnew file mode 100644index 00000000..7878f9eb--- /dev/null+++ b/specs/bounded-read-freshness/implementation.md@@ -0,0 +1,61 @@+# T-63 implementation explanation++This explanation describes the integrated source at `dbf3355d66ab51767fc97ef840dac2ead9c3573b`. Production consumes the verified cumulative T2383 modern transport. The successor to `b8c8194` changes only four detached priorities in one macOS fixture, addressing an observed priority inversion while preserving every assertion. Verification status is qualified below.++After T2383's squash merge, production is already on main. The reconciled T63 branch contains only its unique acceptance tests, fixture repairs and documentation; the explanation below describes the integrated behavior that those tests validate.++## Beginner Level++### What Changed++Covered MCP reads return a complete picture of saved local records with the time that picture was captured. The server has five seconds to prepare its response. It can return a timeout even when a slow database operation continues in the background. Eight unfinished operations are allowed, so repeated retries cannot start unlimited work.++### Why It Matters++A caller can distinguish a recent local capture from evidence of a remote import. The app does not claim remote edits have arrived merely because it recently read its database. Failed database reads produce errors rather than plausible empty results. Continuing a page returns the original picture and its original freshness information; a new initial request creates a new picture.++### Key Concepts++`asOf` describes the saved local capture time. `snapshotId` identifies the captured picture. Freshness describes the available import evidence, which can honestly be unknown. A cursor is a bookmark into that original picture. It does not refresh it or extend its expiry.++## Intermediate Level++### Changes Overview++`MCPReadCoordinator` owns process-lifetime admission, the independent response deadline and physical-work cleanup. `MCPReadCaptureBuilder` copies saved records into immutable DTOs under a history/import generation fence. `MCPImportEvidenceMonitor` and the refresh decision preserve applicable import outcomes separately from local capture. `MCPReadService` prepares projections, metadata and categorized failures. `MCPReadPublicationDomain` couples selected encoded responses with retention publication. Ordinary task pages and T2382 reusable views consume the same capture contract while retaining separate lifecycle policies.++### Implementation Approach++The response timer runs independently of MainActor database work. A 4,850 ms internal cutoff leaves a margin inside the five-second server preparation budget. Timeout selects already prepared error bytes; the physical permit stays held until work actually finishes. Stop/start invalidates unpublished work without resetting unfinished counts.++Saved capture uses a fresh autosave-disabled context and compares persistent-history watermarks before and after copying. No live model or context crosses the executor boundary. Required fetch, serialization or coherence failures preserve `isError` and carry an explicit category. Query failures retain `QUERY_FAILED`; project and milestone execution failures use `READ_FAILED`.++Metadata lives in `result._meta["me.nore.ig.transit/read"]`, outside structured tool data. Retained pages preserve the original metadata bytes and records. Publication validates the entire selected set before committing retained entries, so an error or late result cannot expose an unpublished successful snapshot.++### Trade-offs++The current SwiftData integration cannot prove a remote import applies to the selected capture or request a supported force pull. It returns the approved `unknown`/null evidence and `unavailable` refresh outcome rather than inventing recency. Cached reads bypass import waiting but still capture saved data. Inactive sync reports `not_applicable`. The operation-count and encoded-retention limits bound different resources; neither is a promise about total heap size.++## Expert Level++### Technical Deep Dive++Response selection and physical completion are separate terminal events. A non-cooperative capture can outlive timeout, disconnect or generation invalidation while continuing to consume admission capacity. The strict timer and bounded diagnostic enqueue avoid actor-dependent timeout delivery. Prepared retention candidates, preencoded failure bytes and an atomic publication domain keep success identity consistent with visible retention; stale append versions reject with `READ_BUSY`.++History fencing checks saved-store coherence and is independent of remote-import applicability. Positively relevant import evidence must also be visible to the chosen capture before it can yield `recent_import`. Wall-clock and monotonic age checks prevent a clock change from improving freshness. The last valid applicable success is retained separately from later failures and concurrent outcomes. Canonical task revision/comment evidence uses the merged authoritative record snapshot routine; summary projection does not mint a different revision.++### Architecture Impact++Immutable `CapturedReadView` carries typed scope and completeness. T2382 can reuse the same capture identity and freshness for portfolio totals and task views, while rejecting requests beyond the retained scope. Shared preparation and publication primitives avoid a second freshness service. The integrated modern production route accepts one JSON-RPC object per POST and rejects wire arrays; historical generic batch coordinator tests remain component evidence, not advertised transport support.++### Potential Issues++Explicit retries need backoff and a finite attempt limit because timed-out physical work still holds capacity. Frozen cursors intentionally retain old freshness; callers needing newer records must start a new query. Platform import applicability remains unsupported and must not be inferred from notification arrival, a heartbeat, local save or launch state. Diagnostics distinguish stages but do not prove the cause of unexplained delays.++## Completeness Assessment++Saved capture, bounded response selection/admission, frozen metadata, shared retention publication, categorized failures, modern routing and diagnostics are implemented. Task15's original diagnostics/caller/catalog selection finalized normally: 11 declarations and 19 expanded bodies passed, with zero skips, failures or runtime/global issues. Independent hashes pin the executed source.++Task16 is complete: 23 finalized native selections cover all 2,189 configured declarations exactly once, with 2,425 passing executions and zero failures, skips or warnings/issues. Root independently queried their native test trees and reconciled the full inventory. Five earlier stalled attempts remain excluded and preserved; their cause is unproved. One finalized selection retains its post-body overlap qualification. The repaired publication fixture finalized warning-free on a new signed artifact. See [Task16 acceptance](task16-green-acceptance.md) for precise source, artifact and sequencing evidence. Finalized iOS/UI evidence is reused only under the independently verified unchanged active-source/configuration proof, not as macOS verification.++Live signed-store import applicability is unproved; the honest fallback is implemented. Installed-client compatibility is separately owner-deferred for T2383. No deployment, live-data repair, client activation or CloudKit operation is performed. Parent has now forwarded explicit push/Claude-review disclosure approval; the remaining unique tests/docs are reconciled on merged main for PR Pilot.
diff --git a/specs/bounded-read-freshness/integration-ownership.md b/specs/bounded-read-freshness/integration-ownership.mdindex 02ae1b74..a96408c2 100644--- a/specs/bounded-read-freshness/integration-ownership.md+++ b/specs/bounded-read-freshness/integration-ownership.md@@ -1,6 +1,6 @@ # Shared read integration ownership -Status: coordination proposal before task 13 GREEN. No shared-file handoff has occurred. The verified T63 component baseline is `dc85eabb5b35a6bd6b9ee16908d72aeb2c55bf15`; it does not enable production bounded routing. Task 12 routing fixtures reached actual app RED at `099415e832afc312a94e9521e3704eba729e441d`: saved reads leaked UI changes, frozen metadata was absent, valid and invalid reads exceeded five seconds, and a late cursor root became visible. Lifecycle/helper fixtures may proceed independently of actual T2382 delivery. Actual-module acceptance cannot pass on fixtures alone.+Status: staged transfer prepared against clean `b1f30256b4fb33270809188131d047a29807f162`; no ownership transfer has occurred. All 64 MCP/portfolio production files match the owner's tested `b4c104e7`, whose four current-foundation router cases passed and drained. T63 Stage A and expiry evidence remain separately verified. The retained HTTP test helper differs, so identical local-fixture/runtime GREEN is not claimed. `modern-transfer-manifest.md` and its hashed JSON distinguish genuine transfer prerequisites from later acceptance; diagnostics, descriptions and full-ticket completion do not block the adapter writer. ## Integration layers @@ -8,32 +8,32 @@ Status: coordination proposal before task 13 GREEN. No shared-file handoff has o 2. T63's policy-bound capture preparation starts the import observation window before the decision, preserves the original remaining budget, captures saved values inside the history/generation fence, and freezes metadata. T2382 receives that same complete declared-scope view for aggregation and reusable retention. A generic preparation callback must preserve observation lifetime and private reservation ownership. 3. Ordinary reads and T2382 helpers prepare tool-level results without an originating RPC ID. `MCPPreparedToolRead.encodedToolResult` is authoritative at the current baseline; its logical result is not a replay encoder. T2383's approved `MCPResultEncoder.freeze(...) -> MCPResultToolFragment` is the later modern representation. Cursor replay retains the original fragment, metadata, policy and expiry. 4. The transport prepares the complete RPC response bytes, with the current ID, before offering `PreparedReadResult` to the common publication domain. Candidate grouping and all-store validation precede one terminal selection. No response serializer runs after publication, and a timeout never releases an unfinished physical worker's permit.-5. T2383 takes the modern wire adapter after a verified T63 integration commit and explicit ownership transfer. Modern production rejects wire arrays. Existing coordinator batch tests may remain historical component evidence; T63 adds no dual-era protocol support. Final routing acceptance uses the modern adapter.+5. T2383 takes the modern wire adapter after the parent records the fixed source/evidence base and exact staged ownership transfer. This does not wait for unrelated T63 completion. Modern production rejects wire arrays. Existing coordinator batch tests may remain historical component evidence; T63 adds no dual-era protocol support. Final routing acceptance uses the modern adapter. The parent and T2382 confirmed these tool-level helper signatures before delivery: ```swift handlePortfolioSummary(request: MCPPortfolioSummaryRequest,- view: CapturedReadView,+ capture: MCPPreparedReadCapture?, operation: MCPReadOperation) throws -> MCPPreparedToolRead handleSnapshotTaskQuery(request: MCPSnapshotTaskQueryRequest,- view: CapturedReadView, operation: MCPReadOperation) throws -> MCPPreparedToolRead ``` The earlier no-ID `PreparedReadResult` scaffold is not a valid final-response boundary. T63 owns the one outer RPC encoder, including fallback response bytes and the original budget. The confirmed helper return composes with T2383 frozen fragments. -The types-only capture seam is `MCPReadCapturedPreparing.prepareCapturedRead(request:policy:operation:transform:)`. Its `MCPPreparedReadCapture` capsule carries `view` and `frozenMetadataBytes`. The Sendable async transform may use pure DTO work off MainActor and explicitly hop for handler/store work. Capture remains synchronous on MainActor inside the fence. The observation window remains held through transformation and private result/reservation preparation. This seam's implementation belongs to task 13; declarations do not establish delivery.+The implemented capture seam is `MCPReadCapturedPreparing.prepareCapturedRead(request:policy:operation:transform:)`. Its `MCPPreparedReadCapture` capsule carries `view` and `frozenMetadataBytes`. The Sendable async transform may use pure DTO work off MainActor and explicitly hop for handler/store work. Capture remains synchronous on MainActor inside the fence. The observation window remains held through transformation and private result/reservation preparation. Source delivery and component verification do not replace final modern transport acceptance. ## File ownership | Files or surface | Current owner | Later handoff | | --- | --- | --- |-| `MCPServer.swift`, `MCPServer+Responses.swift`, `MCPServer+ToolListNotifications.swift` | T63 through verified bounded integration | T2383 becomes the sole writer for modern wire validation, discovery, subscriptions and response adaptation after explicit transfer. |+| `MCPServer.swift`, `MCPServer+Routing.swift`, `MCPServer+Responses.swift`, `MCPServer+ToolListNotifications.swift`, `MCPServerDecodeTypes.swift`, `MCPServerLifecycleConfiguration.swift` | T63 until recorded Stage 1 transfer | T2383 becomes the sole writer for modern wire validation, discovery, subscriptions and response adaptation after explicit transfer. | | `MCPToolListChangeBroadcaster.swift` | T63 retains current shared ownership; no new edits planned for read preparation | T2383 transport/subscription ownership with the same explicit transfer. | | `MCPTypes.swift` | T63 preserves the existing metadata/result contract | T2383 modern envelope/result encoding after verified baseline; preserve T63's independent read metadata namespace. | | `MCPToolHandler.swift`, `MCPToolHandler+TaskQuery.swift` | T63 common construction, classification and dispatch; actual T2382 registration | T2383 becomes the sole writer after verified integration. Later T63 diagnostic/read patches are narrow patches coordinated through that owner. |-| `MCPToolDefinitions.swift` | T63 through task 15 caller descriptions and common registration | T2383 supplies a narrow output-schema/discovery patch for T63 to apply; full transfer follows the verified description checkpoint. |+| `MCPToolDefinitions.swift` | T63 retained owner | T2383 supplies an immediate narrow output-schema/discovery patch for T63 to apply; API15 binding does not wait for task 15 descriptions. A later full transfer needs its own record. |+| `MCPToolHandler+CapturedRead.swift`, `MCPToolHandler+PortfolioReadPreparation.swift` | T63 retained owner | Modern producer/fragment glue is a narrow owner-applied patch; admission, saved capture and selector mapping remain intact. | | All `MCP/Reads` files | T63 | Retain ownership. T2383 supplies narrow fragment/preparation changes for T63 to apply. Public physical-scope and freshness contracts remain shared. | | `MCPTaskQuerySnapshotStore.swift` and ordinary retained-page hooks | T63 | Retain ownership for modern fragment retention and exact accounting. Never extend a retained root's original expiry. | | Portfolio aggregation, request parsing, projection, separate handler/schema modules and reusable store | T2382 | T2382 delivers clean verified modules; T63 wires shared entrypoints. T2383 coordinates its reusable-fragment change through T2382. |@@ -47,7 +47,7 @@ No blanket handoff is implied by this table. The parent records the exact clean T2382 delivers its separate portfolio summary and snapshot query handlers, descriptors/tool definitions, reusable-store lifecycle hooks, participant aggregation, and tests from a clean verified revision. It confirms the helper return layer described above. T63 supplies the generic policy-bound capture preparation and shared dispatch registration; portfolio aggregation and reusable lifecycle logic remain in T2382 modules. -T2383's interface-only `8ea94ce0b3b9a3b73fcee330aed0c9883a08e92f` declares `freeze(source:presentation:metadata:)`, `encode(fragment:id:)` and `prepareMutationFallback(...)`. These methods are placeholders, not completed delivery. Its GREEN encoder must preserve original text/isError/source/presentation and frozen `_meta` values without renewed assessment or lossy numeric conversion. Retention charges expanded `encodedResult.count` plus uniquely retained backing once, retaining original policy and expiry. Complete response bytes must be ready before terminal publication.+The earlier interface-only `8ea94ce0b3b9a3b73fcee330aed0c9883a08e92f` declared `freeze(source:presentation:metadata:)`, `encode(fragment:id:)` and `prepareMutationFallback(...)`; it is historical placeholder evidence, not the modern module delivery. Consume the exact reviewed real encoder/schema component and its ABI when delivered. It must preserve original text/isError/source/presentation and frozen `_meta` values without renewed assessment or lossy numeric conversion. Retention charges expanded `encodedResult.count` plus uniquely retained backing once, retaining original policy and expiry. Complete response bytes must be ready before terminal publication. Foundation tasks 1–11 and task 12's fixture draft do not depend on those later modules. Task 13 actual-module acceptance and final modern routing do. This separates preparation from delivery without making T2382/T2383 foundations wait for final T63 production routing.
diff --git a/specs/bounded-read-freshness/modern-transfer-manifest.md b/specs/bounded-read-freshness/modern-transfer-manifest.mdnew file mode 100644index 00000000..ef12319e--- /dev/null+++ b/specs/bounded-read-freshness/modern-transfer-manifest.md@@ -0,0 +1,46 @@+# Staged shared-file transfer to T2383++Status: prepared for the parent to record an explicit transfer. This document does not transfer ownership by itself. Source/test base: `b1f30256b4fb33270809188131d047a29807f162`; production base is unchanged from `90daf44` and the six-file integration `c123210`. Exact file hashes are in `modern-transfer-manifest.json`.++## Verified base and remaining delta++All 64 MCP/portfolio production files match the owner's tested `b4c104e76a482562bc8eae2ae9f54a6e5712ffc5`. Its four current-foundation router tests passed with signed-host preflight, exit zero and normal drain. Earlier helper verification passed 54 declarations/61 cases. T63's own bounded Stage A passed 14 methods/17 executions, and the corrected expiry gate passed one method/six executions at `7a2f4de`. These remain distinct evidence sets; they do not establish final API15 acceptance.++The two corrected router fixtures are now pinned here exactly. Three of four shared fixture dependencies match. T63's `MCPHTTPTestHelpers.swift` intentionally adds nonisolated execution, optional protocol-version headers and `Sendable` response conformance. It is not replaced by the older owner helper. This scheduling/header dependency is the genuine remaining local-harness delta: run the four fixtures with the retained helper during modern integration verification. Do not claim an identical local rerun, and do not repeat the legacy run merely to match bookkeeping.++The owner's `040da36` handoff confirms the corrected fixture hashes and four passing cases at `b4c104e7`. Additional actual-router expiry verification at `ee053269` passed two cases with normal exit/drain: original frozen metadata/expiry before the deadline, exact five-minute snapshot/cursor errors and no recapture. These are two distinct verified source/run identities, totaling six external Stage B cases, not one combined run or local-harness GREEN. The additional expiry fixture has not been imported here; current-helper/modern integration verification must include it.++## Stage 1: release the adapter writer++After the parent records this exact base and file list, T2383 becomes the sole writer for these ten production files:++- `Transit/Transit/MCP/MCPServer.swift`+- `Transit/Transit/MCP/MCPServer+Routing.swift`+- `Transit/Transit/MCP/MCPServer+Responses.swift`+- `Transit/Transit/MCP/MCPServer+ToolListNotifications.swift`+- `Transit/Transit/MCP/MCPServerDecodeTypes.swift`+- `Transit/Transit/MCP/MCPServerLifecycleConfiguration.swift`+- `Transit/Transit/MCP/MCPToolListChangeBroadcaster.swift`+- `Transit/Transit/MCP/MCPTypes.swift`+- `Transit/Transit/MCP/MCPToolHandler.swift`+- `Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift`++The optional seven-file transport-fixture transfer is separately enumerated and hashed in JSON: route, wire-array, notification, tool-list, origin, lifecycle and startup-failure fixtures. The parent must include them explicitly to transfer them. Read coordinator/capture/retention fixtures, T2382's portfolio fixtures and T2384's write fixtures stay with their owners. The common HTTP and environment helpers remain T63-owned; modern header/helper changes are narrow owner-applied patches.++Genuine entry prerequisites are an immutable clean base, matching file hashes, an explicit parent ownership record, and no remaining old writer for those paths. These are source coordination requirements. The current production files already match compiled, tested owner source; local-harness verification is a later acceptance obligation, not a reason to block adapter implementation. T2383's own required RED/GREEN and current execution-permission hold remain its workflow gates; this manifest bypasses neither.++T63 freezes Stage-1 paths after transfer. Any later read/diagnostic change touching them is supplied as a narrow patch to T2383 through the parent. Preserve the process-lifetime coordinator, original decoded admission instant, non-MainActor classification, listener-generation/physical-drain fences and existing write coordinator behavior. Final production takes one JSON-RPC object per POST and rejects arrays; generic coordinator aggregation evidence remains component evidence.++## Stage 2: compose fragments and schemas through retained owners++T2383 supplies its reviewed real encoder/schema modules and exact ABI. T63 applies any narrow binding changes in `MCP/Reads`, `MCPTaskQuerySnapshotStore.swift`, `MCPToolHandler+CapturedRead.swift` and `MCPToolHandler+PortfolioReadPreparation.swift`. T2382 applies reusable-store/portfolio fragment changes in its own modules. Neither owner recreates or re-assesses frozen metadata. Complete actual-ID response bytes and all failure variants must be prepared before the sole publication gate; charge expanded encoded results and uniquely retained backing while keeping original policy and expiry.++`MCPToolDefinitions.swift` remains T63-owned. API15 output-schema/discovery registration is an immediate narrow owner-applied patch from T2383; it does not wait for T63 task 15 descriptions. A later full definition-file transfer requires its own explicit record. T63 can deliver later description changes as patches without holding up API15 delivery.++Before combined runtime acceptance, align the four portfolio router fixtures' request headers with the delivered latest-only adapter and add the separate source/presentation/exact opaque-metadata assertions. These depend on actual delivered APIs; no placeholder or invented interface is accepted.++## Work that does not block Stage 1++T63 tasks 14/15 diagnostics and caller examples, task 16 full macOS/iOS checks, final pre-push review/Pulsar, unrelated typed-task-link schema work, and test-copy bookkeeping do not gate the adapter writer. They remain required for their own ticket completion. Final task 13/API15 GREEN does require the composed adapter/fragment contract and current-helper runtime verification. Heavy jobs remain exclusive and parent-scheduled; this manifest authorizes no run, live write, client activation, merge or deployment.++App, project, signing, isolation and Makefile files remain with the containment/build owner. T2384 retains its write coordinator and write-specific tests. No blanket branch import or shared-file replacement is authorized.
diff --git a/specs/bounded-read-freshness/owner-patches/modern-tool-definitions.md b/specs/bounded-read-freshness/owner-patches/modern-tool-definitions.mdnew file mode 100644index 00000000..db926837--- /dev/null+++ b/specs/bounded-read-freshness/owner-patches/modern-tool-definitions.md@@ -0,0 +1,18 @@+Delegated modern definitions factory++T63 authorizes T2383 to apply modern-tool-definitions.patch exactly on its isolated modern branch. Retained MCPToolDefinitions ownership remains T63; this is the approved factory hunk only. T63 live source intentionally stays unchanged because modern modules are absent here.++Signature: static func modernTools(includingMaintenance: Bool) throws -> [MCPModernToolDescriptor]. It maps tools(includingMaintenance:) once, preserves name/description, parses the existing encoded input schema, and obtains the result descriptor from MCPResultSchemas. Existing arrays, tools/all, input contracts and descriptions remain unchanged. Foundation import is inside the macOS conditional.++Recipient baseline: 76fa6620743307219e31fe7ec3abe1191d466da3; local/recipient/baseline definitions byte equality confirmed. Hashes and source checks are recorded below. Syntax/lint/check application are source preparation only; no typecheck, app compile, runtime GREEN or Task13/15 completion.++Source checks: temporary proposed source strict SwiftLint --no-cache PASS (zero violations), Swift6 frontend syntax parse PASS, recipient read-only git apply --check PASS.++Required recipient tests: extend the existing MCPModernRouterIntegrationTests acceptance with actual definitions parity for maintenance off/on (names, descriptions and semantic input schema equality; independent JSONEncoder dictionary ordering is not a raw-byte parity contract), output schema from actual descriptor, and real modern single-object POST tools/list with outputSchema. No legacy arrays or live writes.++{+ "recipientBase": "76fa6620743307219e31fe7ec3abe1191d466da3",+ "baselineSHA256": "decfde58b4728ace41b4c83f5b32f24a46ef397a001927843d90e279ab53d45a",+ "finalDefinitionsSHA256": "879d1094658ad9840a86ce20839bbae048a4936540c169fa985a1d1df7c132dd",+ "patchSHA256": "36357d3c785fba21796e7443edc0baba08672568a6373495a8d1161a6d0228ea"+}
diff --git a/specs/bounded-read-freshness/portfolio-binding-handoff.md b/specs/bounded-read-freshness/portfolio-binding-handoff.mdnew file mode 100644index 00000000..544cd3af--- /dev/null+++ b/specs/bounded-read-freshness/portfolio-binding-handoff.md@@ -0,0 +1,40 @@+# T63 portfolio binding seams++Current source integration is `c123210`: the exact six implemented portfolio files from owner `8478b17` are consumed, with all handoff hashes matching. The signatures and frozen-capsule contract below remain authoritative. Earlier scaffold and lightweight-validation statements describe historical interface preparation; owner implementation has separate 54-declaration/61-case verification, while local Stage B and final modern acceptance remain pending. See `routing-integration-plan.md` for current readiness.++## Original capture bytes++Use the existing shared `MCPPreparedReadCapture` from the verified T63 preparation revision. It carries `view` and `frozenMetadataBytes`; do not declare another capsule or reconstruct the bytes from `view.metadata`.++The exact proposal relayed to T2382 for confirmation is:++```swift+handlePortfolioSummary(request: MCPPortfolioSummaryRequest,+ capture: MCPPreparedReadCapture?,+ operation: MCPReadOperation) throws -> MCPPreparedToolRead++handleSnapshotTaskQuery(request: MCPSnapshotTaskQueryRequest,+ operation: MCPReadOperation) throws -> MCPPreparedToolRead+```++Initial summary requires the nonnil capsule supplied directly by the admitted `prepareCapturedRead` transform. Summary replay/continuation requires nil and obtains original bytes, identity, policy and expiry from its retained root. Snapshot task queries retrieve their existing `RetainedView` themselves and bypass live capture/refresh. These replace the earlier view-only proposal, which could not preserve the original byte representation. T2382 confirmation and its concrete handler delivery remain pending.++The transform uses the same `MCPReadOperation` and original admission budget. T63 holds the import observation through private aggregation/encoding/retention preparation, then prepares the actual-ID full response before the common publication gate. T2383's later validated/sealed fragment boundary remains a separate delivery.++## Shared schema definition++Source-only commit `f4e29556feb36dec62e8ebeb7f20b5110a5b6f4b` extends the existing `JSONSchemaProperty` with optional `minimum: Int?`, `maximum: Int?`, `const: Bool?`, and `defaultValue: String?`. The last encodes as `default`. Unset values are omitted, preserving existing helpers and callers.++T2382 can bind limits `minimum = 1`, `maximum = 100`, snapshot comments `const = false`, and initial policy `defaultValue = "refresh_if_needed"`. T2383 consumes this same definition rather than introducing another schema type. T63 retains common schema registration and must merge/replace the query cursor branch rather than append an overlapping alternative. Descriptor registration is not verified by this declaration change.++Patch: `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/schema-seam/f4e2955-schema-seam.patch`. Strict standalone actual-source typecheck and lint passed; no app build ran.++## Fault preparation++Source-only commit `1b2e813f154b8dbfd542cb63d4bb66bdac669e1c` exposes the existing MainActor-isolated `MCPReadService.prepareFailure(_:tool:operation:policy:) -> MCPPreparedToolRead`. Existing mapping and payload behavior are unchanged. The admitted portfolio bridge can use it for capture faults before outer encoding, avoiding accidental classification of storage/coherence failures as envelope serialization failures.++Fault injection uses the existing real `MCPReadService(source:monitor:snapshots:...)` and handler `readService` input. A test source conforming to `MCPReadCaptureSource` can throw typed storage, serialization or incoherent-capture errors. No mock shared API or duplicate error mapper is needed. Portfolio request/scope errors retain their own typed handling.++The existing non-query mapper returns plain failure text even though its local selected code is `READ_FAILED`. Integrated fault assertions must verify the intended wire code/category/text and repair any mismatch through the approved RED/GREEN process. This seam does not claim that a machine error code is already present in that text.++Patch and detail: `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/failure-mapper/prepare-failure.patch` and `handoff.md`. Strict narrow lint/diff checks passed; no app test, helper wiring or live Transit write ran.
diff --git a/specs/bounded-read-freshness/publication-expiry-handoff.md b/specs/bounded-read-freshness/publication-expiry-handoff.mdnew file mode 100644index 00000000..0023e162--- /dev/null+++ b/specs/bounded-read-freshness/publication-expiry-handoff.md@@ -0,0 +1,31 @@+# Publication expiry follow-up++The shared source checkpoint is `6de04f60dc5ea1bcd7d2ac7d8403e92af10ec519`. The earlier portfolio wiring checkpoint `226db40` remains separately consumable.++## Error contract++The dispatcher preencodes the appropriate publication-gate expiry response before admission:++| Request | Expiry code |+| --- | --- |+| Ordinary task query or ordinary cursor | `QUERY_EXPIRED` |+| Reusable snapshot task query | `INVALID_SNAPSHOT` |+| Reusable task cursor | `INVALID_CURSOR` |+| Summary initial request or snapshot replay | `INVALID_SNAPSHOT` |+| Summary cursor continuation | `INVALID_CURSOR` |++Busy remains `READ_BUSY`; capacity remains `QUERY_CAPACITY_EXCEEDED`. Error responses retain the actual RPC ID and contain no success freshness metadata or unpublished snapshot/cursor ID.++## Verification readiness++Regression preparation is committed at `11cf1ab`; the mapping correction is `1100799`. One parameterized test declares six cases. It uses the actual ordinary/reusable stores, shared publication domain and coordinator. Advancing the domain clock expires the reusable root while its reservation deadline remains valid. Assertions cover the response code, RPC ID, absent success metadata, zero published/pending entries and bytes, and bounded physical worker drain.++At the unchanged mapping checkpoint, five reusable cases are expected to fail by source inspection. No runtime RED or GREEN has been executed. Strict lint, Swift 6 syntax parsing and diff checks passed; app compilation and the focused isolated run remain pending explicit permission. This regression prepares common publication-gate acceptance; portfolio helper acceptance remains separate.++## T2382 owner handoff++Reusable store reservation can throw capacity before reaching the publication gate. The portfolio helpers must normalize that fault to a `QUERY_CAPACITY_EXCEEDED` machine error. Unknown or expired roots/cursors must become `INVALID_SNAPSHOT` or `INVALID_CURSOR`, without implicit recapture. Passing raw capacity to the common capture mapper currently labels it `storage_failure`, so owner tests must cover the pre-gate fault as well.++Both copied helper bodies remain unchanged `notImplemented` stubs. The descriptor alone now exactly matches owner commit `42d2d82b8596c5a0ac65887f83d25b5bc2bf3613`: one JSON-RPC object per POST, rejected wire arrays, and a distinct `mutate_tasks` application batch. This wording does not establish modern wire implementation acceptance.++Evidence and source-only patches are in `../t63-review-evidence/portfolio-wiring/` outside this repository: `expiry-readiness.md`, `expiry-followup.patch`, `descriptor-modern.patch`, import manifests, lint logs and SHA-256 manifest. The original `source-component.patch` remains unchanged.
diff --git a/specs/bounded-read-freshness/requirements.md b/specs/bounded-read-freshness/requirements.mdindex a8113399..f20380bc 100644--- a/specs/bounded-read-freshness/requirements.md+++ b/specs/bounded-read-freshness/requirements.md@@ -4,17 +4,19 @@ Transit agents need to know when a read describes only the endpoint's local view Review status: approved in full by the user in the parent conversation on 2026-10-03, including the 30,000 ms threshold, eight unfinished-read admission limit, diagnostics, and all decisions in the requirements review. Design, tasks and implementation are also approved by the user; approved scope and contracts remain binding. +Current production transport: the separately approved latest-only T2383 migration accepts one JSON-RPC object per POST and rejects wire arrays. Historical read-only/mixed wire-batch requirements below describe the earlier foundation contract and retained generic component evidence; they do not require array support in final production. A `query_tasks` identifier batch remains one supported read operation. This records an approved integration decision, not a new product approval gate.+ ## Proposed observable contract - Covered tools: `query_tasks` (single, batch, list, and cursor), `query_milestones`, and `get_projects`, including related comments/milestones required by their selected output. - Default policy: `refresh_if_needed`; optional `cached` policy skips import waiting. No separate refresh tool is required.-- Total read budget: 5,000 ms, measured from decoded read admission before executor queueing to an encoded success/error available to transport. Read-only JSON-RPC batches share their admission timestamp and must have a combined encoded response within this budget. For mixed read/write batches each read result's production is bounded while existing writes are preserved; combined HTTP delivery can wait on writes. The user approved this mixed-batch exception. Network upload/download and whole-process suspension are outside the server response guarantee.+- Total read budget: 5,000 ms, measured from decoded read admission before executor queueing to an encoded success/error available to transport. Final production uses the approved single-object POST contract. Network upload/download and whole-process suspension are outside the server response guarantee. - Freshness wait limit: 2,000 ms within the total budget. A relevant successful import is recent when its age at capture is at most 30,000 ms. - Compatibility: keep existing data payload shapes, selection semantics, and query cursor expiry/capacity behavior; add read metadata to the MCP result. Success data are the selected local view, not a claim of remote convergence. - Admission bound: at most eight unfinished covered read operations, including timed-out work still running; return `READ_BUSY` when that capacity is unavailable. This is an operation-count limit, not a total transient-memory limit. - Recommended latency evidence: server diagnostics distinguish queueing, refresh wait, capture/fetch, transformation, serialization, and batch aggregation, including correlated late completion/discard after a caller timeout. This diagnostics detail is approved. -The import recency threshold, admission bound, and latency diagnostics are approved requirements decisions. Exact metadata placement and supported import observation/refresh mechanisms are design decisions, constrained by compatibility and the behavior below. “JSON-RPC batch” means several protocol request elements; `query_tasks` batch mode is one read operation selecting multiple identifiers. Each covered request element is admitted separately in received order against the global available slots; excess elements receive `READ_BUSY`, while all elements keep the common decoded-batch admission timestamp.+The import recency threshold, admission bound, and latency diagnostics are approved requirements decisions. Exact metadata placement and supported import observation/refresh mechanisms are design decisions, constrained by compatibility and the behavior below. “JSON-RPC batch” in historical component evidence means several protocol request elements; `query_tasks` batch mode is one read operation selecting multiple identifiers. Final production rejects the former and preserves the latter. ## Non-Goals @@ -29,11 +31,11 @@ The import recency threshold, admission bound, and latency diagnostics are appro **Acceptance Criteria:** -1. <a name="1.1"></a>WHEN a covered read is admitted, the server SHALL produce its encoded success or defined error within 5,000 ms, including queueing, freshness waiting, local fetches, related-data capture, transformation, and serialization; for individual reads and read-only batches this includes making the response available to transport, while mixed-batch delivery follows the approved exception in 1.5. +1. <a name="1.1"></a>WHEN a covered read is admitted, the server SHALL produce its encoded success or defined error available to transport within 5,000 ms, including queueing, freshness waiting, local fetches, related-data capture, transformation, and serialization. 2. <a name="1.2"></a>IF a complete selected result cannot be returned within that budget, the server SHALL return `READ_TIMEOUT` with the exhausted phase when known and SHALL NOT later emit a second result for that request. 3. <a name="1.3"></a>WHEN eight unfinished covered reads already exist, the server SHALL reject additional covered reads with `READ_BUSY` within their total budget; timed-out work SHALL continue to count against capacity until it finishes. 4. <a name="1.4"></a>WHEN a response deadline expires while a local fetch is slow or blocked, the server SHALL still return the timeout within the total budget; a late result SHALL NOT create or replace a caller-visible snapshot. -5. <a name="1.5"></a>WHEN a batch contains only covered reads, the server SHALL make its complete encoded batch response available within 5,000 ms of batch admission, including aggregate serialization; IF successful-result encoding cannot finish within that deadline, the affected reads SHALL receive defined timeout results within the same deadline. WHEN a batch also contains writes, the server SHALL produce each covered read result within that deadline and disclose that combined delivery may wait for writes. +5. <a name="1.5"></a>WHEN an HTTP POST contains a JSON-RPC wire array, final production SHALL reject it under the already-approved latest-only protocol contract. Earlier whole-array deadline and mixed-delivery tests remain generic component evidence; they SHALL NOT establish an additional production wire path. 6. <a name="1.6"></a>WHEN timed-out work finishes or the read service stops, the server SHALL release its admission slot and discard unneeded capture/page data without publishing a late response or snapshot; retained valid pages SHALL keep existing byte and expiry limits. ### 2. Explicit local capture and freshness evidence
diff --git a/specs/bounded-read-freshness/routing-integration-plan.md b/specs/bounded-read-freshness/routing-integration-plan.mdindex 2657f653..d687405e 100644--- a/specs/bounded-read-freshness/routing-integration-plan.md+++ b/specs/bounded-read-freshness/routing-integration-plan.md@@ -50,20 +50,23 @@ Use latches and physical-completion receipts rather than arbitrary cleanup sleep ## Stage B: actual T2382 modules -After clean module delivery, wire the confirmed signatures returning `MCPPreparedToolRead`:+Source integration is now `c123210ac2ed749726391e16b39cfab81fed84f3`: exactly six portfolio-owned production files from `8478b17f554e9d7e93a3dd5b76fd1396f4295d07`, with every hash matching the owner's dependency manifest. Shared wiring, App/project isolation and tests were not replaced. Owner verification at `a3c2a705` passed 54 declarations/61 expanded cases with normal exit/drain; that is separate component evidence, not T63 integrated GREEN. Local lint, syntax and diff checks passed. No integrated app run has been performed.++The confirmed entrypoints return `MCPPreparedToolRead`: ```swift handlePortfolioSummary(request: MCPPortfolioSummaryRequest,- view: CapturedReadView,+ capture: MCPPreparedReadCapture?, operation: MCPReadOperation) throws -> MCPPreparedToolRead handleSnapshotTaskQuery(request: MCPSnapshotTaskQueryRequest,- view: CapturedReadView, operation: MCPReadOperation) throws -> MCPPreparedToolRead ``` T2382 supplies requests, definitions/descriptors, aggregation, projection, reusable retention and lifecycle hooks. T63 supplies common construction, generic policy-bound preparation, shared registration and outer encoding. Fresh helpers consume the same capsule and original frozen metadata; snapshot replay uses retained view/policy/fragments without recapture or import wait. Do not add RPC IDs to helper interfaces. -Final actual-module assertions include portfolio read classification and descriptor registration, `query_tasks` snapshot dispatch, declared physical-scope rejection, retained metadata/policy/expiry replay, actual reusable/ordinary participant coalescing and all-or-none publication, and lifecycle invalidation. Fixture GREEN cannot satisfy these assertions. Missing module delivery blocks Stage B acceptance only, not Stage A generic routing repair.+Final actual-module assertions include portfolio read classification and descriptor registration, `query_tasks` snapshot dispatch, declared physical-scope rejection, retained metadata/policy/expiry replay, actual reusable/ordinary participant coalescing and all-or-none publication, and lifecycle invalidation. Copied source or fixture GREEN cannot satisfy these assertions; the delivered component is now an input to Stage B verification.++The owner's prepared router suite at `c8e7ebb` contains four methods, including the 2,375-task case. It depends on `MCPPortfolioFixture.swift` and existing model-container/counter/fallback/HTTP test helpers; it has not been copied here. Its current request helper omits the protocol-version header, so the fixture owner must align that boundary with T2383's delivered modern adapter before final combined acceptance. Source/presentation and exact opaque-metadata lexical preservation require their separate modern acceptance assertions. Source delivery removes the implementation prerequisite; a parent-directed fixture handoff and exclusive test grant remain necessary for local Stage B verification. ## Stage C: modern wire ownership and final acceptance
diff --git a/specs/bounded-read-freshness/task13-acceptance.md b/specs/bounded-read-freshness/task13-acceptance.mdnew file mode 100644index 00000000..9f819a29--- /dev/null+++ b/specs/bounded-read-freshness/task13-acceptance.md@@ -0,0 +1,19 @@+# Tasks12/13 acceptance and diagnostics RED readiness++Tasks12/13 are complete for their selected integration scope. The parent-delivered Task17 handoff is `e45bc003`, with tested source `ec1b72136853a3b45587fb387feb382b58a83ec3`. Local component import `522a825` consumes exactly six production files and seventeen owner modern acceptance/router/support fixtures. Local harness alignment `2ea923b554c6b58fc30bdb45a8a07eb5dd94b4fc` changes only caller test support to use the delivered modern factory and encoders.++The immutable MCP audit finds 84 of 86 owner files byte-identical. Service and Coordinator differ only by retained optional disabled diagnostics seams; local MCPReadDiagnostics remains the inactive Task14 scaffold. No App/project/isolation source was replaced. Full source hashes, exception diffs and readiness are recorded in `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/task17-verified-consumption/manifest.json`.++| Acceptance boundary | Evidence |+| --- | --- |+| Generic admission/helper/routing, real listener restart, physical permits, private publication and write/maintenance preservation | Stage A: 14 methods/17 executions passed, separate isolated bootstrap smoke passed |+| Modern single-object protocol, discovery/routing/header/envelope, provider metadata and write result preservation | Previously verified API15 delivery; transferred production remains byte-identical |+| Actual portfolio modules, shared private-page factory, frozen comment-covered records/metadata, ordinary/reusable owner accounting, cursor terminal pins, retained expiry and actual router deadlines | Task17: 54 declarations/61 bodies reached in fourteen suites; 60 console passes, followed by one finalized corrected discovery pass |++Task17's combined run exited143 after sampling and cleanup; its result stayed unfinalized and summary extraction exited64. The separate focused corrected discovery run built, passed preflight/inventory and finalized one passing test with zero failures/skips/warnings. This is two-run acceptance, not a finalized full61 rerun. Parent verified artifact hashes and process drain. The original compile failure and both runtime evidence sets remain in the T2383 worktree. These are exact-source external acceptance results, not a newly executed local runtime run.++Task14 is now unblocked. Its prepared baseline originated at `ce0f1a9`; all diagnostics/caller assertions are retained. The caller harness now invokes the common all-page factory before reservation, the normal modern encoder with the original operation, and independent modern constant failure preparation. No diagnostic queue or instrumentation GREEN implementation was added.++The queued focused RED selectors are `TransitTests/MCPReadDiagnosticsTests` (five declarations/five bodies) followed by `TransitTests/MCPReadCallerContractTests` (five declarations/eight bodies). Total: ten declarations/thirteen bodies. Source inspection expects four diagnostic declarations and one description declaration to expose missing features; five control declarations/eight bodies should remain valid. These are expectations, not executed RED results. Strict lint, syntax parsing and diff checks passed. Execution requires the parent's exclusive slot and a freshly verified isolated host; T2384 currently holds the slot.++Task15 remains blocked by actual Task14 RED. Full platform/write parity, later client-readiness, caller-guide delivery, pre-push review and its authorized Pulsar step remain later obligations. No live/client activation, publishing, push, merge or deployment was performed. Production import applicability remains unproved, with the approved unknown/unavailable fallback.
diff --git a/specs/bounded-read-freshness/task14-red-handoff.md b/specs/bounded-read-freshness/task14-red-handoff.mdnew file mode 100644index 00000000..87839b1b--- /dev/null+++ b/specs/bounded-read-freshness/task14-red-handoff.md@@ -0,0 +1,19 @@+# Task14 diagnostics and caller-contract RED++Meaningful runtime RED is verified at immutable source `ffde7266813f7a80c7efac7f1487a611b4d656d8`. Xcode 27 guarded build-for-testing, signed isolated development-host preflight and exact compiled inventory passed. Only the two approved suites ran, serially, on separately restricted unit-test launch configurations.++| Suite | Declarations | Expanded bodies | Passing bodies | Failing bodies | Assertion issues |+| --- | ---: | ---: | ---: | ---: | ---: |+| MCPReadDiagnosticsTests | 5 | 5 | 1 | 4 | 14 |+| MCPReadCallerContractTests | 5 | 8 | 7 | 1 | 19 |+| Total | 10 | 13 | 8 | 5 | 33 |++The four diagnostic failures expose the inactive queue/writer and missing measured phase, late completion and historical aggregation events. The description failure exposes missing policy, evidence, deadline and retry guidance. All assertions remain intact. The disabled-sink control and four caller declarations passed, including all four policy arguments, exact frozen capture metadata, explicit retry after one storage failure and backoff while timed-out physical work remains admitted. There are zero skipped bodies, global/unknown issues or finalized runtime warnings.++Both test processes exited 65 normally because these expectations fail; both result bundles finalized successfully. No sampling or cleanup signals were needed. The worker verified runner/host absence and released the exclusive slot before extraction. Main independently confirmed the exact build, inventory and test runner PIDs absent. All 102 critical source hashes and 22 earlier artifacts remained unchanged.++The original build at `4cde372` and its first support-import retry at `9bc312e` both exited 65 before preflight/tests. They establish no behavioral RED. Exact owner support imports, seven bounded detached waits through a synchronous helper and two equivalent explicit optional-closure initializations repaired fixture compilation without changing production or assertions. Their logs, results and correction provenance remain preserved separately.++Final evidence is `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/task14-red-ffde726/`: `manifest.json`, `counts.json`, `executed-inventory-verification.json`, finalized summaries/bundles, source verification, preflight, commands and final drain. Its artifact manifest covers 3,853 retained files. Earlier compile-only evidence remains in `task14-red-4cde372`.++Task14 is complete; Rune reports Task15 as the sole ready stream and Task16 blocked. Task15 must implement bounded asynchronous diagnostics and accurate caller-facing descriptions, retaining the original correlation/deadline, physical worker accounting and atomic publication engine. Serialization measurement must bracket the actual operation-aware final RPC encoder; payload construction alone is insufficient. Historical wire-array aggregation remains component coverage because modern production rejects arrays. No GREEN source implementation or further app run is included in this handoff.
diff --git a/specs/bounded-read-freshness/task15-green-acceptance.md b/specs/bounded-read-freshness/task15-green-acceptance.mdnew file mode 100644index 00000000..cf4511ce--- /dev/null+++ b/specs/bounded-read-freshness/task15-green-acceptance.md@@ -0,0 +1,11 @@+# Task15 integrated GREEN acceptance++The dedicated T63 branch integrated verified cumulative T2383 d86f3ad at b8c81945a85b624a9e45e46f86a2cd9bad6e18f8. Common production source remains exact T2383; its diagnostics/constructor wiring and approved catalog READ_FAILED JSON repair are consumed rather than reimplemented. T63 preserves its original four diagnostic/caller/catalog fixture files and adds the already-reviewed seven modern fixture ports plus two bounded rendezvous/error-cleanup repairs. Strict full lint passes 532 files and changed Swift syntax checks pass.++Xcode27 build-for-testing, isolated signed development-host preflight and exact compiled enumeration passed. Original diagnostics/caller ten declarations/thirteen expanded bodies and catalog one declaration/six Cartesian tool/category cases executed successfully in three serial runs. All result bundles finalized PASS with normal zero exits; no failures, skips, expected failures, runtime warnings or global issues. All owned hosts/runners drained normally, without watchdog signals or retries.++Root independently queried finalized native summaries/global issues, checked the original argument matrices in console evidence, and rehashed all 183 indexed artifacts plus all 537 source inputs. Source stayed byte-identical throughout execution. Subsequent a523c4e caller/history documentation changes are separate from the tested b8 source pin. Evidence: `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/task15-integrated-green-d86/manifest.json` and `root-native-review.json`. Earlier focused READ_FAILED RED remains qualified by its unfinalized result; this actual GREEN finalized normally and does not relabel earlier evidence.++The caller guide is [docs/mcp-read-contract.md](../../docs/mcp-read-contract.md). It defines saved-only capture versus frozen replay, unknown import applicability, both policy defaults, inactive sync, total and refresh budgets, failure categories and bounded explicit retries. Current production remains latest-only object POST; historical aggregation tests do not advertise wire-array support.++Task15 is complete. [Task16 integrated native coverage](task16-green-acceptance.md) is now complete, with preserved stalled-attempt and sequencing qualifications. Pre-push publication remains separate. Finalized iOS/UI runs are reused only with the independent active-source/configuration equivalence proof; they do not validate macOS MCP source. No installed-client activation, CloudKit operation or deployment occurs. Parent has now forwarded explicit push/Claude disclosure approval alongside overnight merge authorization.
diff --git a/specs/bounded-read-freshness/task15-source-handoff.md b/specs/bounded-read-freshness/task15-source-handoff.mdnew file mode 100644index 00000000..8ec58edd--- /dev/null+++ b/specs/bounded-read-freshness/task15-source-handoff.md@@ -0,0 +1,33 @@+# Task15 source handoff++Historical source-preparation checkpoint at fa58dc0. Subsequent integrated GREEN is complete: see [task15-green-acceptance.md](task15-green-acceptance.md) and [Task16 acceptance](task16-green-acceptance.md). The readiness limitations below describe this earlier source-only checkpoint.++- Source: `fa58dc0d67aee5dd30e228f30b74ae89c8484953`, parent `48266589abad1133f8443aa99673c65a3f69c517`.+- Worktree: `/Users/arjen/Documents/Codex/2026-10-03/task/transit-t63`, branch `T-63/bounded-read-freshness`.+- Earlier actual RED: `ffde7266813f7a80c7efac7f1487a611b4d656d8`; see [Task14 acceptance](task14-red-handoff.md).++The bounded sink counts active plus queued scalar records and drops excess records. Its dedicated writer runs outside the sink and publication locks. Entries retain the original operation ID, tool, generation, admission, external deadline and internal cutoff through terminal selection, late discard and physical finalization. Measurements cover worker scheduling, the MainActor handoff, refresh policy/wait, saved capture, transformation, actual final RPC encoding and historical component assembly. Modern production still rejects wire arrays. Tool descriptions explain saved capture metadata, policy, import-evidence limits, frozen replay and explicit backoff. Capture identity, freshness evidence, pagination and publication behavior are preserved.++Implementation was delegated under the local make-it-so skill. Coordinator design-critic review identified and resolved the initial OSLog compiler expression, misplaced terminal bookkeeping, missing actor queue measurement, omitted log deadline context and ordinary/reusable query wording. Root independently verified all thirteen source hashes and nine artifact hashes. Original diagnostic/caller suites are byte-identical; transferred Handler/App and the ordinary snapshot store are unchanged.++## Verification readiness++Targeted strict SwiftLint (thirteen paths, no cache), Swift frontend syntax parsing and diff checks passed. Independent standalone OSLog typechecking passed using a private module cache; syntax parsing is not full actor/macro/type checking. No app/project build or runtime tests ran for this GREEN source. No T63 heavy job or retained test host is active; T2384 owns the shared heavy slot.++Next selected suites are `TransitTests/MCPReadDiagnosticsTests` and `TransitTests/MCPReadCallerContractTests`: ten declarations/thirteen expanded bodies, with their original assertions. Parent must grant the slot before guarded Xcode27 build/preflight/exact inventory and serial execution. Preserve finalized results, real counts, normal exit/drain evidence and source pins. Source readiness is not runtime acceptance.++Evidence is local: `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/task15-source-preparation/manifest.json` and `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/task15-root-review/review.json`.++## Owner application and remaining contract gap++Owned app dependencies install the bounded application sink. Production coordinators need two narrow owner patches: `handler-diagnostics.patch` supplies `readService?.diagnostics ?? .disabled` when the handler constructs its coordinator; `app-diagnostics.patch` supplies `reads.diagnostics` to the explicit app coordinator. They do not change admission, publication, preferences or lifecycle. Exact pre/post hashes and distinct local/recipient revisions are in `owner-patches.json`; both read-only application checks passed. Parent routes the handler patch to T2383 and the app patch to containment ownership. Neither file was directly edited.++A pre-existing error-contract gap remains: `MCPReadService.prepareFailure` selects `READ_FAILED` for project/milestone failures but emits only their message text. Machine categories still appear in failure metadata; no successful capture metadata is invented. Task15 does not silently alter this wire shape. Before integrated acceptance, a focused actual RED/GREEN repair must assert project/milestone storage, serialization and incoherence error codes as well as metadata categories. The exact defect is documented in `read-failed-wire-defect.md` beside the source manifest.++## Settings seam delivery++Separate sole-file commit `48266589abad1133f8443aa99673c65a3f69c517` adds the internal MainActor `subscriptionBroadcaster` getter returning the existing private broadcaster. Pre/post hashes are `c2fe9f43e2283c792a98691d349da34ff7fe5dcb3545e5fb23e2c5a40d1cf062` and `13cc27828c387fe4e62ce987ae593912ae61ae57d0e6096c3a6117f4dfcd3238`. Preferences, observer, storage and legacy APIs are unchanged. Independent exact-byte review, Swift parsing and diff checks passed. Patch and evidence: `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/settings-subscription-seam/`.++Keep this getter outside T2383's pinned Task18 RED until the permitted bundle. Later legacy Settings cleanup waits for T2383's exact registration symbols and coordinated common caller/test migration; no replacement stream engine or second observer was introduced.++No push, merge, deployment, live settings, publishing or routine phone upload occurred. Full platform validation and full pre-push-review including parent-controlled Pulsar publication remain later gates.
diff --git a/specs/bounded-read-freshness/task16-green-acceptance.md b/specs/bounded-read-freshness/task16-green-acceptance.mdnew file mode 100644index 00000000..985a5e25--- /dev/null+++ b/specs/bounded-read-freshness/task16-green-acceptance.md@@ -0,0 +1,29 @@+# Task16 integrated acceptance++Source checkpoint: `dbf3355d66ab51767fc97ef840dac2ead9c3573b`. Production source remains exactly the verified cumulative T2383 `d86f3ad`; the successor to T63 integration `b8c8194` changes only four explicit detached-task priorities in one macOS test fixture. Assertions, deadlines, synchronization and production code are unchanged. All four local review agents inspected that repair and found no issue.++## Finalized native coverage++Twenty-three selected finalized native result bundles cover the full configured macOS unit inventory: **2,189 declarations exactly once and 2,425 expanded executions passing**. There are zero failures, skips, expected failures, runtime warnings or legacy global issues. The selection excludes every unfinalized attempt and the superseded individual publication-method runs. Native declaration IDs, rather than console totals alone, establish the disjoint exhaustive union.++Root independently queried each actual native summary, test tree and legacy issue object, then reconciled the union to the compiled full inventory. Root also rehashed 704 earlier bounded-attempt artifacts, 5,626 successor artifacts and all 537 current source inputs. Evidence is outside Git under `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/task16-publication-qos-dbf3355/`: `manifest.json`, `coverage-union.json`, `global-issues-verification.json` and `artifact-sha256.json`. Independent review is in the sibling `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/root-final-verification/` directory: `native-final-review.json` and `hash-final-review.json`.++The successor packet's copied source hash table has correct current row hashes but retains two predecessor labels at its top. Root preserves those indexed bytes and supplies the explicit corrected successor pin in `root-final-verification/source-sha256-dbf3355.json`; no source mismatch was found.++## Preserved limitations and repair++Five attempts passed their bodies but failed native finalization: the original 2,171-declaration remainder, Chunk04, its third subgroup, the isolated publication suite, and one isolated publication method. Their samples, actual termination outcomes and unfinalized bundles remain preserved and excluded from acceptance. Scoped termination followed bounded post-body waits and exact owned-process verification. The root cause of the native finalization stalls remains unproved.++Individual isolation exposed two actual Thread Performance Checker priority inversions: a user-initiated semaphore waiter depended on a default-priority detached finalizer. The adjacent fixture repair sets four producer/gate task priorities explicitly to `userInitiated`. A new isolated signed build and all 11 publication declarations finalized normally, with the checker enabled and no warning messages. This verifies the repaired fixture; it does not retroactively establish the cause of earlier stalls.++Chunk05 began while Chunk04 was still waiting after its test bodies. Chunk05 itself finalized normally and contributes 300 declarations/387 executions, but retains that post-body overlap qualification. The worker subsequently enforced a fail-closed zero-owned-runner/host check before every inventory and runtime launch, and all remaining launches were serial with normal drain. No cosmetic rerun erases the sequencing deviation.++The new build's first invocation failed before compilation because its private temporary directory was absent. Its log and exit74 are preserved separately; directory preparation was corrected, and the successor build passed. This is not a test result. Strict signed development-host preflight passed with unit mode, exact host startup guards and no CloudKit, push or app-group entitlements. Full lint passed 532 files with zero violations. All owned heavy jobs are drained and the slot is released.++## Platform qualification and remaining workflow++Finalized iOS results (1,310 declarations/1,358 executions) and separate UI results (21/24) are reused from the actual T2383 tested artifact at `6bc20e16bd29137526d5f4a804e7c84829e6e073`. Root verified that all 20 changed Swift files are entirely macOS gated in both versions and that active iOS/build/configuration inputs are unchanged. The updated proof is `task16-reused-ios-evidence/source-equivalence-dbf3355.json`. This is qualified reuse, not new iOS execution or macOS evidence.++Task16 is complete. Live signed-store import applicability remains unsupported/unproved; approved `unknown`/null/`unavailable` behavior remains binding. T2383 installed-client compatibility is separately owner-deferred. No client activation, live-data repair, CloudKit operation or deployment occurs.++Full pre-push review and Pulsar publication completed before the original branch push. Parent subsequently forwarded explicit approval for pushes and external Claude sharing. Reconciliation on squash-merged main preserves all 537 compiled inputs byte-for-byte and all previous qualifications; the remaining unique tests/docs proceed through the updated scoped review and PR Pilot.
diff --git a/specs/bounded-read-freshness/tasks.md b/specs/bounded-read-freshness/tasks.mdindex 34829422..a6a5d0a6 100644--- a/specs/bounded-read-freshness/tasks.md+++ b/specs/bounded-read-freshness/tasks.md@@ -6,6 +6,8 @@ references: --- # T-63 bounded read freshness implementation +Current production scope follows the approved latest-only single-object POST contract: reject JSON-RPC arrays. Completed generic wire-batch/aggregation tasks and their evidence remain historical component verification, not final production routing requirements. Task-ID batches remain supported. Final tasks 12/13/16 use the modern adapter after its explicit ownership handoff; no product gate is reopened.+ - [x] 1. Define shared read contracts and injection seams on the merged foundation <!-- id:vh146y0 --> - Types/interfaces-only exemption. Before these edits, align only this clean dedicated branch to merged foundation 201205bd4e786c7f152d8f99006b37da7da888c7; preserve all other worktrees and the approved spec commits. Do not modify T2380. - Create macOS-gated explicitly nonisolated Sendable DTO/protocol definitions in Transit/Transit/MCP/Reads and optional MCPToolResult metadata. Define typed ReadCaptureScope, CaptureCompleteness, LocalRecordKey, CapturedReadView, MCPRetainedViewSource, MCPPreparedPublication validation/commit/discard, PreparedReadResult and PreencodedPublicationErrors.@@ -122,50 +124,53 @@ references: - Requirements: [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), [2.6](requirements.md#2.6), [3.1](requirements.md#3.1), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4) - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md -- [-] 12. Red: add full routing, lifecycle and T2382 integration tests <!-- id:vh146yb -->- - Extend MCPServer tests for single/read-only/mixed JSONRPC, invalid arguments, notifications/all-notification HTTP 202, stopped service and restart with unfinished work; assert final encoded bytes and publication match terminal selection.+- [x] 12. Red: add full routing, lifecycle and T2382 integration tests <!-- id:vh146yb -->+ - Extend MCPServer tests for single-object modern requests, invalid arguments, modern notification handling, wire-array rejection, stopped service and restart with unfinished work; assert final encoded bytes and publication match terminal selection. Earlier mixed/all-notification batch fixtures remain historical generic component evidence. - Add shared helper contract tests for T2382 descriptor registration, portfolio read classification, snapshotId dispatch, same view identity/evidence, scoped rejection and per-store batch aggregation. Use fixtures until parent supplies approved T2382 modules; integrated acceptance cannot pass on fixtures alone. - Write preservation regressions for merged write safety inputs/outputs/receipts/revisions, fallback-storage mutating allow-list and maintenance tools outside freshness scope. - Foundation tasks 1–9 never depend on these integration tests or on T2382 modules. Keep fixture-based red tests separate from actual-module final acceptance to avoid a circular cross-ticket gate.- - Evidence: Actual single-route RED compiled and ran (three methods/four device executions failed); saved-only/frozen metadata, five-second valid+invalid tool-domain availability and no late cursor-root publication are unwired. Additional admission/helper capability RED compiled and ran three methods/three device executions, all failed with zero skips; this proves missing interface binding only. Stage A generic admission/helper/router/lifecycle/private-publication/write-preservation fixtures are now implemented and verified GREEN on the isolated host (14 methods/17 executions). Actual T2382 module fixtures/final acceptance remain outstanding, so this mixed integration task remains in progress; see foundation-handoff.md.+ - Evidence: Historical single-route RED compiled and ran three methods/four failing executions; admission/helper capability RED ran three failing executions with zero skips. Stage A later verified generic admission/helper/router/lifecycle/private-publication/write preservation (14 methods/17 executions). Exact verified API15/Task17 consumption now closes the actual-module and modern-adapter remainder; Task17 preserves its unfinalized combined-run limits and separate finalized discovery correction. See task13-acceptance.md. - Blocked-by: vh146y6 (Green: implement independent deadline and physical admission coordination), vh146y8 (Green: implement shared publication domain and migrate ordinary retention), vh146ya (Green: migrate covered handler reads onto captured DTO projection) - Stream: 1 - Owner: t63-foundation-runtime - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [4.4](requirements.md#4.4), [5.3](requirements.md#5.3), [6.2](requirements.md#6.2) - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md -- [-] 13. Green: wire server lifecycle, common schemas and T2382 helpers <!-- id:vh146yc -->- - T63 alone edits MCPServer routes/batch/start/stop, TransitApp construction, handler init/common dispatch/readOnlyToolNames, MCPToolDefinitions existing readPolicy/common provider wiring and shared MCPTypes. Inject one process-lifetime coordinator/monitor/publication domain and capture builder.+- [x] 13. Green: wire server lifecycle, common schemas and T2382 helpers <!-- id:vh146yc -->+ - T63 owns shared MCPServer routes/start/stop, handler init/common dispatch/readOnlyToolNames, MCPToolDefinitions common provider wiring and shared MCPTypes until the explicit modern transfer. App/project/isolation changes require the containment owner's exact component; do not replace them. Inject one process-lifetime coordinator/monitor/publication domain and capture builder. - External prerequisite: parent delivers T2382 separate MCPToolHandler+PortfolioSummary, +SnapshotTaskQuery, MCPPortfolioToolDefinitions and retained-store hook modules matching approved interface. Wire query_tasks snapshotId dispatch to those helpers; do not duplicate their code or touch their worktree. Parent chooses clean dependency commit/cherry-pick after both task gates. - Run task 12 with actual modules. Keep write behavior/order, maintenance exclusion, encoded availability and atomic publication intact; never clear physical counts on generation changes.- - Partial evidence: Stage A generic routing/lifecycle/private-publication/write-preservation passed on the preflight-verified isolated development host: six sequential suites, 14 methods/17 device executions, zero failures/skips. Dedicated isolated bootstrap smoke passed separately (one test). Actual T2382 helpers and final T2383 modern adapter remain unverified Stage B/C prerequisites; this task is not complete. See foundation-handoff.md and external stage-a-isolated evidence.+ - Accepted evidence: Stage A established generic routing/lifecycle/private-publication/write preservation (14 methods/17 executions, separate bootstrap smoke). Verified API15 and Task17 close the actual-module/modern-adapter prerequisites. Task17 evidence combines 60 console passes from its unfinalized run with one finalized focused discovery pass; no finalized full61 run is claimed. Exact components are integrated at 522a825 with local disabled diagnostic seams preserved. See task13-acceptance.md for immutable source equivalence, coverage and remaining later gates. - Blocked-by: vh146yb (Red: add full routing, lifecycle and T2382 integration tests) - Stream: 1 - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [4.4](requirements.md#4.4), [5.3](requirements.md#5.3), [6.2](requirements.md#6.2) - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md -- [ ] 14. Red: add nonblocking diagnostics and executable caller-contract tests <!-- id:vh146yd -->+- [x] 14. Red: add nonblocking diagnostics and executable caller-contract tests <!-- id:vh146yd --> - Add diagnostic sink tests covering correlation and monotonic queue/refresh/capture/transform/serialization/batch durations, late completion/discard, bounded enqueue and simulated slow logging that cannot delay timeout/hold domain lock. - Add executable caller-example tests for new-query/new-capture versus cursor/same-capture, cached/default semantics, busy/timeout backoff, error mapping, no unbounded retry and mixed delivery caveat. Assert advertised MCP read descriptions expose these limits without changing payload shape. - Caller documentation creation remains an ancillary delivery requirement outside the skill's coding-only checklist; tests validate examples used in that guide.+ - Actual RED verified at ffde726: guarded build/preflight/exact compiled inventory passed, then both selected suites ran serially. All ten declarations/thirteen bodies executed: eight passing controls and five intended failing bodies, zero skips, 33 missing-feature assertions. Both xcresults finalized with no runtime warnings/global issues; runners/host drained normally and slot released before extraction. The two earlier compile-only attempts remain preserved. See task14-red-handoff.md. Task15 is now ready; no diagnostic GREEN implementation is included. - Blocked-by: vh146yc (Green: wire server lifecycle, common schemas and T2382 helpers) - Stream: 1 - Requirements: [4.1](requirements.md#4.1), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3) - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md -- [ ] 15. Green: implement bounded phase diagnostics and caller-facing tool descriptions <!-- id:vh146ye -->+- [x] 15. Green: implement bounded phase diagnostics and caller-facing tool descriptions <!-- id:vh146ye --> - Implement bounded nonblocking diagnostic sink/event values with original operation correlation retained through late finalizer; measure actual elapsed stages without synchronous timer-path filesystem work or speculative CloudKit attribution. - Update code-level MCPToolDefinitions read descriptions/error guidance to match approved metadata/policy/deadline/import/backoff contracts and task 14 examples. Run task 14, including blocked logging. - Caller-guide creation and publication follow-up are tracked outside this coding-only checklist; pass the validated executable examples to that separate delivery step.+ - Actual GREEN accepted at integrated b8c8194: original ten declarations/thirteen bodies plus catalog one declaration/six cases all passed. Three finalized native results have zero failures/skips/runtime warnings/global issues, normal zero exits and verified drain. Exact compiled inventory, original argument matrices, 537 source inputs and 183 evidence hashes were independently verified. Diagnostic constructors and READ_FAILED repair come from verified T2383 d86f3ad; caller guide is docs/mcp-read-contract.md. See task15-green-acceptance.md. - Blocked-by: vh146yd (Red: add nonblocking diagnostics and executable caller-contract tests) - Stream: 1 - Requirements: [4.1](requirements.md#4.1), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3) - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md -- [ ] 16. Validate the integrated read contract and merged write parity with Xcode27 <!-- id:vh146yf -->+- [x] 16. Validate the integrated read contract and merged write parity with Xcode27 <!-- id:vh146yf --> - Test task 2–15 suites with actual T2382 integration and saved-only/whole-versus-scoped capture. Include real router-return timing under blocked MainActor/slow large encoding, frozen pages, event/import faults, process-lifetime accounting and atomic same-store batch cases; retain precise supported/unsupported live-history result. - Coordinate exclusive heavy build/simulator slot with parent before make lint/full macOS and required iOS gates; serialize SwiftData suites using owning fixtures. Xcode 27 only. If Makefile builds fail, use Xcode MCP when available and report exact unavailable capability; no downgrade or concurrent heavy worker. - Testing-only task; repairs reuse the adjacent red/green unit pair for the affected component before rerunning targeted acceptance. Full pre-push-review including Pulsar is mandatory afterwards under its separate skill; parent approval controls otherwise unauthorized publication, with no merge/deploy.+ - Evidence: Finalized native union covers all 2,189 compiled declarations exactly once, with 2,425 expanded passing executions and zero failures/skips/expected failures/runtime warnings/global issues. Fixture-only QoS repair dbf3355 preserves assertions; all other 537-input source evidence is reconciled. Five stalled attempts are excluded and preserved; Chunk05 retains its post-body overlap qualification. Qualified unchanged-active-source iOS/UI results are reused. See task16-green-acceptance.md; final pre-push publication and the parent-controlled external-review gate remain separate. - Blocked-by: vh146ye (Green: implement bounded phase diagnostics and caller-facing tool descriptions) - Stream: 1 - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [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), [2.6](requirements.md#2.6), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3)
diff --git a/specs/bounded-read-freshness/typed-link-schema-owner-agreement.md b/specs/bounded-read-freshness/typed-link-schema-owner-agreement.mdnew file mode 100644index 00000000..d3cc6705--- /dev/null+++ b/specs/bounded-read-freshness/typed-link-schema-owner-agreement.md@@ -0,0 +1,13 @@+# T1734 schema registration: narrow T63 agreement++Reviewed inventory: `tests/typed-task-links/schema-registration-inventory.md` and its unapplied patch on the T1734 branch, inventory source `4459a964`. The parent verified task-1 local RED at `eaf5f461`; task-2 model/schema source follows the approved DAG. This review applies no factory patch or model definition.++T63 grants the schema-list-only addition in `Transit/TransitTests/TestModelContainer.swift`, default `init()`: append `TaskLinkOccurrence.self` and `TaskLinkRemovalEvidence.self` immediately after `MCPWriteReceipt.self`. No competing fixture edit exists. The two real definitions are committed in T1734 `794c155`; the application dependency is satisfied. The designated T1734 worker may apply that exact hunk now on its isolated branch at `e547e55` or its descendant. This is not a whole-file handoff and does not authorize editing the active T63 worktree.++Preserve the current UUID-named configuration, in-memory store, CloudKit `.none`, owning lifetime/retained containers, context construction, custom-schema initializer, rollback helper and counter fixtures. On later component integration, T63 applies the same list-only addition against its latest file after consuming the model definitions; it does not replace the fixture from the inventory checkpoint.++T63's `MCP/Reads` files consume an injected container and contain no model-container factory requiring this registration. No capture, history fence, canonical revision, snapshot, freshness or admission code changes belong in the registration patch. `ContainerFactory` already accepts its caller's schema and needs no extra registration.++Containment has already approved/applied the App and Makefile list additions in T1734 `55c88fa`. The remaining five paths outside T63's ownership are `Transit/TransitTests/MCPWritePersistenceProbeTests.swift`, `tests/mcp-write-probe/ServiceProbe.swift`, `CoordinatorProbe.swift`, `FoundationProbe.swift` and `Probe.swift`. Route those five list-only hunks to their write/probe owner; T63's one-path grant has no remaining ownership dependency. The probe `seed-old` five-model branch, six-entity pre-feature disk fixture and intentionally graph-free isolation migration fixture stay unchanged.++Application order is definitions first, owner-applied registration hunks second, then local schema/migration verification under a separately assigned exclusive test slot. No source application here, competing tests, real CloudKit account/schema operation, client activation or live-data mutation is authorized.
Final acceptance uses only 23 finalized selections with a disjoint union of all 2,189 declaration IDs. Five unfinalized attempts remain preserved with samples and scoped cleanup. Chunk05 contributes native PASS for 300 declarations / 387 executions but began during Chunk04 post-body finalization and retains that qualification. Later launches enforced a zero-owned-runner/host gate and normal drain. Independent root source table corrects two copied predecessor labels without altering indexed bytes.
Parent forwarded explicit user approval for private-repository pushes, sharing changes with Claude, and overnight merges after checks. Deployment/client activation/live-data repair remain excluded.