Transit branch T-2384/publication files 116 unique delta commits 5 macOS 2409 declarations / 3049 passing cases iOS units 1289 declarations / 1334 passing cases iOS UI 21 declarations / 24 passing cases

Pre-push review: T2384 batch task mutations

Unique T2384 feature delta reconciled onto merged main. Fresh native macOS and isolated iOS unit/UI acceptance passed.

At a glance

  • Fresh UI acceptance follows reviewed fixture corrections. The first 24-body run had four real fixture failures and a sampled runner-only finalization termination; that attempt is retained and not counted as clean acceptance.

  • One application tools/call with explicit saved-only dry run or ordered per-item execution; 1–50 unique task targets.

  • Per-item original receipts, revisions, text and retry evidence remain authoritative. Complete compact fallback bytes exist before effects.

  • Only the feature delta is reviewed here; the396-commit common foundation is already merged.

  • Native counts are explicit above; JUnit and line coverage were not fabricated.

Verdict

Ready to push

Four internal specialist reviews and independent root checks cleared the unique feature delta and preservation of main fixes. Fresh native full macOS and isolated iOS unit/UI runs finalized with zero failures/skips/runtime warnings and complete owned process drain. Explicit owner approval covers GitHub publication, configured Claude review and eligible squash merge. MacBook client activation is deferred and is not a merge blocker.

Review findings

3 raised · 3 fixed · 0 skipped

Jump to findings →

Tests

Pass rate: n/a

New tests: 130

Diff coverage: n/a

Jump to tests →

Commits

Three-level explanation

What changed

mutate_tasks lets a caller submit a plan containing 1–50 explicit task edits, status changes, or comments in one tool call. Each item names one task and supplies its own retry key. Update and status items also supply the revision they expect to edit. A task can appear only once in a plan.

Why it matters

A caller can preview a canonical description update and several duplicate closures before submitting them. Preview reads saved local records and describes normalized proposed effects without saving anything or reserving retry keys. Execution processes items in order and stops at the first unsuccessful or unverified result. Earlier successful items remain saved.

Key concepts

A revision detects edits made since an earlier read. A retry key identifies one exact operation in the originating local store. A retained receipt records the original result, so retrying identical arguments can return that result without repeating the effect. The batch has no shared receipt or all-or-nothing transaction: retrying the batch can replay its completed prefix and continue previously unattempted items.

Changes overview

The feature lives in MCP/BatchWrites. Its parser validates the entire bounded request before privately constructing an executable plan. It preserves original argument spellings for the existing protected write coordinator. A saved-read factory provides a private, autosave-disabled context for preview. The batch coordinator invokes the existing protected operation once per attempted item and advances only after authoritative committed evidence.

Implementation approach

The optional batch policy guards every relevant shared-context phase. Pending UI edits prevent new acceptance, mutation, save, rollback, or unresolved recovery through that context. Read-only retained terminal replay and key-conflict inspection remain available. Standalone writes keep their default policy. Comment validation is shared with the existing comment service, and status-plus-comment remains one protected transaction.

The batch result is one generated logical source. Every returned attempted-item result retains original text, optional isError, and available original JSON separately from the aggregate's classification. Common structured presentation adds task-identity link entries outside that source; the delivered common contract explicitly reports navigation unavailable pending its separate foundation. Before any effect, the handler prepares a complete response containing request correlation and compact original index/tool/key/UUID recovery mappings. Later encoding failure selects those ready bytes without running the encoder again.

Trade-offs

The bounded list reduces round trips while retaining per-item transactions. It does not provide a CloudKit transaction, automatic duplicate selection, or compensation. Saved-only preview avoids disturbing pending edits but cannot certify imported freshness or future write availability. Existing receipt replay preserves historical results even when the target later changes or disappears; it does not certify current canonical contents.

Technical deep dive

Shape validation rejects unknown fields, safety-format errors, wrong JSON types, normalized UUID collisions, duplicate tool/key pairs, and exact caller-ID collisions before any item is attempted. Numeric integer fields are checked from original decimal tokens, avoiding floating-point rounding. Domain strings and conditional status-comment authors retain existing per-item validation semantics. Original UUID argument spelling stays part of T2380 payload binding.

The evidence classifier verifies receipt version, tool/key identity, types, target identity, revisions, terminal dates, and optional error flag before treating an item as committed. Unreadable or unsupported evidence cannot prove no effect. Cancellation is observed between attempts; it does not undo committed effects or turn a caller timeout into observed cancellation. An unstarted item has no acceptance attributable to this submission.

Original retained JSON is inserted through validated raw fragments rather than reparsed through Foundation dictionaries. Missing and null fields, unknown fields, numeric lexemes, and exact original text remain preserved. The common parser's 32-container cap can reject a generated aggregate whose individually readable nested receipts were shallower; that post-effect failure selects the preencoded shallow fallback. Compact fallback excludes giant caller labels, raw records, and entity links. Normal result context may carry explicit task UUID source positions while the prepared fallback context stays link-free.

Architecture impact

The application batch remains one modern tools/call, outside protected single-operation key registration, covered-read admission, snapshot retention, and the five-second read contract. Its router must preserve the original JSON argument subtree before the older Any bridge. App-owned services, coordinator, and container are injected; no second receipt engine, guard format, or recovery action is introduced.

Operational limits

Retry guarantees are local-store and retention scoped. Callers retain original arguments, keys, returned expiries, and original submission time when the first response is lost. Removed or expired receipts do not prove the original effect never happened; a removed key can execute as new under the existing write contract. Unknown commitment requires reconciliation with original keys, never automatic key rotation. A retained canonical update may replay while duplicate closures remain unattempted, so callers needing a current canonical-state condition reconcile it before those closures.

Important changes — detailed

Batch request: validate the entire bounded plan before effects

Transit/Transit/MCP/BatchWrites/MCPBatchTaskRequest.swift

Why it matters. A malformed later item cannot leave an earlier write behind. Exact numeric tokens and normalized UUID collisions remain shape checks.

What to look at. MCPBatchTaskRequest.parse and private request construction

Takeaway. Carry lossless parsed values until the safety boundary has admitted every item.
Rationale. Approved AC1.1–1.3 and ADR admission boundary.

Shared write coordinator: guard batch clean phases and preserve replay

Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift

Why it matters. New batch operations cannot save or roll back pending UI edits; retained terminal replay still works without live reads.

What to look at. Optional MCPBatchWritePolicy gates and dirty retained inspection

Takeaway. An opt-in policy can strengthen one provider without changing standalone defaults.
Rationale. Approved saved-only and dirty-context amendment; reuse existing receipt/recovery authority.

Batch result: retain exact original item evidence

Transit/Transit/MCP/BatchWrites/MCPBatchTaskResult.swift

Why it matters. Unknown fields, numeric lexemes, missing/null distinctions, raw text and optional flags survive the new aggregate.

What to look at. execution originalResult raw fragment and independent aggregate error flag

Takeaway. Separate immutable source evidence from supplemental presentation.
Rationale. AC4.3/5.2–5.4 and coordinated T2383 source contract.

Prepared response: deliver recovery bytes without a second encoder

Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreparedResponse.swift

Why it matters. Encoding can fail after a durable commit; compact recovery cannot invent no-effect certainty or fresh-key permission.

What to look at. prepare before effects and immutable ready-byte selection

Takeaway. Prepare the complete correlated deliverable before starting mutations.
Rationale. Approved Q8 and full preeffect fallback decision; depth32 and giant-itemId fixtures.

Modern route: dispatch one application batch before the Any bridge

Transit/Transit/MCP/MCPServer+Routing.swift

Why it matters. Exact input safety values survive; batch adds no outer receipt, covered-read admission, retention or deadline.

What to look at. applicationBatch interception, owning container injection and explicit normal task-identity positions

Takeaway. Tool batching and JSON-RPC transport batching are separate contracts.
Rationale. AC1.1/6.4 and noncircular delivered T2383/T63 integration seam.

Key decisions

Independent protected items; no whole-batch receipt

Reuse T2380’s tool/key/store scope and original argument binding. Ordered execution advances only on authoritative committed evidence; earlier effects stay saved.

Saved-only preview and opt-in clean-phase policy

A private autosave-disabled context observes saved records. Dirty retained terminal inspection remains available without repair; new effects and unresolved recovery are blocked while unrelated edits are pending.

Prepared full fallback and collision-free presentation

Prepare request-correlated bytes before dispatch. Normal source retains full item originals; compact fallback strips labels/raw records/links and permits only original index/tool/key/UUID recovery. Task-link entries remain explicitly unavailable under the common navigation contract.

Review findings

SeverityAreaFindingResolution
minorRepository MCP guideCLAUDE.md lists 12 tools and omits mutate_tasks.Update to 13 tools and document batch-owned implementation boundary.
minorSpec overview indexThree-way documentation merge preserved detail section but omitted feature index row.Restore Done batch index row after pinned native verification.
majorExisting iOS UI fixturesFirst fresh UI run exposed three direct-toolbar assumptions and a portrait remote-query/predicate timeout.Use existing overflow-aware Settings helper and assert a captured portrait frame without weakening layout requirements. Full UI suite rerun separately; first failed/unfinalized attempt retained.

Tests

Source: local run at 2026-10-04T23:07:13.707250+00:00 · snapshot b90e6f84255f01c3de39104ea59a9aa0c77c7acb

Baseline: none

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

Coverage scope: as the project configures it

No test results

The test runner could not be detected.

New and removed tests

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

Blast radius

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

Dependents none found Changed Dependencies none found . Transit/Transit Transit/Transit/MCP …ansit/Transit/MCP/BatchWrites Transit/Transit/MCP/Results Transit/Transit/MCP/Writes Transit/Transit/Services Transit/TransitTests Transit/TransitUITests tests/batch-task-mutations tests/development-isolation MakefileMakefile Transit/Transit/TransitApp.swift…nsit/Transit/TransitApp.swift Transit/Transit/MCP/MCPServer+Routing.swift…t/MCP/MCPServer+Routing.swift Transit/Transit/MCP/MCPToolDefinitions.swift…/MCP/MCPToolDefinitions.swift Transit/Transit/MCP/MCPToolHandler.swift…nsit/MCP/MCPToolHandler.swift Transit/Transit/MCP/BatchWrites/MCPBatchModernProvider.swift…/MCPBatchModernProvider.swift Transit/Transit/MCP/BatchWrites/MCPBatchSavedReadContext.swift…CPBatchSavedReadContext.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskContext.swift…tes/MCPBatchTaskContext.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskCoordinator+Execution.swift…skCoordinator+Execution.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskCoordinator.swift…MCPBatchTaskCoordinator.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskEvidence.swift…es/MCPBatchTaskEvidence.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskEvidenceValidation.swift…hTaskEvidenceValidation.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskFallback.swift…es/MCPBatchTaskFallback.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskHandler.swift…tes/MCPBatchTaskHandler.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskInputArguments.swift…BatchTaskInputArguments.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskInputIdentity.swift…PBatchTaskInputIdentity.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskOutputSchema.swift…CPBatchTaskOutputSchema.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreparedResponse.swift…tchTaskPreparedResponse.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreview.swift…tes/MCPBatchTaskPreview.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreviewHandler.swift…BatchTaskPreviewHandler.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskRequest.swift…tes/MCPBatchTaskRequest.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskResponse.swift…es/MCPBatchTaskResponse.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskResult.swift…ites/MCPBatchTaskResult.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskSchema.swift…ites/MCPBatchTaskSchema.swift Transit/Transit/MCP/BatchWrites/MCPBatchToolDefinition.swift…/MCPBatchToolDefinition.swift Transit/Transit/MCP/BatchWrites/MCPBatchWritePolicy.swift…tes/MCPBatchWritePolicy.swift Transit/Transit/MCP/BatchWrites/MCPTaskMutationValidation.swift…PTaskMutationValidation.swift Transit/Transit/MCP/Results/MCPModernProviderBinding.swift…CPModernProviderBinding.swift Transit/Transit/MCP/Writes/MCPWriteCommand.swift…/Writes/MCPWriteCommand.swift Transit/Transit/MCP/Writes/MCPWriteCoordinator+Outcomes.swift…iteCoordinator+Outcomes.swift Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift…tes/MCPWriteCoordinator.swift Transit/Transit/Services/CommentInputValidation.swift…/CommentInputValidation.swift Transit/Transit/Services/CommentService.swift…Services/CommentService.swift Transit/TransitTests/MCPBatchTaskAggregateTests.swift…BatchTaskAggregateTests.swift Transit/TransitTests/MCPBatchTaskCoordinatorBaselineTests.swift…oordinatorBaselineTests.swift Transit/TransitTests/MCPBatchTaskCoordinatorDurabilityTests.swift…rdinatorDurabilityTests.swift Transit/TransitTests/MCPBatchTaskCoordinatorFixture.swift…hTaskCoordinatorFixture.swift Transit/TransitTests/MCPBatchTaskCoordinatorSequenceFixtures.swift…dinatorSequenceFixtures.swift Transit/TransitTests/MCPBatchTaskCoordinatorTests.swift…tchTaskCoordinatorTests.swift Transit/TransitTests/MCPBatchTaskEncodingTests.swift…PBatchTaskEncodingTests.swift Transit/TransitTests/MCPBatchTaskEvidenceBoundaryTests.swift…skEvidenceBoundaryTests.swift Transit/TransitTests/MCPBatchTaskEvidenceTests.swift…PBatchTaskEvidenceTests.swift Transit/TransitTests/MCPBatchTaskExecutionAdapterTests.swift…skExecutionAdapterTests.swift Transit/TransitTests/MCPBatchTaskModernFixture.swift…PBatchTaskModernFixture.swift Transit/TransitTests/MCPBatchTaskModernTests.swift…MCPBatchTaskModernTests.swift Transit/TransitTests/MCPBatchTaskPreparedResponseTests.swift…skPreparedResponseTests.swift Transit/TransitTests/MCPBatchTaskPreviewFixture.swift…BatchTaskPreviewFixture.swift Transit/TransitTests/MCPBatchTaskPreviewTests.swift…CPBatchTaskPreviewTests.swift Transit/TransitTests/MCPBatchTaskRequestBoundaryTests.swift…askRequestBoundaryTests.swift Transit/TransitTests/MCPBatchTaskRequestFixtures.swift…atchTaskRequestFixtures.swift Transit/TransitTests/MCPBatchTaskRequestTests.swift…CPBatchTaskRequestTests.swift Transit/TransitTests/MCPBatchTaskResponseTests.swift…PBatchTaskResponseTests.swift Transit/TransitTests/MCPBatchTaskResultFixtures.swift…BatchTaskResultFixtures.swift Transit/TransitTests/MCPBatchTaskSafetyFixture.swift…PBatchTaskSafetyFixture.swift Transit/TransitTests/MCPBatchTaskSafetyTests.swift…MCPBatchTaskSafetyTests.swift Transit/TransitTests/MCPBatchTaskSchemaTests.swift…MCPBatchTaskSchemaTests.swift Transit/TransitTests/MCPMaintenanceHandlerTests.swift…MaintenanceHandlerTests.swift Transit/TransitTests/MCPMilestoneToolTests.swift…s/MCPMilestoneToolTests.swift Transit/TransitTests/MCPModernResultFixture.swift…/MCPModernResultFixture.swift Transit/TransitTests/MCPTaskMutationSavedStatusBoundaryTests.swift…avedStatusBoundaryTests.swift Transit/TransitTests/MCPTaskMutationValidationTests.swift…MutationValidationTests.swift Transit/TransitTests/MCPTestHelpers.swift…sitTests/MCPTestHelpers.swift Transit/TransitTests/MCPToolHandlerTests.swift…sts/MCPToolHandlerTests.swift Transit/TransitUITests/TransitUITests.swift…tUITests/TransitUITests.swift tests/batch-task-mutations/cleanup_preview_fixtures.py…s/cleanup_preview_fixtures.py tests/development-isolation/DisposableStorePath.swift…ion/DisposableStorePath.swift tests/development-isolation/MigrationProbe.swift…solation/MigrationProbe.swift tests/development-isolation/run.py…/development-isolation/run.py
addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

116 files: 87 code · 29 docs. Click to expand.

Code (87)

Makefile Modified +4 / -4
diff --git a/Makefile b/Makefileindex 8401a141..ceb44b76 100644--- a/Makefile+++ b/Makefile@@ -157,7 +157,7 @@ test-development-isolation: prepare-cache-dirs test-development-configuration 	xcrun swiftc -parse-as-library -default-isolation MainActor -module-cache-path $(CLANG_MODULE_CACHE) \ 		$(MCP_PROBE_MODELS) Transit/Transit/MCP/Writes/{MCPCanonicalJSON,MCPRecordRevision}.swift \ 		Transit/Transit/Services/{AppPersistencePolicy,IsolatedPersistenceConfiguration}.swift \-		tests/development-isolation/MigrationProbe.swift \+		tests/development-isolation/{DisposableStorePath,MigrationProbe}.swift \ 		-o $(DERIVED_DATA)/isolated-migration-probe 	xcrun swiftc -parse-as-library -default-isolation MainActor -module-cache-path $(CLANG_MODULE_CACHE) \ 		$(MCP_PROBE_MODELS) \@@ -201,12 +201,12 @@ test-mcp-write-guards: prepare-cache-dirs test-mcp-write-foundation: prepare-cache-dirs 	xcrun swiftc $(MCP_PROBE_SWIFT_FLAGS) -parse-as-library -default-isolation MainActor -module-cache-path $(CLANG_MODULE_CACHE) \ 		$(MCP_PROBE_MODELS) Transit/Transit/MCP/Writes/{MCPCanonicalJSON,MCPRecordSnapshot,MCPRecordRevision,MCPLocalReservationStore,MCPWriteReceiptStore}.swift \-		Transit/Transit/Services/CommentService.swift Transit/Transit/Extensions/ModelContext+{Save,SafeRollback}.swift \+		Transit/Transit/Services/CommentInputValidation.swift Transit/Transit/Services/CommentService.swift Transit/Transit/Extensions/ModelContext+{Save,SafeRollback}.swift \ 		tests/mcp-write-probe/FoundationProbe.swift -o $(DERIVED_DATA)/mcp-write-foundation-probe 	$(DERIVED_DATA)/mcp-write-foundation-probe  .PHONY: test-mcp-write-services-MCP_PROBE_SERVICES = Transit/Transit/Services/{TaskService,TaskService+Error,MilestoneService,MilestoneService+Error,ProjectService,CommentService,ModelFetching,UsedDisplayIDs,DisplayIDAllocator,DisplayIDRecordLookup,CloudKitCounterStore,CreationProjectValidator,TaskCreationMilestoneValidator,ProjectNameReconciler,MilestoneNameReconciler,StatusEngine,PersistenceAvailability,ContainerFactory}.swift+MCP_PROBE_SERVICES = Transit/Transit/Services/{TaskService,TaskService+Error,MilestoneService,MilestoneService+Error,ProjectService,CommentInputValidation,CommentService,ModelFetching,UsedDisplayIDs,DisplayIDAllocator,DisplayIDRecordLookup,CloudKitCounterStore,CreationProjectValidator,TaskCreationMilestoneValidator,ProjectNameReconciler,MilestoneNameReconciler,StatusEngine,PersistenceAvailability,ContainerFactory}.swift MCP_PROBE_DEPENDENCIES ?= $(DERIVED_DATA)/Build/Products/Debug .PHONY: format-mcp-write format-mcp-write:@@ -248,7 +248,7 @@ test-mcp-write-coordinator: prepare-cache-dirs  test-mcp-write-services: prepare-cache-dirs 	xcrun swiftc $(MCP_PROBE_SWIFT_FLAGS) -parse-as-library -default-isolation MainActor -module-cache-path $(CLANG_MODULE_CACHE) \-		$(MCP_PROBE_MODELS) Transit/Transit/Services/{TaskService,TaskService+Error,MilestoneService,MilestoneService+Error,ProjectService,CommentService,ModelFetching,UsedDisplayIDs,DisplayIDAllocator,DisplayIDRecordLookup,CloudKitCounterStore,CreationProjectValidator,TaskCreationMilestoneValidator,ProjectNameReconciler,MilestoneNameReconciler,StatusEngine,PersistenceAvailability,ContainerFactory}.swift \+		$(MCP_PROBE_MODELS) Transit/Transit/Services/{TaskService,TaskService+Error,MilestoneService,MilestoneService+Error,ProjectService,CommentInputValidation,CommentService,ModelFetching,UsedDisplayIDs,DisplayIDAllocator,DisplayIDRecordLookup,CloudKitCounterStore,CreationProjectValidator,TaskCreationMilestoneValidator,ProjectNameReconciler,MilestoneNameReconciler,StatusEngine,PersistenceAvailability,ContainerFactory}.swift \ 		Transit/Transit/Intents/{IntentHelpers,IntentError}.swift Transit/Transit/Extensions/ModelContext+{Save,SafeRollback}.swift \ 		tests/mcp-write-probe/ServiceProbe.swift -o $(DERIVED_DATA)/mcp-write-service-probe 	$(DERIVED_DATA)/mcp-write-service-probe
Transit/Transit/MCP/BatchWrites/MCPBatchModernProvider.swift Added +41 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchModernProvider.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchModernProvider.swiftnew file mode 100644index 00000000..5360ecb8--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchModernProvider.swift@@ -0,0 +1,41 @@+#if os(macOS)+import Foundation++/// One application batch in one admitted tools/call. Transport notification and+/// capability checks stay with the modern owner; no read deadline or retention.+@MainActor enum MCPBatchModernProvider {+    static func call(_ modern: MCPModernRequest, handler: MCPToolHandler) async throws -> MCPResultResponseSelection {+        guard case .callTool(let name, .applicationBatch) = modern.method,+              name.utf8.elementsEqual("mutate_tasks".utf8) else { throw MCPResultBoundaryError.unsupportedEvidence }+        let arguments: MCPJSONValue+        if case .object(let members) = modern.params,+           members.filter({ $0.name.utf8.elementsEqual("arguments".utf8) }).count == 1,+           let supplied = MCPBatchTaskInputValue.member("arguments", in: members) {+            arguments = supplied+        } else { arguments = .null }+        switch try MCPBatchTaskRequest.parse(validatedValue: arguments) {+        case .invalid(let diagnostics):+            let source = try MCPBatchTaskResult.invalidInput(diagnostics)+            return .normal(try MCPResultProviderSelection.encode(outcome: .init(source: source,+                context: .init(tool: "mutate_tasks", semanticFailure: nil, mutationRecovery: nil, entityPositions: [])),+                id: modern.id, metadata: nil))+        case .valid(let request):+            if request.mode == .dryRun {+                let report = try handler.batchPreview(request)+                let source = try MCPBatchTaskResult.preview(request, report: report)+                return .normal(try MCPResultProviderSelection.encode(outcome: .init(source: source,+                    context: MCPBatchTaskContext.normal(request, recovery: nil)), id: modern.id, metadata: nil))+            }+            let items = request.items.map {+                MCPBatchRecoveryItem(index: $0.index, itemId: $0.itemId, operation: $0.operation,+                    originalKey: .init(tool: $0.command.tool, idempotencyKey: $0.command.key),+                    targetTaskId: $0.targetTaskId)+            }+            let prepared = try MCPBatchTaskPreparedResponse.prepare(id: modern.id, items: items, metadata: nil)+            return try await MCPBatchTaskResponse.execute(request, prepared: prepared,+                executor: { item in try await handler.executeBatchItem(item) },+                encodeOutcome: handler.batchResultEncoder ?? MCPResultProviderSelection.encode)+        }+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchSavedReadContext.swift Added +21 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchSavedReadContext.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchSavedReadContext.swiftnew file mode 100644index 00000000..1781ad8f--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchSavedReadContext.swift@@ -0,0 +1,21 @@+#if os(macOS)+import Foundation+import SwiftData++/// Owns a private, non-saving context for one synchronous preview observation.+/// Fetch descriptors in preview validators must exclude pending changes; the+/// shared UI context is never fetched, refreshed, saved or rolled back here.+@MainActor enum MCPBatchSavedReadContext {+    static func withContext<Result>(+        container: ModelContainer, persistence: PersistenceAvailability,+        _ body: @MainActor (ModelContext) throws -> Result+    ) throws -> Result {+        guard !persistence.isFallbackStorageActive else {+            throw MCPWriteFailure("PERSISTENCE_UNAVAILABLE", PersistenceAvailability.unavailableHint)+        }+        let context = ModelContext(container)+        context.autosaveEnabled = false+        return try body(context)+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskContext.swift Added +12 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskContext.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskContext.swiftnew file mode 100644index 00000000..f1d1bc39--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskContext.swift@@ -0,0 +1,12 @@+#if os(macOS)+import Foundation++@MainActor enum MCPBatchTaskContext {+    static func normal(_ request: MCPBatchTaskRequest, recovery: MCPMutationRecoveryContext?) -> MCPResultContext {+        MCPResultContext(tool: "mutate_tasks", semanticFailure: nil, mutationRecovery: recovery,+            entityPositions: request.items.map {+                .init(entityType: .task, sourcePath: "/items/\($0.index)/taskId")+            })+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskCoordinator+Execution.swift Added +25 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskCoordinator+Execution.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskCoordinator+Execution.swiftnew file mode 100644index 00000000..9c10628c--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskCoordinator+Execution.swift@@ -0,0 +1,25 @@+#if os(macOS)+import Foundation++extension MCPBatchTaskCoordinator {+    /// Captures the stop fact for this invocation only. Receipt replay does not+    /// manufacture a pending-edit signal or fetch current domain records.+    convenience init(+        preparedResponse: MCPBatchTaskPreparedResponse, writeCoordinator: MCPWriteCoordinator,+        observedCancellation: @escaping @MainActor () -> Bool = { Task.isCancelled }+    ) {+        self.init(preparedResponse: preparedResponse, executor: { item in+            var pendingEditsStop = false+            let policy = MCPBatchWritePolicy(onPendingEditsStop: { pendingEditsStop = true })+            let result = await writeCoordinator.execute(tool: item.command.tool,+                arguments: item.command.arguments, batchPolicy: policy)+            guard result.content.count == 1, let text = result.content.first?.text else {+                throw MCPResultBoundaryError.unsupportedEvidence+            }+            let source = try MCPResultAdapter.source(text: text, isError: result.isError,+                origin: .retainedJSON, evidence: .established)+            return Execution(source: source, pendingEditsStop: pendingEditsStop)+        }, observedCancellation: observedCancellation)+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskCoordinator.swift Added +135 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskCoordinator.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskCoordinator.swiftnew file mode 100644index 00000000..206a825c--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskCoordinator.swift@@ -0,0 +1,135 @@+#if os(macOS)+import Foundation++/// Ordered execution over original protected-command evidence. The complete+/// prepared fallback capability is required before any item can be dispatched.+@MainActor final class MCPBatchTaskCoordinator {+    nonisolated struct Execution: Sendable {+        let source: MCPResultSource+        let pendingEditsStop: Bool++        init(source: MCPResultSource, pendingEditsStop: Bool = false) {+            self.source = source+            self.pendingEditsStop = pendingEditsStop+        }+    }++    nonisolated enum State: String, Sendable { case attempted, notAttempted = "not_attempted" }+    nonisolated enum Reason: String, Sendable {+        case itemResult = "item_result", evidenceUnavailable = "evidence_unavailable"+        case pendingEdits = "pending_edits", cancelled+    }+    nonisolated struct Blocker: Sendable, Equatable {+        let index: Int+        let itemId: String+    }+    nonisolated struct Stop: Sendable {+        let reason: Reason+        let nextUnstartedIndex: Int+        let blocker: Blocker?+    }+    nonisolated struct Entry: Sendable {+        let index: Int+        let itemId: String+        let operation: String+        let originalKey: String+        let taskID: UUID+        let state: State+        let originalResult: MCPResultSource?+    }+    nonisolated struct Report: Sendable {+        let summary: String+        let confirmedCommittedCount: Int+        let entries: [Entry]+        let stop: Stop?+        let observedCancellation: Bool+        let isError: Bool?+    }+    nonisolated enum Error: Swift.Error, Sendable, Equatable { case preparedRequestMismatch, executeModeRequired }+    typealias Executor = @MainActor (MCPBatchTaskRequest.Item) async throws -> Execution+    private let preparedResponse: MCPBatchTaskPreparedResponse+    private let executor: Executor+    private let observedCancellation: @MainActor () -> Bool++    init(preparedResponse: MCPBatchTaskPreparedResponse, executor: @escaping Executor,+         observedCancellation: @escaping @MainActor () -> Bool = { Task.isCancelled }) {+        self.preparedResponse = preparedResponse+        self.executor = executor+        self.observedCancellation = observedCancellation+    }++    func run(_ request: MCPBatchTaskRequest) async throws -> Report {+        guard request.mode == .execute else { throw Error.executeModeRequired }+        try validatePreparedIdentity(request)+        var entries = request.items.map { entry($0, source: nil, attempted: false) }+        var committed = 0+        var cancelled = false+        for item in request.items {+            cancelled = observedCancellation() || cancelled+            if cancelled {+                return report("interrupted", committed: committed, entries: entries,+                    stop: Stop(reason: .cancelled, nextUnstartedIndex: item.index, blocker: nil), cancelled: true)+            }+            let execution: Execution+            do { execution = try await executor(item) } catch {+                entries[item.index] = entry(item, source: nil, attempted: true)+                cancelled = observedCancellation() || cancelled+                return stopped(item, reason: .evidenceUnavailable, committed: committed,+                               entries: entries, cancelled: cancelled)+            }+            entries[item.index] = entry(item, source: execution.source, attempted: true)+            let comment = item.command.arguments["comment"] as? String+            let assessment = MCPBatchTaskEvidence.assess(source: execution.source,+                operation: item.operation, originalKey: item.command.key, taskID: item.targetTaskId,+                requiresStatusComment: item.operation == "update_task_status" &&+                    comment?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false)+            cancelled = observedCancellation() || cancelled+            switch assessment.kind {+            case .committed: committed += 1+            case .unavailable:+                return stopped(item, reason: .evidenceUnavailable, committed: committed,+                               entries: entries, cancelled: cancelled)+            case .itemResult:+                return stopped(item, reason: execution.pendingEditsStop ? .pendingEdits : .itemResult,+                               committed: committed, entries: entries, cancelled: cancelled)+            }+        }+        return report("all_committed", committed: committed, entries: entries, stop: nil, cancelled: cancelled)+    }++    private func validatePreparedIdentity(_ request: MCPBatchTaskRequest) throws {+        guard case .applicationBatch(let recovery) = preparedResponse.context.mutationRecovery,+              recovery.count == request.items.count else { throw Error.preparedRequestMismatch }+        for (index, pair) in zip(request.items, recovery).enumerated() {+            let (item, retained) = pair+            guard item.index == index, retained.index == index,+                  retained.operation.utf8.elementsEqual(item.operation.utf8),+                  retained.originalKey.tool.utf8.elementsEqual(item.command.tool.utf8),+                  retained.originalKey.idempotencyKey.utf8.elementsEqual(item.command.key.utf8),+                  retained.targetTaskId == item.targetTaskId else { throw Error.preparedRequestMismatch }+        }+    }++    private func entry(_ item: MCPBatchTaskRequest.Item, source: MCPResultSource?, attempted: Bool) -> Entry {+        Entry(index: item.index, itemId: item.itemId, operation: item.operation, originalKey: item.command.key,+              taskID: item.targetTaskId, state: attempted ? .attempted : .notAttempted, originalResult: source)+    }++    private func stopped(+        _ item: MCPBatchTaskRequest.Item, reason: Reason, committed: Int, entries: [Entry], cancelled: Bool+    ) -> Report {+        report(reason == .evidenceUnavailable ? "evidence_unavailable" : "stopped",+            committed: committed, entries: entries,+            stop: Stop(reason: reason, nextUnstartedIndex: item.index + 1,+                       blocker: Blocker(index: item.index, itemId: item.itemId)), cancelled: cancelled)+    }++    private func report(+        _ summary: String, committed: Int, entries: [Entry], stop: Stop?, cancelled: Bool+    ) -> Report {+        Report(summary: summary, confirmedCommittedCount: committed, entries: entries,+               stop: stop, observedCancellation: cancelled, isError: stop == nil ? nil : true)+    }++}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskEvidence.swift Added +110 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskEvidence.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskEvidence.swiftnew file mode 100644index 00000000..04f98dc3--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskEvidence.swift@@ -0,0 +1,110 @@+#if os(macOS)+import Foundation++/// Establishes supported saved commitment from immutable source evidence only.+/// This does not certify current content, retention or a whole-batch result.+nonisolated enum MCPBatchTaskEvidence {+    nonisolated enum Kind: Sendable { case committed, itemResult, unavailable }++    nonisolated struct Assessment: Sendable {+        let kind: Kind+        let source: MCPResultSource+        var canAdvance: Bool { kind == .committed }+    }++    static func assess(+        source: MCPResultSource, operation: String, originalKey: String,+        taskID: UUID, requiresStatusComment: Bool+    ) -> Assessment {+        Assessment(kind: inspect(source, operation: operation, originalKey: originalKey,+                                 taskID: taskID, requiresStatusComment: requiresStatusComment), source: source)+    }++    private static func inspect(+        _ source: MCPResultSource, operation: String, originalKey: String,+        taskID: UUID, requiresStatusComment: Bool+    ) -> Kind {+        let root = source.document?.value+        guard source.kind == .json, source.evidence == .established,+            MCPBatchTaskEvidenceValidation.numberIsOne(member("contractVersion", in: root)),+            exact(string(member("tool", in: root)), operation),+            exact(string(member("idempotencyKey", in: root)), originalKey)+        else { return .unavailable }+        if let outcome = string(member("outcome", in: root)), outcome != "committed" {+            let supported = supportedFailure(root, outcome: outcome, isError: source.originalIsError)+            return supported ? .itemResult : .unavailable+        }+        guard exact(string(member("outcome", in: root)), "committed"),+            member("accepted", in: root) == .boolean(true), source.originalIsError != true,+            absentOrNull(member("error", in: root)), absentOrNull(member("retryAction", in: root)),+            let entityID = uuid(member("entityId", in: root)),+            let record = member("record", in: root), validRecord(record, taskID: taskID),+            savedIdentityMatches(operation: operation, entityID: entityID, record: record, taskID: taskID),+            !requiresStatusComment || (operation == "update_task_status" &&+                validRecord(member("comment", in: root), taskID: taskID) &&+                uuid(member("id", in: member("comment", in: root))) != nil),+            let completed = MCPBatchTaskEvidenceValidation.timestamp(member("completedAt", in: root)),+            let expiry = MCPBatchTaskEvidenceValidation.timestamp(member("replayExpiresAt", in: root)),+            expiry > completed+        else { return .unavailable }+        return .committed+    }++    private static func absentOrNull(_ value: MCPJSONValue?) -> Bool {+        value == nil || value == .null+    }++    private static func supportedFailure(_ root: MCPJSONValue?, outcome: String, isError: Bool?) -> Bool {+        guard isError == true, let error = member("error", in: root),+            let code = string(member("code", in: error)), !code.isEmpty,+            string(member("message", in: error)) != nil,+            let retry = string(member("retryAction", in: root))+        else { return false }+        let accepted = member("accepted", in: root)+        switch outcome {+        case "rejected":+            return (accepted == .boolean(false) || accepted == .boolean(true)) &&+                ["new_request_new_key", "retry_same_request"].contains(retry)+        case "in_progress":+            return accepted == .boolean(true) && retry == "retry_same_request"+        case "uncertain":+            return (accepted == .boolean(true) || accepted == .null) &&+                retry == "reconcile"+        default: return false+        }+    }++    private static func savedIdentityMatches(+        operation: String, entityID: UUID, record: MCPJSONValue, taskID: UUID+    ) -> Bool {+        switch operation {+        case "update_task", "update_task_status": return entityID == taskID+        case "add_comment": return uuid(member("id", in: record)) == entityID+        default: return false+        }+    }++    private static func validRecord(_ value: MCPJSONValue?, taskID: UUID) -> Bool {+        uuid(member("taskId", in: value)) == taskID &&+            MCPBatchTaskEvidenceValidation.revision(member("revision", in: value))+    }++    private static func member(_ name: String, in value: MCPJSONValue?) -> MCPJSONValue? {+        guard case .object(let members) = value else { return nil }+        return members.first { $0.name.unicodeScalars.elementsEqual(name.unicodeScalars) }?.value+    }++    private static func string(_ value: MCPJSONValue?) -> String? {+        guard case .string(let value) = value else { return nil }+        return value+    }++    private static func exact(_ value: String?, _ expected: String) -> Bool {+        value?.unicodeScalars.elementsEqual(expected.unicodeScalars) == true+    }++    private static func uuid(_ value: MCPJSONValue?) -> UUID? {+        string(value).flatMap(UUID.init(uuidString:))+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskEvidenceValidation.swift Added +51 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskEvidenceValidation.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskEvidenceValidation.swiftnew file mode 100644index 00000000..252fbe1f--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskEvidenceValidation.swift@@ -0,0 +1,51 @@+#if os(macOS)+import Foundation++nonisolated enum MCPBatchTaskEvidenceValidation {+    /// Equality to one uses decimal digits/exponent, never Double/Decimal.+    /// The common parser already validated the complete numeric lexeme.+    static func numberIsOne(_ value: MCPJSONValue?) -> Bool {+        guard case .number(let number) = value, !number.lexeme.hasPrefix("-") else { return false }+        let pieces = number.lexeme.split { $0 == "e" || $0 == "E" }+        let exponent: Int+        if pieces.count == 2 {+            guard let parsed = Int(pieces[1]) else { return false }+            exponent = parsed+        } else { exponent = 0 }+        let mantissa = pieces[0].split(separator: ".")+        let fractionCount = mantissa.count == 2 ? mantissa[1].utf8.count : 0+        let digits = Array(mantissa.joined().utf8)+        var first = 0+        var end = digits.count+        while first < end && digits[first] == 48 { first += 1 }+        while end > first && digits[end - 1] == 48 { end -= 1 }+        guard end - first == 1, digits[first] == 49 else { return false }+        return exponent == fractionCount - (digits.count - end)+    }++    static func revision(_ value: MCPJSONValue?) -> Bool {+        guard case .string(let text) = value, text.utf8.count == 67 else { return false }+        let bytes = Array(text.utf8)+        return bytes.prefix(3).elementsEqual([114, 49, 58]) &&+            bytes.dropFirst(3).allSatisfy { (48...57).contains($0) || (97...102).contains($0) }+    }++    /// Parsing alone can normalize invalid dates. Require canonical UTC+    /// millisecond spelling and formatter roundtrip before comparing instants.+    static func timestamp(_ value: MCPJSONValue?) -> Date? {+        guard case .string(let text) = value, text.utf8.count == 24 else { return nil }+        let bytes = Array(text.utf8)+        let separators: [Int: UInt8] = [4: 45, 7: 45, 10: 84, 13: 58, 16: 58, 19: 46, 23: 90]+        for (index, byte) in bytes.enumerated() {+            if let separator = separators[index] {+                guard byte == separator else { return nil }+            } else if !(48...57).contains(byte) { return nil }+        }+        let formatter = ISO8601DateFormatter()+        formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+        formatter.timeZone = TimeZone(secondsFromGMT: 0)+        guard let date = formatter.date(from: text), formatter.string(from: date) == text else { return nil }+        return date+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskFallback.swift Added +43 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskFallback.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskFallback.swiftnew file mode 100644index 00000000..a12190c5--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskFallback.swift@@ -0,0 +1,43 @@+#if os(macOS)+import Foundation++/// Owns the shallow batch failure payload; the common encoder owns all wire+/// bytes. Unbounded item IDs, records, text and navigation data never enter it.+nonisolated enum MCPBatchTaskFallback {+    static func source(items: [MCPBatchRecoveryItem]) throws -> MCPResultSource {+        guard (1...50).contains(items.count), items.enumerated().allSatisfy({ index, item in+            item.index == index && item.targetTaskId != nil &&+                ["update_task", "update_task_status", "add_comment"].contains(item.operation) &&+                item.operation.unicodeScalars.elementsEqual(item.originalKey.tool.unicodeScalars) &&+                validKey(item.originalKey.idempotencyKey)+        }) else { throw MCPResultBoundaryError.unsupportedEvidence }+        var writer = MCPResultByteWriter(checkpoint: {})+        try writer.literal("{\"contractVersion\":1,\"mode\":\"execute\",\"atomicity\":\"per_item\",")+        try writer.literal("\"summary\":\"serialization_failed\",\"effectEvidence\":\"unestablished\",")+        try writer.literal("\"recovery\":{\"direction\":\"reconcile_original_write\",\"items\":[")+        for (index, item) in items.enumerated() {+            if index > 0 { try writer.literal(",") }+            try writer.literal("{\"index\":\(item.index)")+            try writer.field("operation", item.operation)+            try writer.field("tool", item.originalKey.tool)+            try writer.field("idempotencyKey", item.originalKey.idempotencyKey)+            if let taskID = item.targetTaskId { try writer.field("targetTaskId", taskID.uuidString) }+            try writer.literal("}")+        }+        try writer.literal("]}}")+        guard let text = String(data: writer.data, encoding: .utf8) else {+            throw MCPResultBoundaryError.invalidJSON+        }+        return try MCPResultAdapter.source(text: text, isError: true,+                                           origin: .generatedJSON, evidence: .unestablished)+    }++    private static func validKey(_ key: String) -> Bool {+        guard (1...128).contains(key.utf8.count) else { return false }+        return key.utf8.allSatisfy {+            (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) ||+                [46, 95, 58, 45].contains($0)+        }+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskHandler.swift Added +35 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskHandler.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskHandler.swiftnew file mode 100644index 00000000..66ff541e--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskHandler.swift@@ -0,0 +1,35 @@+#if os(macOS)+import Foundation+import SwiftData++/// Feature-local mode selection. Complete response preparation remains a+/// prerequisite; aggregate serialization and modern dispatch are later seams.+@MainActor enum MCPBatchTaskHandler {+    enum Error: Swift.Error { case executionUnavailable }++    enum Result {+        case invalidInput([MCPBatchTaskRequest.Diagnostic])+        case preview(MCPBatchTaskRequest, MCPBatchTaskPreview.Report)+        case execution(MCPBatchTaskRequest, MCPBatchTaskCoordinator.Report)+    }++    static func handle(+        arguments: MCPJSONValue, container: ModelContainer, persistence: PersistenceAvailability,+        coordinator: MCPBatchTaskCoordinator? = nil, includeComments: Bool = true,+        reads: MCPBatchTaskPreview.Reads = .init()+    ) async throws -> Result {+        switch try MCPBatchTaskRequest.parse(validatedValue: arguments) {+        case .invalid(let diagnostics): return .invalidInput(diagnostics)+        case .valid(let request):+            switch request.mode {+            case .dryRun:+                return .preview(request, try MCPBatchTaskPreview.evaluate(request, container: container,+                    persistence: persistence, includeComments: includeComments, reads: reads))+            case .execute:+                guard let coordinator else { throw Error.executionUnavailable }+                return .execution(request, try await coordinator.run(request))+            }+        }+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskInputArguments.swift Added +72 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskInputArguments.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskInputArguments.swiftnew file mode 100644index 00000000..27a62395--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskInputArguments.swift@@ -0,0 +1,72 @@+#if os(macOS)+import Foundation++@MainActor enum MCPBatchTaskInputArguments {+    enum Validation {+        case valid([String: Any])+        case invalid(String)+    }++    static func validate(_ value: MCPJSONValue, operation: String) throws -> Validation {+        guard case .object(let members) = value else { return .invalid("arguments") }+        let shape = try MCPBatchTaskSchema.arguments(operation)+        if let field = MCPBatchTaskInputValue.closedField(members, allowed: Array(shape.properties.keys)) {+            return .invalid(field)+        }+        for field in shape.required where MCPBatchTaskInputValue.member(field, in: members) == nil {+            return .invalid(field)+        }+        var arguments: [String: Any] = [:]+        for member in members {+            guard let property = shape.properties[member.name] else { return .invalid(member.name) }+            switch try bridge(member.value, type: property.type, field: member.name) {+            case .invalid: return .invalid(member.name)+            case .valid(let value): arguments[member.name] = value+            }+        }+        return .valid(arguments)+    }++    private enum Bridged {+        case valid(Any)+        case invalid+    }++    private static func bridge(_ value: MCPJSONValue, type: String?, field: String) throws -> Bridged {+        switch type {+        case "string":+            guard case .string(let text) = value, validString(text, field: field) else { return .invalid }+            return .valid(text)+        case "integer":+            guard let integer = MCPBatchTaskInputValue.integer(value) else { return .invalid }+            return .valid(integer)+        case "boolean":+            guard case .boolean(let flag) = value else { return .invalid }+            return .valid(flag)+        case "object": return metadata(value)+        default: return .invalid+        }+    }++    private static func validString(_ text: String, field: String) -> Bool {+        switch field {+        case "idempotencyKey": return MCPBatchTaskInputValue.key(text)+        case "expectedRevision": return MCPBatchTaskEvidenceValidation.revision(.string(text))+        case "taskId": return UUID(uuidString: text) != nil+        default: return true // Domain strings, including empty values, are checked per item.+        }+    }++    private static func metadata(_ value: MCPJSONValue) -> Bridged {+        guard case .object(let members) = value else { return .invalid }+        var metadata: [String: String] = [:]+        for member in members {+            // The latest modern bridge also rejects canonical-equivalent names+            // that cannot survive [String: Any]. Never silently collapse a key.+            guard case .string(let text) = member.value, metadata[member.name] == nil else { return .invalid }+            metadata[member.name] = text+        }+        return .valid(metadata)+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskInputIdentity.swift Added +76 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskInputIdentity.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskInputIdentity.swiftnew file mode 100644index 00000000..186a37f9--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskInputIdentity.swift@@ -0,0 +1,76 @@+#if os(macOS)+import Foundation++/// Opaque JSON identities use decoded scalar spelling, never Swift's canonical+/// String equivalence. Valid UTF-8 is a unique encoding of those scalars.+nonisolated struct MCPBatchTaskInputIdentity: Hashable {+    let value: String++    static func == (lhs: Self, rhs: Self) -> Bool {+        lhs.value.utf8.elementsEqual(rhs.value.utf8)+    }++    func hash(into hasher: inout Hasher) {+        for byte in value.utf8 { hasher.combine(byte) }+    }+}++nonisolated enum MCPBatchTaskInputValue {+    static func closedField(_ members: [MCPJSONMember], allowed: [String]) -> String? {+        var seen: Set<MCPBatchTaskInputIdentity> = []+        for member in members {+            guard allowed.contains(where: { $0.utf8.elementsEqual(member.name.utf8) }),+                  seen.insert(MCPBatchTaskInputIdentity(value: member.name)).inserted else { return member.name }+        }+        return nil+    }++    static func member(_ name: String, in members: [MCPJSONMember]) -> MCPJSONValue? {+        members.first { $0.name.utf8.elementsEqual(name.utf8) }?.value+    }++    static func string(_ value: MCPJSONValue?) -> String? {+        guard case .string(let text) = value else { return nil }+        return text+    }++    static func key(_ text: String) -> Bool {+        guard (1...128).contains(text.utf8.count) else { return false }+        return text.utf8.allSatisfy {+            (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) ||+                [46, 95, 58, 45].contains($0)+        }+    }++    /// Mathematical integral JSON numbers must fit Int exactly. A Double bridge+    /// could round a fraction to one or underflow it to zero before validation.+    static func integer(_ value: MCPJSONValue) -> Int? {+        guard case .number(let number) = value else { return nil }+        var spelling = number.lexeme[...]+        let negative = spelling.first == "-"+        if negative { spelling.removeFirst() }+        let pieces = spelling.split { $0 == "e" || $0 == "E" }+        let mantissa = pieces[0].split(separator: ".")+        let fractionCount = mantissa.count == 2 ? mantissa[1].utf8.count : 0+        let digits = mantissa.joined()+        var first = digits.startIndex+        var end = digits.endIndex+        while first < end && digits[first] == "0" { first = digits.index(after: first) }+        if first == end { return 0 }+        while end > first && digits[digits.index(before: end)] == "0" { end = digits.index(before: end) }+        let exponent: Int+        if pieces.count == 2 {+            guard let parsed = Int(pieces[1]) else { return nil }+            exponent = parsed+        } else { exponent = 0 }+        let (scale, scaleOverflow) = exponent.subtractingReportingOverflow(fractionCount)+        let trailingZeros = digits.distance(from: end, to: digits.endIndex)+        let (shift, shiftOverflow) = scale.addingReportingOverflow(trailingZeros)+        let significantCount = digits.distance(from: first, to: end)+        guard !scaleOverflow, !shiftOverflow, shift >= 0, significantCount <= 19,+              shift <= 19 - significantCount else { return nil }+        let integer = (negative ? "-" : "") + String(digits[first..<end]) + String(repeating: "0", count: shift)+        return Int(integer)+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskOutputSchema.swift Added +52 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskOutputSchema.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskOutputSchema.swiftnew file mode 100644index 00000000..a52b6441--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskOutputSchema.swift@@ -0,0 +1,52 @@+#if os(macOS)+import Foundation++nonisolated enum MCPBatchTaskOutputSchema {+    /// Generated schema data only. Historical JSON never passes through+    /// Foundation's value bridge; nested original payload accepts every JSON value.+    static func descriptor(description: String) throws -> MCPResultSchemaDescriptor {+        let common = try MCPResultSchemas.descriptor(tool: "mutate_tasks", description: description)+        guard var schema = try JSONSerialization.jsonObject(with: common.outputSchema.originalUTF8) as? [String: Any],+              var definitions = schema["$defs"] as? [String: Any],+              var jsonSource = definitions["jsonSource"] as? [String: Any],+              var properties = jsonSource["properties"] as? [String: Any] else {+            throw MCPResultBoundaryError.unsupportedEvidence+        }+        definitions["batchPayload"] = try JSONSerialization.jsonObject(with: logical().originalUTF8)+        properties["payload"] = ["$ref": "#/$defs/batchPayload"]+        jsonSource["properties"] = properties+        definitions["jsonSource"] = jsonSource+        schema["$defs"] = definitions+        return MCPResultSchemaDescriptor(tool: "mutate_tasks", description: description,+            outputSchema: try MCPJSONDocument.parse(+                JSONSerialization.data(withJSONObject: schema, options: .sortedKeys)))+    }++    static func logical() throws -> MCPJSONDocument {+        try MCPJSONDocument.parse(#"""+        {"type":"object","required":["contractVersion","summary"],"properties":{+          "contractVersion":{"const":1},"mode":{"enum":["dry_run","execute"]},"atomicity":{"const":"per_item"},+          "summary":{"enum":["preview_valid","preview_invalid","all_committed","stopped","interrupted",+                              "evidence_unavailable","rejected_input","serialization_failed"]},+          "confirmedCommittedCount":{"type":"integer","minimum":0,"maximum":50},+          "observedCancellation":{"type":"boolean"},"advisory":{"const":true},+          "observation":{"const":"saved_local_store"},"keyState":{"const":"unchecked"},+          "stop":{"type":"object","required":["reason","nextUnstartedIndex"],"properties":{+            "reason":{"enum":["item_result","evidence_unavailable","pending_edits","cancelled"]},+            "nextUnstartedIndex":{"type":"integer","minimum":0,"maximum":50},+            "blocker":{"type":"object","required":["index","itemId"],"properties":{+              "index":{"type":"integer"},"itemId":{"type":"string"}}}}},+          "items":{"type":"array","minItems":1,"maxItems":50,"items":{"type":"object",+            "required":["index","itemId","operation","idempotencyKey","taskId","state"],"properties":{+              "index":{"type":"integer"},"itemId":{"type":"string"},"operation":{"type":"string"},+              "idempotencyKey":{"type":"string"},"taskId":{"type":"string","format":"uuid"},+              "state":{"enum":["attempted","not_attempted","valid","invalid","unavailable"]},+              "originalResult":{"type":"object","required":["text"],"additionalProperties":false,+                "properties":{"text":{"type":"string"},"payload":{},"isError":{"type":"boolean"}}},+              "current":{},"proposedEffects":{},"diagnostic":{"type":"object"}}}},+          "diagnostics":{"type":"array"},"effectEvidence":{"const":"unestablished"},"recovery":{"type":"object"}+        }}+        """#)+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreparedResponse.swift Added +51 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreparedResponse.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreparedResponse.swiftnew file mode 100644index 00000000..350b37e6--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreparedResponse.swift@@ -0,0 +1,51 @@+#if os(macOS)+import Foundation++/// Required capability for future batch execution. Only successful preparation+/// of complete correlated bytes can construct it; it retains no encoder callback.+nonisolated struct MCPBatchTaskPreparedResponse: Sendable {+    private let id: JSONRPCId+    private let fixedContext: MCPResultContext+    private let metadata: MCPResultMetadata?+    private let fallbackSource: MCPResultSource+    private let readyBytes: Data++    var context: MCPResultContext { fixedContext }++    private init(id: JSONRPCId, context: MCPResultContext, metadata: MCPResultMetadata?,+                 fallbackSource: MCPResultSource, readyBytes: Data) {+        self.id = id+        self.fixedContext = context+        self.metadata = metadata+        self.fallbackSource = fallbackSource+        self.readyBytes = readyBytes+    }++    static func prepare(+        id: JSONRPCId, items: [MCPBatchRecoveryItem], metadata: MCPResultMetadata?,+        checkpoint: @escaping @Sendable () throws -> Void = {}+    ) throws -> MCPBatchTaskPreparedResponse {+        try checkpoint()+        let source = try MCPBatchTaskFallback.source(items: items)+        let context = MCPResultContext(tool: "mutate_tasks", semanticFailure: nil,+                                       mutationRecovery: .applicationBatch(items: items), entityPositions: [])+        let bytes = try MCPResultEncoder.prepareMutationFallback(id: id, source: source,+            context: context, metadata: metadata, checkpoint: checkpoint)+        return MCPBatchTaskPreparedResponse(id: id, context: context, metadata: metadata,+                                            fallbackSource: source, readyBytes: bytes)+    }++    /// The delivered common selector still owns identity validation and delivery+    /// suppression. Its preparation callback only selects these immutable bytes.+    func select(+        encodeOutcome: MCPResultProviderSelection.EncodeOutcome = MCPResultProviderSelection.encode,+        shouldDeliver: @escaping @Sendable () -> Bool = { !Task.isCancelled },+        dispatch: @escaping @Sendable () async throws -> MCPResultProviderOutcome+    ) async throws -> MCPResultResponseSelection {+        let prepared = readyBytes+        return try await MCPResultProviderSelection.mutation(id: id, context: fixedContext,+            metadata: metadata, fallbackSource: fallbackSource, prepareFallback: { _, _, _, _ in prepared },+            encodeOutcome: encodeOutcome, shouldDeliver: shouldDeliver, dispatch: dispatch)+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreview.swift Added +196 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreview.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreview.swiftnew file mode 100644index 00000000..268fbb51--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreview.swift@@ -0,0 +1,196 @@+#if os(macOS)+import Foundation+import SwiftData++/// Synchronous saved-local observation. No write coordinator or reservation+/// store is supplied to this boundary; only immutable values leave it.+@MainActor enum MCPBatchTaskPreview {+    nonisolated enum State: String, Sendable { case valid, invalid, unavailable }++    nonisolated struct Entry: Sendable {+        let index: Int+        let itemId: String+        let state: State+        let code: String?+        let current: MCPJSONDocument?+        let proposedEffects: MCPJSONDocument?+    }++    nonisolated struct Report: Sendable {+        let entries: [Entry]+        let observation: String+        let keyState: String+        let advisory: Bool+        let isError: Bool?+    }++    /// Descriptor seams permit spies to prove saved-only fetches even when+    /// a read fails. The milestone adapter implements the same generic seam.+    struct Reads {+        var tasks: (FetchDescriptor<TransitTask>, ModelContext) throws -> [TransitTask] = {+            try $1.fetch($0)+        }+        var comments: (FetchDescriptor<Comment>, ModelContext) throws -> [Comment] = {+            try $1.fetch($0)+        }+        var milestones: (ModelContext) -> any ModelFetching = { $0 }+    }++    static func evaluate(+        _ request: MCPBatchTaskRequest,+        container: ModelContainer, persistence: PersistenceAvailability,+        includeComments: Bool = true, reads: Reads = Reads()+    ) throws -> Report {+        guard !persistence.isFallbackStorageActive else {+            return report(request.items.map { entry($0, state: .unavailable, code: "PERSISTENCE_UNAVAILABLE") })+        }+        return try MCPBatchSavedReadContext.withContext(container: container, persistence: persistence) { context in+            let milestones = MilestoneService(modelContext: context,+                displayIDAllocator: DisplayIDAllocator(store: NoAllocation(), isCloudSyncActive: false),+                fetcher: SavedFetcher(base: reads.milestones(context)))+            return report(request.items.map {+                evaluate($0, context: context, milestones: milestones, includeComments: includeComments, reads: reads)+            })+        }+    }++    private static func report(_ entries: [Entry]) -> Report {+        Report(entries: entries, observation: "saved_local_store", keyState: "unchecked",+               advisory: true, isError: entries.allSatisfy { $0.state == .valid } ? nil : true)+    }++    private static func entry(+        _ item: MCPBatchTaskRequest.Item, state: State, code: String? = nil,+        current: MCPJSONDocument? = nil, effects: MCPJSONDocument? = nil+    ) -> Entry {+        Entry(index: item.index, itemId: item.itemId, state: state, code: code,+              current: current, proposedEffects: effects)+    }++    private static func evaluate(+        _ item: MCPBatchTaskRequest.Item, context: ModelContext, milestones: MilestoneService,+        includeComments: Bool, reads: Reads+    ) -> Entry {+        let task: TransitTask+        let snapshot: MCPRecordSnapshot+        let current: MCPJSONDocument+        do {+            let id = item.targetTaskId+            var descriptor = FetchDescriptor<TransitTask>(predicate: #Predicate { $0.id == id })+            descriptor.includePendingChanges = false+            let tasks = try reads.tasks(descriptor, context)+            guard tasks.count == 1, let resolved = tasks.first else {+                return entry(item, state: .invalid,+                    code: tasks.isEmpty ? "TASK_NOT_FOUND" : "DUPLICATE_TASK_IDENTIFIER")+            }+            task = resolved+            snapshot = try MCPRecordSnapshot.task(task) { id in+                var comments = CommentService.descriptor(for: id)+                comments.includePendingChanges = false+                return try reads.comments(comments, context)+            }+            var record = snapshot.record+            if !includeComments { record.removeValue(forKey: "comments") }+            current = try document(record)+        } catch {+            // Failure obtaining required saved evidence is never a domain+            // negative answer, regardless of the injected error's type/code.+            return entry(item, state: .unavailable, code: "INTERNAL_ERROR")+        }+        if let expected = item.command.expectedRevision, expected != snapshot.revision {+            return entry(item, state: .invalid, code: "REVISION_CONFLICT", current: current)+        }+        do {+            let proposed = try effects(item.command, task: task, milestones: milestones)+            let encoded: MCPJSONDocument+            do { encoded = try document(proposed) } catch {+                return entry(item, state: .unavailable, code: "INTERNAL_ERROR", current: current)+            }+            return entry(item, state: .valid, current: current, effects: encoded)+        } catch {+            let failure = MCPWriteFailure.from(error)+            return entry(item, state: failure.code == "INTERNAL_ERROR" ? .unavailable : .invalid,+                         code: failure.code, current: current)+        }+    }++    private static func document(_ value: [String: Any]) throws -> MCPJSONDocument {+        try MCPJSONDocument.parse(JSONSerialization.data(withJSONObject: value, options: [.sortedKeys]))+    }++    private static func effects(+        _ command: MCPWriteCommand, task: TransitTask, milestones: MilestoneService+    ) throws -> [String: Any] {+        if command.tool == "update_task" {+            return updateEffects(try TaskUpdateValidator.validate(+                command.arguments, task: task, milestoneService: milestones).get())+        }+        if command.tool == "add_comment" {+            let input: CommentInputValidation.Input+            do {+                input = try CommentInputValidation.normalize(+                    content: command.arguments["content"] as? String ?? "",+                    authorName: command.arguments["authorName"] as? String ?? "")+            } catch { throw MCPWriteFailure("INVALID_INPUT", "Invalid comment: \(error)") }+            return ["content": input.content, "authorName": input.authorName, "isAgent": true]+        }+        let status = try MCPTaskMutationValidation.status(currentStatus: task.statusRawValue,+            targetStatus: command.arguments["status"] as? String ?? "",+            comment: command.arguments["comment"] as? String,+            authorName: command.arguments["authorName"] as? String)+        let comment: Any = status.comment.map {+            ["content": $0.content, "authorName": $0.authorName, "isAgent": true] as [String: Any]+        } as Any? ?? NSNull()+        return ["status": status.targetStatus, "statusChanged": status.statusChanged,+                "lastStatusChange": status.lastStatusChange.rawValue,+                "completion": status.completion.rawValue, "comment": comment]+    }++    private static func updateEffects(_ update: ValidatedTaskUpdate) -> [String: Any] {+        var effects: [String: Any] = [:]+        effects["name"] = update.name+        switch update.description {+        case .noChange: break+        case .set(let value): effects["description"] = value+        case .clear: effects["description"] = NSNull()+        }+        effects["type"] = update.type?.rawValue+        effects["priority"] = update.priority?.rawValue+        switch update.metadata {+        case .noChange: break+        case .set(let value): effects["metadata"] = value+        case .clear: effects["metadata"] = NSNull()+        }+        switch update.milestoneAction {+        case .none: break+        case .assign(let milestone): effects["milestoneId"] = milestone.id.uuidString+        case .clear: effects["milestone"] = NSNull()+        }+        return effects+    }++    private struct SavedFetcher: ModelFetching {+        let base: any ModelFetching++        func fetch<T: PersistentModel>(_ descriptor: FetchDescriptor<T>) throws -> [T] {+            var descriptor = descriptor+            descriptor.includePendingChanges = false+            do { return try base.fetch(descriptor) } catch { throw ReadFailure.unavailable }+        }+    }++    private enum ReadFailure: Error { case unavailable }++    /// Milestone validation needs a service dependency, but never allocation.+    /// An inert store also prevents construction from opening CloudKit access.+    nonisolated private struct NoAllocation: DisplayIDAllocator.CounterStore {+        func loadCounter() async throws -> DisplayIDAllocator.CounterSnapshot {+            throw DisplayIDAllocator.Error.cloudSyncInactive+        }++        func saveCounter(nextDisplayID: Int, expectedChangeTag: String?) async throws {+            throw DisplayIDAllocator.Error.cloudSyncInactive+        }+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreviewHandler.swift Added +28 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreviewHandler.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreviewHandler.swiftnew file mode 100644index 00000000..f21ad56f--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreviewHandler.swift@@ -0,0 +1,28 @@+#if os(macOS)+import Foundation+import SwiftData++/// Feature-local value boundary; shared modern dispatch is integrated later.+/// Execute requests deliberately have no coordinator at this preview seam.+@MainActor enum MCPBatchTaskPreviewHandler {+    enum Result {+        case invalidInput([MCPBatchTaskRequest.Diagnostic])+        case preview(MCPBatchTaskRequest, MCPBatchTaskPreview.Report)+        case executionUnavailable+    }++    static func handle(+        arguments: MCPJSONValue, container: ModelContainer,+        persistence: PersistenceAvailability, includeComments: Bool = true,+        reads: MCPBatchTaskPreview.Reads = .init()+    ) throws -> Result {+        switch try MCPBatchTaskRequest.parse(validatedValue: arguments) {+        case .invalid(let diagnostics): return .invalidInput(diagnostics)+        case .valid(let request):+            guard request.mode == .dryRun else { return .executionUnavailable }+            return .preview(request, try MCPBatchTaskPreview.evaluate(request, container: container,+                persistence: persistence, includeComments: includeComments, reads: reads))+        }+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskRequest.swift Added +139 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskRequest.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskRequest.swiftnew file mode 100644index 00000000..1a89fa5e--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskRequest.swift@@ -0,0 +1,139 @@+#if os(macOS)+import Foundation++/// Establishes the entire shape before callers can admit any item. No service+/// or write coordinator is reachable here; original JSON stays immutable.+@MainActor struct MCPBatchTaskRequest {+    enum Mode: String { case dryRun = "dry_run", execute }++    struct Item {+        let index: Int+        let itemId: String+        let operation: String+        let targetTaskId: UUID+        let originalArguments: MCPJSONValue+        let command: MCPWriteCommand+    }++    struct Diagnostic {+        let index: Int?+        let itemId: String?+        let field: String+        let code: String+    }++    enum Validation {+        case valid(MCPBatchTaskRequest)+        case invalid([Diagnostic])+    }++    let mode: Mode+    let items: [Item]++    private init(mode: Mode, items: [Item]) {+        self.mode = mode+        self.items = items+    }++    static func parse(_ document: MCPJSONDocument) throws -> Validation {+        try parse(validatedValue: document.value)+    }++    /// The shared modern owner can pass the original parsed arguments tree here+    /// before Any conversion. This avoids losing numeric tokens in a roundtrip.+    static func parse(validatedValue value: MCPJSONValue) throws -> Validation {+        guard case .object(let members) = value else { return invalid(field: "arguments") }+        if let field = MCPBatchTaskInputValue.closedField(members, allowed: ["mode", "items"]) {+            return invalid(field: field)+        }+        let mode: Mode+        let modeValue = MCPBatchTaskInputValue.string(MCPBatchTaskInputValue.member("mode", in: members))+        if modeValue?.utf8.elementsEqual("execute".utf8) == true {+            mode = .execute+        } else if modeValue?.utf8.elementsEqual("dry_run".utf8) == true {+            mode = .dryRun+        } else { return invalid(field: "mode") }+        guard case .array(let values) = MCPBatchTaskInputValue.member("items", in: members),+              (1...50).contains(values.count) else { return invalid(field: "items") }+        var items: [Item] = []+        var diagnostics: [Diagnostic] = []+        var identities = Identities()+        for (index, value) in values.enumerated() {+            switch try item(value, index: index) {+            case .invalid(let diagnostic): diagnostics.append(diagnostic)+            case .valid(let item):+                if let field = identities.insert(item) {+                    diagnostics.append(diagnostic(index: index, itemId: item.itemId, field: field))+                } else { items.append(item) }+            }+        }+        return diagnostics.isEmpty ? .valid(Self(mode: mode, items: items)) : .invalid(diagnostics)+    }++    private enum Candidate {+        case valid(Item)+        case invalid(Diagnostic)+    }++    private static func item(_ value: MCPJSONValue, index: Int) throws -> Candidate {+        guard case .object(let members) = value else {+            return .invalid(diagnostic(index: index, itemId: nil, field: "item"))+        }+        let itemId = MCPBatchTaskInputValue.string(MCPBatchTaskInputValue.member("itemId", in: members))+        let usableId = itemId.flatMap { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : $0 }+        func rejected(_ field: String) -> Candidate {+            .invalid(diagnostic(index: index, itemId: usableId, field: field))+        }+        if let field = MCPBatchTaskInputValue.closedField(members, allowed: ["itemId", "operation", "arguments"]) {+            return rejected(field)+        }+        guard let usableId else { return rejected("itemId") }+        guard let operation = MCPBatchTaskInputValue.string(MCPBatchTaskInputValue.member("operation", in: members)),+              MCPBatchTaskSchema.operations.contains(where: { $0.utf8.elementsEqual(operation.utf8) }) else {+            return rejected("operation")+        }+        guard let originalArguments = MCPBatchTaskInputValue.member("arguments", in: members) else {+            return rejected("arguments")+        }+        switch try MCPBatchTaskInputArguments.validate(originalArguments, operation: operation) {+        case .invalid(let field): return rejected(field)+        case .valid(let arguments):+            do {+                let command = try MCPWriteCommand.validate(tool: operation, arguments: arguments)+                guard let taskId = (arguments["taskId"] as? String).flatMap(UUID.init(uuidString:)) else {+                    return rejected("taskId")+                }+                return .valid(Item(index: index, itemId: usableId, operation: operation,+                                   targetTaskId: taskId, originalArguments: originalArguments, command: command))+            } catch { return rejected("arguments") }+        }+    }++    nonisolated private struct ToolKey: Hashable {+        let operation: MCPBatchTaskInputIdentity+        let key: MCPBatchTaskInputIdentity+    }++    private struct Identities {+        var itemIds: Set<MCPBatchTaskInputIdentity> = []+        var taskIds: Set<UUID> = []+        var keys: Set<ToolKey> = []++        mutating func insert(_ item: Item) -> String? {+            guard itemIds.insert(MCPBatchTaskInputIdentity(value: item.itemId)).inserted else { return "itemId" }+            guard taskIds.insert(item.targetTaskId).inserted else { return "taskId" }+            let key = ToolKey(operation: MCPBatchTaskInputIdentity(value: item.operation),+                              key: MCPBatchTaskInputIdentity(value: item.command.key))+            return keys.insert(key).inserted ? nil : "idempotencyKey"+        }+    }++    private static func diagnostic(index: Int?, itemId: String?, field: String) -> Diagnostic {+        Diagnostic(index: index, itemId: itemId, field: field, code: "INVALID_INPUT")+    }++    private static func invalid(field: String) -> Validation {+        .invalid([diagnostic(index: nil, itemId: nil, field: field)])+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskResponse.swift Added +44 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskResponse.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskResponse.swiftnew file mode 100644index 00000000..a12167b4--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskResponse.swift@@ -0,0 +1,44 @@+#if os(macOS)+import Foundation++/// The caller supplies an admitted immutable request and complete capability.+/// No item can run before preparation; later failures only select ready bytes.+@MainActor enum MCPBatchTaskResponse {+    static func execute(+        _ request: MCPBatchTaskRequest, prepared: MCPBatchTaskPreparedResponse,+        writeCoordinator: MCPWriteCoordinator,+        encodeOutcome: MCPResultProviderSelection.EncodeOutcome = MCPResultProviderSelection.encode,+        shouldDeliver: @escaping @Sendable () -> Bool = { !Task.isCancelled }+    ) async throws -> MCPResultResponseSelection {+        let batch = MCPBatchTaskCoordinator(preparedResponse: prepared, writeCoordinator: writeCoordinator)+        return try await select(request, prepared: prepared, batch: batch,+                                encodeOutcome: encodeOutcome, shouldDeliver: shouldDeliver)+    }++    static func execute(+        _ request: MCPBatchTaskRequest, prepared: MCPBatchTaskPreparedResponse,+        executor: @escaping MCPBatchTaskCoordinator.Executor,+        encodeOutcome: MCPResultProviderSelection.EncodeOutcome = MCPResultProviderSelection.encode,+        shouldDeliver: @escaping @Sendable () -> Bool = { !Task.isCancelled }+    ) async throws -> MCPResultResponseSelection {+        let batch = MCPBatchTaskCoordinator(preparedResponse: prepared, executor: executor)+        return try await select(request, prepared: prepared, batch: batch,+                                encodeOutcome: encodeOutcome, shouldDeliver: shouldDeliver)+    }++    private static func select(+        _ request: MCPBatchTaskRequest, prepared: MCPBatchTaskPreparedResponse, batch: MCPBatchTaskCoordinator,+        encodeOutcome: MCPResultProviderSelection.EncodeOutcome,+        shouldDeliver: @escaping @Sendable () -> Bool+    ) async throws -> MCPResultResponseSelection {+        // Normal public positions never enter the fixed compact-fallback context.+        let context = MCPBatchTaskContext.normal(request, recovery: prepared.context.mutationRecovery)+        return try await prepared.select(encodeOutcome: encodeOutcome, shouldDeliver: shouldDeliver,+            dispatch: { @MainActor in+                let report = try await batch.run(request)+                let source = try MCPBatchTaskResult.execution(request, report: report)+                return MCPResultProviderOutcome(source: source, context: context)+            })+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskResult.swift Added +132 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskResult.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskResult.swiftnew file mode 100644index 00000000..06bc8c8c--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskResult.swift@@ -0,0 +1,132 @@+#if os(macOS)+import Foundation++/// Logical batch source only. Raw JSON comes exclusively from validated+/// documents; the common encoder owns modern envelopes and byte selection.+@MainActor enum MCPBatchTaskResult {+    static func execution(_ request: MCPBatchTaskRequest, report: MCPBatchTaskCoordinator.Report) throws+        -> MCPResultSource {+        guard request.mode == .execute, report.entries.count == request.items.count else {+            throw MCPResultBoundaryError.unsupportedEvidence+        }+        var writer = MCPResultByteWriter(checkpoint: {})+        try start(&writer, mode: "execute", summary: report.summary)+        try writer.literal(",\"confirmedCommittedCount\":\(report.confirmedCommittedCount)")+        if report.observedCancellation { try writer.literal(",\"observedCancellation\":true") }+        if let stop = report.stop { try writer.literal(",\"stop\":"); try writeStop(stop, into: &writer) }+        try writer.literal(",\"items\":[")+        for (index, pair) in zip(request.items, report.entries).enumerated() {+            let (item, entry) = pair+            guard item.index == index, entry.index == index, entry.taskID == item.targetTaskId,+                  entry.itemId.utf8.elementsEqual(item.itemId.utf8),+                  entry.operation.utf8.elementsEqual(item.operation.utf8),+                  entry.originalKey.utf8.elementsEqual(item.command.key.utf8) else {+                throw MCPResultBoundaryError.unsupportedEvidence+            }+            if index > 0 { try writer.literal(",") }+            try mapping(item, into: &writer)+            try writer.field("state", entry.state.rawValue)+            if let original = entry.originalResult {+                try writer.literal(",\"originalResult\":{")+                try writer.field("text", original.originalText, first: true)+                if let payload = original.document {+                    try writer.literal(",\"payload\":"); try writer.raw(payload.originalUTF8)+                }+                if let flag = original.originalIsError { try writer.literal(",\"isError\":\(flag ? "true" : "false")") }+                try writer.literal("}")+            }+            if entry.state == .notAttempted, let stop = report.stop {+                try writer.literal(",\"diagnostic\":"); try writeStop(stop, into: &writer)+            }+            try writer.literal("}")+        }+        try writer.literal("]}")+        return try source(writer, isError: report.isError)+    }++    static func preview(_ request: MCPBatchTaskRequest, report: MCPBatchTaskPreview.Report) throws+        -> MCPResultSource {+        guard request.mode == .dryRun, report.entries.count == request.items.count else {+            throw MCPResultBoundaryError.unsupportedEvidence+        }+        var writer = MCPResultByteWriter(checkpoint: {})+        try start(&writer, mode: "dry_run", summary: report.isError == true ? "preview_invalid" : "preview_valid")+        try writer.field("observation", report.observation)+        try writer.field("keyState", report.keyState)+        try writer.literal(",\"advisory\":true,\"items\":[")+        for (index, pair) in zip(request.items, report.entries).enumerated() {+            let (item, entry) = pair+            guard item.index == index, entry.index == index,+                  entry.itemId.utf8.elementsEqual(item.itemId.utf8) else {+                throw MCPResultBoundaryError.unsupportedEvidence+            }+            if index > 0 { try writer.literal(",") }+            try mapping(item, into: &writer)+            try writer.field("state", entry.state.rawValue)+            if let code = entry.code {+                try writer.literal(",\"diagnostic\":{"); try writer.field("code", code, first: true)+                try writer.literal("}")+            }+            if let current = entry.current { try writer.literal(",\"current\":"); try writer.raw(current.originalUTF8) }+            if let effects = entry.proposedEffects {+                try writer.literal(",\"proposedEffects\":"); try writer.raw(effects.originalUTF8)+            }+            try writer.literal("}")+        }+        try writer.literal("]}")+        return try source(writer, isError: report.isError)+    }++    static func invalidInput(_ diagnostics: [MCPBatchTaskRequest.Diagnostic]) throws -> MCPResultSource {+        var writer = MCPResultByteWriter(checkpoint: {})+        try writer.literal("{\"contractVersion\":1,\"summary\":\"rejected_input\",\"diagnostics\":[")+        for (index, diagnostic) in diagnostics.enumerated() {+            if index > 0 { try writer.literal(",") }+            try writer.literal("{")+            try writer.field("code", diagnostic.code, first: true)+            try writer.field("field", diagnostic.field)+            if let item = diagnostic.index { try writer.literal(",\"index\":\(item)") }+            if let itemId = diagnostic.itemId { try writer.field("itemId", itemId) }+            try writer.literal("}")+        }+        try writer.literal("]}")+        return try source(writer, isError: true)+    }++    private static func start(_ writer: inout MCPResultByteWriter, mode: String, summary: String) throws {+        try writer.literal("{\"contractVersion\":1,\"atomicity\":\"per_item\"")+        try writer.field("mode", mode)+        try writer.field("summary", summary)+    }++    private static func mapping(_ item: MCPBatchTaskRequest.Item, into writer: inout MCPResultByteWriter) throws {+        try writer.literal("{\"index\":\(item.index)")+        try writer.field("itemId", item.itemId)+        try writer.field("operation", item.operation)+        try writer.field("idempotencyKey", item.command.key)+        // Preserve the original accepted spelling; compact recovery uses normalized UUIDs.+        guard let taskId = item.command.arguments["taskId"] as? String else {+            throw MCPResultBoundaryError.unsupportedEvidence+        }+        try writer.field("taskId", taskId)+    }++    private static func writeStop(_ stop: MCPBatchTaskCoordinator.Stop, into writer: inout MCPResultByteWriter) throws {+        try writer.literal("{")+        try writer.field("reason", stop.reason.rawValue, first: true)+        try writer.literal(",\"nextUnstartedIndex\":\(stop.nextUnstartedIndex)")+        if let blocker = stop.blocker {+            try writer.literal(",\"blocker\":{\"index\":\(blocker.index)")+            try writer.field("itemId", blocker.itemId)+            try writer.literal("}")+        }+        try writer.literal("}")+    }++    private static func source(_ writer: MCPResultByteWriter, isError: Bool?) throws -> MCPResultSource {+        guard let text = String(data: writer.data, encoding: .utf8) else { throw MCPResultBoundaryError.invalidJSON }+        return try MCPResultAdapter.source(text: text, isError: isError,+                                           origin: .generatedJSON, evidence: .established)+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchTaskSchema.swift Added +71 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskSchema.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskSchema.swiftnew file mode 100644index 00000000..1c55fe9a--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskSchema.swift@@ -0,0 +1,71 @@+#if os(macOS)+import Foundation++/// Logical rich input descriptor only. Shared registration stays with its owner.+nonisolated enum MCPBatchTaskSchema {+    nonisolated struct ArgumentShape: Sendable {+        let properties: [String: JSONSchemaProperty]+        let required: [String]+    }++    static let operations = ["update_task", "update_task_status", "add_comment"]++    /// Public fields/types stay sourced from the actual protected definitions.+    /// Only batch targeting and metadata/domain-stage restrictions differ.+    static func arguments(_ operation: String) throws -> ArgumentShape {+        guard operations.contains(operation),+              let definition = MCPToolDefinitions.coreTools.first(where: { $0.name == operation }),+              var properties = definition.inputSchema.properties else {+            throw MCPResultBoundaryError.unsupportedEvidence+        }+        properties.removeValue(forKey: "displayId")+        var required = definition.inputSchema.required ?? []+        if !required.contains("taskId") { required.append("taskId") }+        return ArgumentShape(properties: properties, required: required)+    }++    static func inputSchema() throws -> MCPJSONDocument {+        let branches = try operations.map(branch)+        let schema: [String: Any] = [+            "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object",+            "additionalProperties": false, "required": ["mode", "items"],+            "properties": [+                "mode": ["type": "string", "enum": ["dry_run", "execute"]],+                "items": ["type": "array", "minItems": 1, "maxItems": 50,+                          "items": ["oneOf": branches]]+            ]+        ]+        return try MCPJSONDocument.parse(JSONSerialization.data(withJSONObject: schema, options: [.sortedKeys]))+    }++    private static func branch(_ operation: String) throws -> [String: Any] {+        let shape = try arguments(operation)+        var fields: [String: Any] = [:]+        for (name, property) in shape.properties { fields[name] = field(name, property: property) }+        return [+            "type": "object", "additionalProperties": false, "required": ["itemId", "operation", "arguments"],+            "properties": [+                "itemId": ["type": "string", "minLength": 1, "pattern": "\\S",+                           "description": "Opaque nonblank caller mapping; preserved without trimming."],+                "operation": ["type": "string", "const": operation],+                "arguments": ["type": "object", "additionalProperties": false,+                              "properties": fields, "required": shape.required]+            ]+        ]+    }++    private static func field(_ name: String, property: JSONSchemaProperty) -> [String: Any] {+        var description = property.description ?? ""+        if let values = property.enumValues {+            description += " Supported values: " + values.joined(separator: ", ") ++                ". Invalid strings are item domain failures."+        }+        var result: [String: Any] = ["type": property.type ?? "string", "description": description]+        if let pattern = property.pattern { result["pattern"] = pattern }+        if name == "taskId" { result["format"] = "uuid" }+        if name == "metadata" { result["additionalProperties"] = ["type": "string"] }+        // No enum/const or conditional author requirement for domain values.+        return result+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchToolDefinition.swift Added +23 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchToolDefinition.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchToolDefinition.swiftnew file mode 100644index 00000000..8e30c6ac--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchToolDefinition.swift@@ -0,0 +1,23 @@+#if os(macOS)+import Foundation++nonisolated enum MCPBatchToolDefinition {+    static let description = """+        Preview or execute 1–50 ordered task mutations (update_task, update_task_status, add_comment). \+        Dry runs observe saved local storage only: advisory=true and keyState=unchecked. \+        Execute commits independently per item and stops at the first noncommitted or unestablished result. \+        Every item needs its own original protected-tool key and task UUID; update operations need expectedRevision. \+        Retry using identical original item arguments and keys in the originating store. No whole-batch transaction \+        or automatic retry exists. Historical receipt replay does not certify current contents. \+        Uncertain effects or serialization_failed require original-key reconciliation, never fresh-key retries.+        """++    // Typed core definitions remain the source for standalone argument validators.+    // Latest-only modern discovery substitutes the complete rich batch schema.+    static let definition = MCPToolDefinition(name: "mutate_tasks", description: description,+        inputSchema: .object(properties: [+            "mode": .stringEnum("Explicit mode", values: ["dry_run", "execute"]),+            "items": .array("1–50 uniquely targeted ordered mutations", itemType: "object")+        ], required: ["mode", "items"]))+}+#endif
Transit/Transit/MCP/BatchWrites/MCPBatchWritePolicy.swift Added +71 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchWritePolicy.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchWritePolicy.swiftnew file mode 100644index 00000000..80c4b51f--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchWritePolicy.swift@@ -0,0 +1,71 @@+#if os(macOS)+import Foundation+import SwiftData++/// Opt-in safeguards for batch calls through the existing receipt coordinator.+/// The synchronous callback runs only for a fresh apply, never for replay.+@MainActor struct MCPBatchWritePolicy {+    enum RetainedInspection {+        case terminal(MCPWriteReceipt)+        case reused+        case unavailable(accepted: Bool?)+    }++    let onPendingEditsStop: @MainActor () -> Void+    let validateBeforeApply: @MainActor (MCPWriteCommand, ModelContext) throws -> Void++    init(+        validateBeforeApply: @escaping @MainActor (MCPWriteCommand, ModelContext) throws -> Void =+            MCPBatchWritePolicy.validateTaskIdentity,+        onPendingEditsStop: @escaping @MainActor () -> Void = {}+    ) {+        self.validateBeforeApply = validateBeforeApply+        self.onPendingEditsStop = onPendingEditsStop+    }++    private static func validateTaskIdentity(_ command: MCPWriteCommand, context: ModelContext) throws {+        guard ["update_task", "update_task_status", "add_comment"].contains(command.tool),+            let rawID = command.arguments["taskId"] as? String, let taskID = UUID(uuidString: rawID)+        else { throw MCPWriteFailure("INVALID_INPUT", "Batch writes require an explicit task UUID") }+        var descriptor = FetchDescriptor<TransitTask>(predicate: #Predicate { $0.id == taskID })+        descriptor.fetchLimit = 2+        descriptor.includePendingChanges = false+        let matches = try context.fetch(descriptor)+        guard !matches.isEmpty else { throw MCPWriteFailure("TASK_NOT_FOUND", "Task UUID was not found") }+        guard matches.count == 1 else {+            throw MCPWriteFailure("DUPLICATE_TASK_IDENTIFIER", "Task UUID identifies multiple saved tasks")+        }+    }++    /// Uses existing durable validation without repairing either store. Models+    /// stay on MainActor and are immediately replayed by their owning caller.+    static func inspectRetained(+        _ command: MCPWriteCommand, payload: String, reservations: MCPLocalReservationStore,+        receipts: MCPWriteReceiptStore, now: Date+    ) -> RetainedInspection {+        do {+            return try reservations.withValidatedBindings {+                if let binding = try reservations.lookup(tool: command.tool, key: command.key) {+                    guard binding.expiresAt.map({ $0 <= now }) != true else {+                        return .unavailable(accepted: nil)+                    }+                    guard binding.requestJSON == payload else { return .reused }+                    guard let receipt = try receipts.lookup(tool: command.tool, key: command.key, durable: true),+                        receipt.id == binding.receiptID, receipt.requestJSON == binding.requestJSON,+                        receipt.formatVersion == binding.formatVersion, receipt.localScopeID == binding.scopeID,+                        binding.expiresAt == nil || binding.expiresAt == receipt.expiresAt,+                        receipt.expiresAt.map({ $0 <= now }) != true+                    else { return .unavailable(accepted: true) }+                    return receipt.resultJSON == nil ? .unavailable(accepted: true) : .terminal(receipt)+                }+                if let receipt = try receipts.lookup(tool: command.tool, key: command.key, durable: true),+                    receipt.expiresAt.map({ $0 <= now }) != true {+                    guard receipt.requestJSON == payload else { return .reused }+                    return receipt.resultJSON == nil ? .unavailable(accepted: true) : .terminal(receipt)+                }+                return .unavailable(accepted: nil)+            }+        } catch { return .unavailable(accepted: nil) }+    }+}+#endif
Transit/Transit/MCP/BatchWrites/MCPTaskMutationValidation.swift Added +48 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPTaskMutationValidation.swift b/Transit/Transit/MCP/BatchWrites/MCPTaskMutationValidation.swiftnew file mode 100644index 00000000..e01c9585--- /dev/null+++ b/Transit/Transit/MCP/BatchWrites/MCPTaskMutationValidation.swift@@ -0,0 +1,48 @@+#if os(macOS)+import Foundation++/// MCP-specific conditional author validation and symbolic status effects.+/// No model, timestamp or comment identity is created by this value boundary.+@MainActor enum MCPTaskMutationValidation {+    nonisolated enum TimestampAction: String, Sendable { case unchanged, update, set, clear }++    nonisolated struct Status: Sendable, Equatable {+        let targetStatus: String+        let statusChanged: Bool+        let comment: CommentInputValidation.Input?+        let lastStatusChange: TimestampAction+        let completion: TimestampAction+    }++    static func status(+        currentStatus: String, targetStatus: String,+        comment: String?, authorName: String?+    ) throws -> Status {+        guard let target = TaskStatus(rawValue: targetStatus) else {+            throw MCPWriteFailure("INVALID_STATUS", "Invalid task status")+        }+        if comment != nil,+           authorName?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty != false {+            throw MCPWriteFailure("INVALID_INPUT", "authorName is required when comment is provided")+        }+        let normalized: CommentInputValidation.Input?+        if let comment, !comment.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+            normalized = try CommentInputValidation.normalize(content: comment, authorName: authorName ?? "")+        } else { normalized = nil }+        let current = TaskStatus(rawValue: currentStatus) ?? .idea+        let changed = current != target+        let completion: TimestampAction+        if !changed {+            completion = .unchanged+        } else if target.isTerminal {+            completion = .set+        } else if current.isTerminal {+            completion = .clear+        } else {+            completion = .unchanged+        }+        return Status(targetStatus: target.rawValue, statusChanged: changed, comment: normalized,+                      lastStatusChange: changed ? .update : .unchanged, completion: completion)+    }+}+#endif
Transit/Transit/MCP/MCPServer+Routing.swift Modified +13 / -5
diff --git a/Transit/Transit/MCP/MCPServer+Routing.swift b/Transit/Transit/MCP/MCPServer+Routing.swiftindex ea116eb0..556d8047 100644--- a/Transit/Transit/MCP/MCPServer+Routing.swift+++ b/Transit/Transit/MCP/MCPServer+Routing.swift@@ -69,6 +69,10 @@ extension MCPServer {             return encodedResponse(try MCPModernDiscovery.encodeTools(id: modern.id,                 tools: MCPToolDefinitions.modernTools(includingMaintenance: maintenanceEnabled)))         case .callTool(let tool, let execution):+            // Batch shape and numeric tokens must reach the parser before Any conversion.+            if case .applicationBatch = execution {+                return selectedResponse(try await MCPBatchModernProvider.call(modern, handler: handler))+            }             let rpc = MCPModernWire.request(modern, tool: tool)             if case .coveredRead = execution {                 guard let read = MCPBoundedReadDispatcher.classify(rpc) else {@@ -83,11 +87,8 @@ extension MCPServer {                     })                 return encodedResponse(bytes)             }-            switch try await MCPModernProviderBinding.call(rpc, tool: tool, handler: handler,-                maintenanceEnabled: maintenanceEnabled) {-            case .normal(let bytes), .reconciliation(let bytes): return encodedResponse(bytes)-            case .suppressed: return Response(status: .accepted)-            }+            return selectedResponse(try await MCPModernProviderBinding.call(rpc, tool: tool, handler: handler,+                maintenanceEnabled: maintenanceEnabled))         case .listenSubscriptions:             do {                 return try await toolListChangeStreamResponse(modern: modern, context: context, handler: handler)@@ -98,6 +99,13 @@ extension MCPServer {         }     } +    nonisolated private static func selectedResponse(_ selection: MCPResultResponseSelection) -> Response {+        switch selection {+        case .normal(let bytes), .reconciliation(let bytes): return encodedResponse(bytes)+        case .suppressed: return Response(status: .accepted)+        }+    }+     /// Dispatches one non-empty JSON-RPC batch and builds its HTTP response.     private static func batchResponse(         for elements: [BatchElement],
Transit/Transit/MCP/MCPToolDefinitions.swift Modified +12 / -9
diff --git a/Transit/Transit/MCP/MCPToolDefinitions.swift b/Transit/Transit/MCP/MCPToolDefinitions.swiftindex d3125954..af05412d 100644--- a/Transit/Transit/MCP/MCPToolDefinitions.swift+++ b/Transit/Transit/MCP/MCPToolDefinitions.swift@@ -2,12 +2,11 @@ import Foundation  // MARK: - Tool Definitions- nonisolated enum MCPToolDefinitions {     static let coreTools: [MCPToolDefinition] = [         createTask, updateTaskStatus, queryTasks, addComment, getProjects, createProject,         createMilestone, queryMilestones, updateMilestone, deleteMilestone, updateTask,-        MCPPortfolioToolDefinitions.queryProjectSummaries+        MCPPortfolioToolDefinitions.queryProjectSummaries, MCPBatchToolDefinition.definition     ]      static let maintenanceTools: [MCPToolDefinition] = [@@ -23,15 +22,19 @@ nonisolated enum MCPToolDefinitions {         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))+            let input: MCPJSONDocument+            let result: MCPResultSchemaDescriptor+            if definition.name == "mutate_tasks" {+                input = try MCPBatchTaskSchema.inputSchema()+                result = try MCPBatchTaskOutputSchema.descriptor(description: definition.description)+            } else {+                input = try MCPJSONDocument.parse(JSONEncoder().encode(definition.inputSchema))+                result = try MCPResultSchemas.descriptor(tool: definition.name, description: definition.description)+            }+            return MCPModernToolDescriptor(name: definition.name, description: definition.description,+                inputSchema: input, resultSchema: result)         }     } 
Transit/Transit/MCP/MCPToolHandler.swift Modified +54 / -21
diff --git a/Transit/Transit/MCP/MCPToolHandler.swift b/Transit/Transit/MCP/MCPToolHandler.swiftindex 53827dbc..1dd995b2 100644--- a/Transit/Transit/MCP/MCPToolHandler.swift+++ b/Transit/Transit/MCP/MCPToolHandler.swift@@ -28,6 +28,10 @@ final class MCPToolHandler {     private let persistence: PersistenceAvailability     private let writeCoordinator: MCPWriteCoordinator? +    // Batch provider injection only; Task14 binds dispatch after real-route RED.+    let batchContainer: ModelContainer?+    let batchResultEncoder: MCPResultProviderSelection.EncodeOutcome?+     /// Task14 fault seam declaration; task15 binds only the post-effect provider encoding stage.     let maintenanceReassignmentEncoder: (@Sendable (ReassignmentResult) throws -> String)? @@ -78,7 +82,9 @@ final class MCPToolHandler {         readService: MCPReadService? = nil,         readCoordinator: MCPReadCoordinator? = nil,         reusableSnapshots: MCPReusableSnapshotStore? = nil,-        maintenanceReassignmentEncoder: (@Sendable (ReassignmentResult) throws -> String)? = nil+        maintenanceReassignmentEncoder: (@Sendable (ReassignmentResult) throws -> String)? = nil,+        batchContainer: ModelContainer? = nil,+        batchResultEncoder: MCPResultProviderSelection.EncodeOutcome? = nil     ) {         self.taskService = taskService         self.taskFetcher = taskFetcher ?? taskService@@ -109,6 +115,8 @@ final class MCPToolHandler {             return try MCPReusableSnapshotStore(domain: domain)         }         self.writeCoordinator = writeCoordinator+        self.batchContainer = batchContainer+        self.batchResultEncoder = batchResultEncoder         self.maintenanceReassignmentEncoder = maintenanceReassignmentEncoder         self.readService = readService     }@@ -357,26 +365,7 @@ final class MCPToolHandler {         }          if MCPWriteCommand.protectedTools.contains(name) {-            let result: MCPToolResult-            if let writeCoordinator {-                result = await writeCoordinator.execute(tool: name, arguments: arguments)-            } else {-                do {-                    let command = try MCPWriteCommand.validate(tool: name, arguments: arguments)-                    result = MCPWriteOutcome.result(-                        MCPWriteOutcome.failure(-                            tool: name, key: command.key,-                            failure: .init("PERSISTENCE_UNAVAILABLE", "Protected write storage is not available"),-                            accepted: false, retryAction: "retry_same_request"-                        ), isError: true)-                } catch {-                    result = MCPWriteOutcome.result(-                        MCPWriteOutcome.failure(-                            tool: name, key: arguments["idempotencyKey"] as? String,-                            failure: MCPWriteFailure.from(error), accepted: false-                        ), isError: true)-                }-            }+            let result = await protectedWriteResult(tool: name, arguments: arguments)             return JSONRPCResponse.success(id: id, result: result)         } @@ -749,4 +738,48 @@ extension MCPToolHandler {  } +extension MCPToolHandler {+    /// Shared with batch invocation; the default policy preserves standalone behavior.+    func protectedWriteResult(+        tool: String, arguments: [String: Any], batchPolicy: MCPBatchWritePolicy? = nil+    ) async -> MCPToolResult {+        if let writeCoordinator {+            return await writeCoordinator.execute(tool: tool, arguments: arguments, batchPolicy: batchPolicy)+        }+        do {+            let command = try MCPWriteCommand.validate(tool: tool, arguments: arguments)+            return MCPWriteOutcome.result(MCPWriteOutcome.failure(tool: tool, key: command.key,+                failure: .init("PERSISTENCE_UNAVAILABLE", "Protected write storage is not available"),+                accepted: false, retryAction: "retry_same_request"), isError: true)+        } catch {+            return MCPWriteOutcome.result(MCPWriteOutcome.failure(tool: tool,+                key: arguments["idempotencyKey"] as? String, failure: MCPWriteFailure.from(error), accepted: false),+                isError: true)+        }+    }++    func batchPreview(_ request: MCPBatchTaskRequest) throws -> MCPBatchTaskPreview.Report {+        guard let batchContainer else {+            return .init(entries: request.items.map {+                .init(index: $0.index, itemId: $0.itemId, state: .unavailable, code: "PERSISTENCE_UNAVAILABLE",+                      current: nil, proposedEffects: nil)+            }, observation: "saved_local_store", keyState: "unchecked", advisory: true, isError: true)+        }+        return try MCPBatchTaskPreview.evaluate(request, container: batchContainer, persistence: persistence)+    }++    func executeBatchItem(_ item: MCPBatchTaskRequest.Item) async throws -> MCPBatchTaskCoordinator.Execution {+        var pendingEditsStop = false+        let policy = MCPBatchWritePolicy(onPendingEditsStop: { pendingEditsStop = true })+        let result = await protectedWriteResult(tool: item.command.tool,+            arguments: item.command.arguments, batchPolicy: policy)+        guard result.content.count == 1, let text = result.content.first?.text else {+            throw MCPResultBoundaryError.unsupportedEvidence+        }+        let source = try MCPResultAdapter.source(text: text, isError: result.isError,+            origin: .retainedJSON, evidence: .established)+        return .init(source: source, pendingEditsStop: pendingEditsStop)+    }+}+ #endif
Transit/Transit/MCP/Results/MCPModernProviderBinding.swift Modified +2 / -0
diff --git a/Transit/Transit/MCP/Results/MCPModernProviderBinding.swift b/Transit/Transit/MCP/Results/MCPModernProviderBinding.swiftindex 9e13cf05..8943ed1b 100644--- a/Transit/Transit/MCP/Results/MCPModernProviderBinding.swift+++ b/Transit/Transit/MCP/Results/MCPModernProviderBinding.swift@@ -83,6 +83,8 @@ nonisolated enum MCPModernProviderBinding {                 execution = .coveredRead             } else if $0.name == "scan_duplicate_display_ids" {                 execution = .ordinaryRead+            } else if $0.name == "mutate_tasks" {+                execution = .applicationBatch             } else if $0.name == "reassign_duplicate_display_ids" {                 execution = .unprotectedMaintenance             } else {
Transit/Transit/MCP/Writes/MCPWriteCommand.swift Modified +4 / -5
diff --git a/Transit/Transit/MCP/Writes/MCPWriteCommand.swift b/Transit/Transit/MCP/Writes/MCPWriteCommand.swiftindex a2542621..12268c7f 100644--- a/Transit/Transit/MCP/Writes/MCPWriteCommand.swift+++ b/Transit/Transit/MCP/Writes/MCPWriteCommand.swift@@ -173,13 +173,12 @@ struct MCPWriteCommand {                 milestoneService: services.milestones)             return try saved(MCPRecordSnapshot.task(task, in: services.context))         }-        guard let status = TaskStatus(rawValue: try string("status")) else {+        let validation = try MCPTaskMutationValidation.status(+            currentStatus: task.statusRawValue, targetStatus: try string("status"),+            comment: arguments["comment"] as? String, authorName: arguments["authorName"] as? String)+        guard let status = TaskStatus(rawValue: validation.targetStatus) else {             throw MCPWriteFailure("INVALID_STATUS", "Invalid task status")         }-        if arguments["comment"] != nil,-            (arguments["authorName"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty != false {-            throw MCPWriteFailure("INVALID_INPUT", "authorName is required when comment is provided")-        }         let comment = try services.tasks.updateStatus(             task: task, to: status,             comment: arguments["comment"] as? String,
Transit/Transit/MCP/Writes/MCPWriteCoordinator+Outcomes.swift Added +59 / -0
diff --git a/Transit/Transit/MCP/Writes/MCPWriteCoordinator+Outcomes.swift b/Transit/Transit/MCP/Writes/MCPWriteCoordinator+Outcomes.swiftnew file mode 100644index 00000000..095ee61e--- /dev/null+++ b/Transit/Transit/MCP/Writes/MCPWriteCoordinator+Outcomes.swift@@ -0,0 +1,59 @@+#if os(macOS)+import Foundation++// Shared outcome construction stays byte-compatible for standalone and batch calls.+@MainActor extension MCPWriteCoordinator {+    func replay(_ receipt: MCPWriteReceipt) -> MCPToolResult? {+        guard let json = receipt.resultJSON, let isError = receipt.resultIsError else { return nil }+        return MCPToolResult(content: [.text(json)], isError: isError ? true : nil)+    }++    func reused(_ command: MCPWriteCommand) -> MCPToolResult {+        transient(+            command, .init("IDEMPOTENCY_KEY_REUSED", "The key is already bound to different arguments"),+            accepted: false)+    }++    func uncertain(_ command: MCPWriteCommand) -> MCPToolResult {+        transient(+            command, .init("OUTCOME_UNCERTAIN", "Reconcile the original operation before issuing another write"),+            accepted: true, outcome: "uncertain", retry: "reconcile")+    }++    func transient(+        _ command: MCPWriteCommand, _ failure: MCPWriteFailure, accepted: Bool?,+        outcome: String = "rejected", retry: String? = nil+    ) -> MCPToolResult {+        MCPWriteOutcome.result(+            MCPWriteOutcome.failure(+                tool: command.tool, key: command.key,+                failure: failure, accepted: accepted,+                outcome: outcome, retryAction: retry), isError: true)+    }+    /// Existing durable validation only: no guard repair, expiry write, recovery+    /// hook, domain lookup or shared-context mutation is permitted in this path.+    func inspectRetainedWhileDirty(+        _ command: MCPWriteCommand, payload: String,+        reservations: MCPLocalReservationStore, receipts: MCPWriteReceiptStore, now: Date,+        batchPolicy: MCPBatchWritePolicy? = nil+    ) -> MCPToolResult {+        switch MCPBatchWritePolicy.inspectRetained(+            command, payload: payload, reservations: reservations, receipts: receipts, now: now) {+        case .terminal(let receipt):+            return replay(receipt) ?? dirtyUnavailable(command, accepted: true, batchPolicy: batchPolicy)+        case .reused: return reused(command)+        case .unavailable(let accepted): return dirtyUnavailable(command, accepted: accepted, batchPolicy: batchPolicy)+        }+    }++    func dirtyUnavailable(+        _ command: MCPWriteCommand, accepted: Bool?, batchPolicy: MCPBatchWritePolicy? = nil+    ) -> MCPToolResult {+        batchPolicy?.onPendingEditsStop()+        return transient(+            command, .init("OUTCOME_UNCERTAIN", "Pending UI edits prevent recovery; reconcile the original key"),+            accepted: accepted, outcome: "uncertain", retry: "reconcile")+    }++}+#endif
Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift Modified +40 / -40
diff --git a/Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift b/Transit/Transit/MCP/Writes/MCPWriteCoordinator.swiftindex 9fb72601..11931b16 100644--- a/Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift+++ b/Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift@@ -19,7 +19,6 @@ import SwiftData     private let receipts: MCPWriteReceiptStore?     private let startupFailure: MCPWriteFailure?     private var active: [String: String] = [:]-     init(         services: MCPWriteCommandServices, sidecarDirectory: URL,         persistence: PersistenceAvailability? = nil,@@ -69,7 +68,9 @@ import SwiftData         }     } -    func execute(tool: String, arguments: [String: Any]) async -> MCPToolResult {+    func execute(+        tool: String, arguments: [String: Any], batchPolicy: MCPBatchWritePolicy? = nil+    ) async -> MCPToolResult {         let command: MCPWriteCommand         do { command = try MCPWriteCommand.validate(tool: tool, arguments: arguments) } catch {             return MCPWriteOutcome.result(@@ -102,9 +103,14 @@ import SwiftData                 command, .init("OPERATION_IN_PROGRESS", "Retry the same request after completion"),                 accepted: true, outcome: "in_progress", retry: "retry_same_request")         }+        if batchPolicy != nil && services.context.hasChanges {+            return inspectRetainedWhileDirty(+                command, payload: payload, reservations: reservations, receipts: receipts,+                now: clock(), batchPolicy: batchPolicy)+        }         return await accept(-            command, payload: payload, namespace: namespace,-            reservations: reservations, receipts: receipts)+            command, payload: payload,+            reservations: reservations, receipts: receipts, batchPolicy: batchPolicy)     } } @@ -141,13 +147,15 @@ extension MCPWriteCoordinator {     }      fileprivate func accept(-        _ command: MCPWriteCommand, payload: String, namespace: String,-        reservations: MCPLocalReservationStore, receipts: MCPWriteReceiptStore+        _ command: MCPWriteCommand, payload: String,+        reservations: MCPLocalReservationStore, receipts: MCPWriteReceiptStore,+        batchPolicy: MCPBatchWritePolicy?     ) async -> MCPToolResult {         let acceptance: Acceptance         do {             acceptance = try reservations.withValidatedBindings {-                acceptSynchronously(command, payload: payload, reservations: reservations, receipts: receipts)+                acceptSynchronously(+                    command, payload: payload, reservations: reservations, receipts: receipts, batchPolicy: batchPolicy)             }         } catch {             return transient(@@ -157,19 +165,26 @@ extension MCPWriteCoordinator {         switch acceptance {         case .result(let result): return result         case .ready(let guardRecord, let receipt):+            let namespace = command.tool + "\u{0000}" + command.key             active[namespace] = payload             defer { active.removeValue(forKey: namespace) }             // The acceptance snapshot is gone before entering any async method.             return await runAccepted(                 command, guardRecord: guardRecord, receipt: receipt,-                reservations: reservations, receipts: receipts)+                reservations: reservations, batchPolicy: batchPolicy)         }     }      private func acceptSynchronously(         _ command: MCPWriteCommand, payload: String,-        reservations: MCPLocalReservationStore, receipts: MCPWriteReceiptStore+        reservations: MCPLocalReservationStore, receipts: MCPWriteReceiptStore,+        batchPolicy: MCPBatchWritePolicy?     ) -> Acceptance {+        if batchPolicy != nil && services.context.hasChanges {+            return .result(inspectRetainedWhileDirty(+                command, payload: payload, reservations: reservations, receipts: receipts,+                now: clock(), batchPolicy: batchPolicy))+        }         let tool = command.tool         if let existing = existingOutcome(command, payload: payload, reservations: reservations, receipts: receipts) {             return .result(existing)@@ -215,14 +230,22 @@ extension MCPWriteCoordinator {      fileprivate func runAccepted(         _ command: MCPWriteCommand, guardRecord: MCPLocalReservation, receipt: MCPWriteReceipt,-        reservations: MCPLocalReservationStore, receipts: MCPWriteReceiptStore+        reservations: MCPLocalReservationStore,+        batchPolicy: MCPBatchWritePolicy?     ) async -> MCPToolResult {         let prepared: PreparedMCPWrite         do {             try await preparationHook(command)+            if batchPolicy != nil && services.context.hasChanges {+                return dirtyUnavailable(command, accepted: true, batchPolicy: batchPolicy)+            }             prepared = try await command.prepare(using: services)             try Task.checkCancellation()         } catch {+            // Return before a rejection phase can save or roll back UI edits.+            if batchPolicy != nil && services.context.hasChanges {+                return dirtyUnavailable(command, accepted: true, batchPolicy: batchPolicy)+            }             // Validate a fresh scope after suspension, before retaining rejection.             do {                 return try reservations.withValidatedBindings {@@ -232,26 +255,31 @@ extension MCPWriteCoordinator {                 }             } catch { return uncertain(command) }         }+        if batchPolicy != nil && services.context.hasChanges {+            return dirtyUnavailable(command, accepted: true, batchPolicy: batchPolicy)+        }         do {             // No snapshot survives preparation. This fresh phase covers baseline,             // mutation, terminal save, expiry repair, and synchronous recovery.             return try reservations.withValidatedBindings {                 try reservations.validateBinding(guardRecord)                 if services.context.hasChanges { try save(services.context, .baseline) }-                return commit(command, prepared: prepared, receipt: receipt, guardRecord: guardRecord)+                return commit(+                    command, prepared: prepared, receipt: receipt, guardRecord: guardRecord, batchPolicy: batchPolicy)             }         } catch { return uncertain(command) }     }      fileprivate func commit(         _ command: MCPWriteCommand, prepared: PreparedMCPWrite,-        receipt: MCPWriteReceipt, guardRecord: MCPLocalReservation+        receipt: MCPWriteReceipt, guardRecord: MCPLocalReservation, batchPolicy: MCPBatchWritePolicy?     ) -> MCPToolResult {         let context = services.context         let autosave = context.autosaveEnabled         context.autosaveEnabled = false         defer { context.autosaveEnabled = autosave }         do {+            try batchPolicy?.validateBeforeApply(command, context)             var envelope = try command.apply(prepared, using: services)             envelope["contractVersion"] = 1             envelope["tool"] = command.tool@@ -368,33 +396,5 @@ extension MCPWriteCoordinator {         receipt.resultIsError = rejected         return MCPToolResult(content: [.text(json)], isError: rejected ? true : nil)     }--    fileprivate func replay(_ receipt: MCPWriteReceipt) -> MCPToolResult? {-        guard let json = receipt.resultJSON, let isError = receipt.resultIsError else { return nil }-        return MCPToolResult(content: [.text(json)], isError: isError ? true : nil)-    }--    fileprivate func reused(_ command: MCPWriteCommand) -> MCPToolResult {-        transient(-            command, .init("IDEMPOTENCY_KEY_REUSED", "The key is already bound to different arguments"),-            accepted: false)-    }--    fileprivate func uncertain(_ command: MCPWriteCommand) -> MCPToolResult {-        transient(-            command, .init("OUTCOME_UNCERTAIN", "Reconcile the original operation before issuing another write"),-            accepted: true, outcome: "uncertain", retry: "reconcile")-    }--    fileprivate func transient(-        _ command: MCPWriteCommand, _ failure: MCPWriteFailure, accepted: Bool?,-        outcome: String = "rejected", retry: String? = nil-    ) -> MCPToolResult {-        MCPWriteOutcome.result(-            MCPWriteOutcome.failure(-                tool: command.tool, key: command.key,-                failure: failure, accepted: accepted,-                outcome: outcome, retryAction: retry), isError: true)-    } } #endif
Transit/Transit/Services/CommentInputValidation.swift Added +23 / -0
diff --git a/Transit/Transit/Services/CommentInputValidation.swift b/Transit/Transit/Services/CommentInputValidation.swiftnew file mode 100644index 00000000..4aa0fa63--- /dev/null+++ b/Transit/Transit/Services/CommentInputValidation.swift@@ -0,0 +1,23 @@+import Foundation++/// Pure comment inputs shared by macOS automation and service callers.+/// Service mutation and error mapping remain with CommentService.+nonisolated enum CommentInputValidation {+    struct Input: Sendable, Equatable {+        let content: String+        let authorName: String+    }++    enum Error: Swift.Error, Sendable, Equatable {+        case emptyContent+        case emptyAuthorName+    }++    static func normalize(content: String, authorName: String) throws -> Input {+        let content = content.trimmingCharacters(in: .whitespacesAndNewlines)+        guard !content.isEmpty else { throw Error.emptyContent }+        let author = authorName.trimmingCharacters(in: .whitespacesAndNewlines)+        guard !author.isEmpty else { throw Error.emptyAuthorName }+        return Input(content: content, authorName: author)+    }+}
Transit/Transit/Services/CommentService.swift Modified +10 / -7
diff --git a/Transit/Transit/Services/CommentService.swift b/Transit/Transit/Services/CommentService.swiftindex 530a7986..294b3e15 100644--- a/Transit/Transit/Services/CommentService.swift+++ b/Transit/Transit/Services/CommentService.swift@@ -54,19 +54,22 @@ final class CommentService: CommentFetching {         isAgent: Bool,         save: ((ModelContext) throws -> Void)? = { try $0.save() }     ) throws -> Comment {-        let trimmedContent = content.trimmingCharacters(in: .whitespacesAndNewlines)-        guard !trimmedContent.isEmpty else { throw Error.emptyContent }--        let trimmedAuthor = authorName.trimmingCharacters(in: .whitespacesAndNewlines)-        guard !trimmedAuthor.isEmpty else { throw Error.emptyAuthorName }+        let input: CommentInputValidation.Input+        do {+            input = try CommentInputValidation.normalize(content: content, authorName: authorName)+        } catch CommentInputValidation.Error.emptyContent {+            throw Error.emptyContent+        } catch CommentInputValidation.Error.emptyAuthorName {+            throw Error.emptyAuthorName+        }          // Resolve the task in this service's context to ensure the         // relationship is established within a single ModelContext.         let resolvedTask = try resolveTask(task)          let comment = Comment(-            content: trimmedContent,-            authorName: trimmedAuthor,+            content: input.content,+            authorName: input.authorName,             isAgent: isAgent,             task: resolvedTask         )
Transit/Transit/TransitApp.swift Modified +1 / -1
diff --git a/Transit/Transit/TransitApp.swift b/Transit/Transit/TransitApp.swiftindex cb5d6b34..7f9b2108 100644--- a/Transit/Transit/TransitApp.swift+++ b/Transit/Transit/TransitApp.swift@@ -169,7 +169,7 @@ struct TransitApp: App {             commentService: commentService, milestoneService: milestoneService,             maintenanceService: maintenanceService, settings: mcpSettings,             persistence: persistence, taskQuerySnapshots: reads.snapshots, writeCoordinator: writeCoordinator,-            readService: reads, readCoordinator: readCoordinator+            readService: reads, readCoordinator: readCoordinator, batchContainer: container         )         self.mcpServer = MCPServer(toolHandler: mcpToolHandler, readCoordinator: readCoordinator)         #endif
Transit/TransitTests/MCPBatchTaskAggregateTests.swift Added +188 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskAggregateTests.swift b/Transit/TransitTests/MCPBatchTaskAggregateTests.swiftnew file mode 100644index 00000000..848e230d--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskAggregateTests.swift@@ -0,0 +1,188 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPBatchTaskAggregateTests {+    private typealias Sequence = MCPBatchTaskCoordinatorSequenceFixtures+    private typealias Fixture = MCPBatchTaskResultFixtures++    @Test(arguments: [nil, false, true] as [Bool?])+    func nestedOriginalValueTextAndOptionalFlagStayExact(flag: Bool?) async throws {+        let request = try Sequence.request(count: 1)+        let text = Fixture.committed(extra: #", "unknown":{"n":1E9999,"null":null,"source":"collision"}"#)+            .replacingOccurrences(of: Fixture.taskID.uuidString, with: request.items[0].targetTaskId.uuidString)+            .replacingOccurrences(of: Fixture.key, with: request.items[0].command.key)+        let original = try MCPResultAdapter.source(text: text, isError: flag,+                                                   origin: .retainedJSON, evidence: .established)+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Sequence.prepared(request), executor: { _ in+            .init(source: original)+        })+        let report = try await batch.run(request)+        let source = try MCPBatchTaskResult.execution(request, report: report)+        #expect(Fixture.field("mode", in: source.document?.value) == .string("execute"))+        let nested = try originalResult(source)+        #expect(Fixture.field("payload", in: nested) == original.document?.value)+        #expect(Fixture.field("text", in: nested) == .string(text))+        let retainedText = try #require(MCPBatchTaskInputValue.string(Fixture.field("text", in: nested)))+        #expect(retainedText.utf8.elementsEqual(text.utf8))+        let retainedBytes = try #require(original.document?.originalUTF8)+        #expect(source.document?.originalUTF8.range(of: retainedBytes) != nil)+        #expect(Fixture.field("isError", in: nested) == flag.map(MCPJSONValue.boolean))+        #expect(source.originalIsError == (flag == true ? true : nil))+        #expect(source.originalText.contains("1E9999"))+    }++    @Test(arguments: ["malformed", "unknown"])+    func unreadableAndUnsupportedRetainAvailableOriginalEvidence(kind: String) async throws {+        let request = try Sequence.request(count: 1)+        let original = try Sequence.source(request.items[0], kind: kind)+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Sequence.prepared(request), executor: { _ in+            .init(source: original)+        })+        let report = try await batch.run(request)+        let source = try MCPBatchTaskResult.execution(request, report: report)+        let nested = try originalResult(source)+        #expect(Fixture.field("text", in: nested) == .string(original.originalText))+        #expect(Fixture.field("payload", in: nested) == original.document?.value)+        #expect(Fixture.field("isError", in: nested) == original.originalIsError.map(MCPJSONValue.boolean))+        #expect(Fixture.field("summary", in: source.document?.value) == .string("evidence_unavailable"))+        #expect(source.originalIsError == true)+    }++    @Test func skippedMappingsDoNotInventAcceptanceOrReceipts() async throws {+        let request = try Sequence.request(count: 3)+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Sequence.prepared(request), executor: { item in+            .init(source: try Sequence.source(item, kind: "rejected"))+        })+        let report = try await batch.run(request)+        let source = try MCPBatchTaskResult.execution(request, report: report)+        guard case .array(let items) = Fixture.field("items", in: source.document?.value) else {+            Issue.record("Expected mapped entries"); return+        }+        #expect(items.count == 3)+        for index in 1...2 {+            #expect(Fixture.field("state", in: items[index]) == .string("not_attempted"))+            #expect(Fixture.field("itemId", in: items[index]) == .string(request.items[index].itemId))+            let mapped = try #require(MCPBatchTaskInputValue.string(Fixture.field("taskId", in: items[index])))+            let original = try #require(request.items[index].command.arguments["taskId"] as? String)+            #expect(mapped.utf8.elementsEqual(original.utf8))+            #expect(UUID(uuidString: mapped) == request.items[index].targetTaskId)+            for name in ["originalResult", "accepted", "record", "receipt", "replayExpiresAt"] {+                #expect(Fixture.field(name, in: items[index]) == nil)+            }+        }+        #expect(Fixture.field("atomicity", in: source.document?.value) == .string("per_item"))+    }++    @Test func modernStructuredPayloadIsTheSameLogicalSourceOnce() async throws {+        let request = try Sequence.request(count: 1)+        let prepared = try Sequence.prepared(request)+        let batch = MCPBatchTaskCoordinator(preparedResponse: prepared, executor: { item in+            .init(source: try Sequence.source(item))+        })+        let report = try await batch.run(request)+        let source = try MCPBatchTaskResult.execution(request, report: report)+        let bytes = try MCPResultProviderSelection.encode(outcome: .init(source: source, context: prepared.context),+                                                          id: .string("aggregate.rpc"), metadata: nil)+        let result = try Fixture.result(bytes)+        let structured = Fixture.field("structuredContent", in: result)+        #expect(Fixture.field("payload", in: Fixture.field("source", in: structured)) == source.document?.value)+        #expect(Fixture.field("isError", in: result) == nil)+        guard case .array(let content) = Fixture.field("content", in: result) else {+            Issue.record("Expected compatible text"); return+        }+        #expect(Fixture.field("text", in: content[0]) == .string(source.originalText))+    }++    @Test func previewAndShapeDiagnosticsHaveIndependentErrorFlags() throws {+        let fixture = try MCPBatchTaskCoordinatorFixture()+        let input = try MCPJSONDocument.parse(JSONSerialization.data(withJSONObject:+            ["mode": "dry_run", "items": [fixture.item(0)]]))+        guard case .valid(let request) = try MCPBatchTaskRequest.parse(input) else {+            throw MCPResultBoundaryError.invalidJSON+        }+        let report = try MCPBatchTaskPreview.evaluate(request, container: fixture.owner.container,+                                                     persistence: PersistenceAvailability())+        let preview = try MCPBatchTaskResult.preview(request, report: report)+        #expect(preview.originalIsError == nil)+        #expect(Fixture.field("mode", in: preview.document?.value) == .string("dry_run"))+        #expect(Fixture.field("summary", in: preview.document?.value) == .string("preview_valid"))+        #expect(Fixture.field("observation", in: preview.document?.value) == .string("saved_local_store"))+        #expect(Fixture.field("confirmedCommittedCount", in: preview.document?.value) == nil)+        let rejected = try MCPBatchTaskResult.invalidInput([.init(index: 1, itemId: "caller", field: "taskId",+                                                                 code: "INVALID_INPUT")])+        #expect(rejected.originalIsError == true)+        #expect(Fixture.field("confirmedCommittedCount", in: rejected.document?.value) == nil)+        #expect(Fixture.field("accepted", in: rejected.document?.value) == nil)+        #expect(Fixture.field("summary", in: rejected.document?.value) == .string("rejected_input"))+        #expect(fixture.saveStages.isEmpty && !fixture.owner.context.hasChanges)+    }++    @Test func realCommitThenEncodingFailureSelectsReadyBytesWithoutReencoding() async throws {+        let fixture = try MCPBatchTaskCoordinatorFixture()+        let request = try fixture.request([fixture.item(0, changes: ["name": "Real durable effect"])])+        let prepared = try Sequence.prepared(request)+        let expected = try MCPResultEncoder.prepareMutationFallback(id: .string("task9.request"),+            source: MCPBatchTaskFallback.source(items: recovery(request)), context: prepared.context, metadata: nil)+        let batch = MCPBatchTaskCoordinator(preparedResponse: prepared,+                                           writeCoordinator: try #require(fixture.coordinator))+        let report = try await batch.run(request)+        #expect(report.confirmedCommittedCount == 1)+        let source = try MCPBatchTaskResult.execution(request, report: report)+        let counts = MCPBatchTaskEncodingCounts()+        let context = prepared.context+        let selected = try await prepared.select(encodeOutcome: { _, _, _ in+            counts.record("encode"); throw MCPResultBoundaryError.resourceLimit+        }, dispatch: { .init(source: source, context: context) })+        #expect(try Fixture.reconciliation(selected) == expected)+        #expect(counts.snapshot().encode == 1)+        #expect(try fixture.durableTasks().first { $0.id == fixture.tasks[0].id }?.name == "Real durable effect")+        let suppressed = try await prepared.select(shouldDeliver: { false }, dispatch: {+            Issue.record("Suppressed delivery before dispatch must execute nothing")+            throw MCPResultBoundaryError.unsupportedEvidence+        })+        guard case .suppressed = suppressed else { Issue.record("Expected delivery suppression"); return }+    }++    @Test func nestedDepthOverflowAfterRealCommitUsesCompactFallback() async throws {+        let fixture = try MCPBatchTaskCoordinatorFixture()+        let giant = String(repeating: "giant-id", count: 30_000)+        var value = try fixture.item(0)+        value["itemId"] = giant+        let request = try fixture.request([value])+        let prepared = try Sequence.prepared(request)+        let source = try await fixture.source(request.items[0])+        let tail = ",\"deep\":" + String(repeating: "[", count: 31) + "null" + String(repeating: "]", count: 31) + "}"+        let original = try MCPResultAdapter.source(text: String(source.originalText.dropLast()) + tail,+            isError: source.originalIsError, origin: .retainedJSON, evidence: .established)+        #expect(original.document != nil)+        let batch = MCPBatchTaskCoordinator(preparedResponse: prepared, executor: { _ in .init(source: original) })+        let report = try await batch.run(request)+        #expect(report.confirmedCommittedCount == 1)+        let selected = try await prepared.select(dispatch: { @MainActor in+            let aggregate = try MCPBatchTaskResult.execution(request, report: report)+            return .init(source: aggregate, context: prepared.context)+        })+        let bytes = try Fixture.reconciliation(selected)+        let wire = try #require(String(data: bytes, encoding: .utf8))+        #expect(wire.contains("serialization_failed") && !wire.contains(giant) && !wire.contains("deep"))+        #expect(try fixture.durableTasks().first { $0.id == fixture.tasks[0].id }?.taskDescription ==+            "Canonical description")+    }++    private func originalResult(_ source: MCPResultSource) throws -> MCPJSONValue {+        guard case .array(let items) = Fixture.field("items", in: source.document?.value) else {+            throw MCPResultBoundaryError.invalidJSON+        }+        return try #require(Fixture.field("originalResult", in: items[0]))+    }++    private func recovery(_ request: MCPBatchTaskRequest) -> [MCPBatchRecoveryItem] {+        request.items.map { .init(index: $0.index, itemId: $0.itemId, operation: $0.operation,+            originalKey: .init(tool: $0.command.tool, idempotencyKey: $0.command.key), targetTaskId: $0.targetTaskId) }+    }+}+#endif
Transit/TransitTests/MCPBatchTaskCoordinatorBaselineTests.swift Added +166 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskCoordinatorBaselineTests.swift b/Transit/TransitTests/MCPBatchTaskCoordinatorBaselineTests.swiftnew file mode 100644index 00000000..b4ea471a--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskCoordinatorBaselineTests.swift@@ -0,0 +1,166 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++/// Existing protected coordinator controls run independently of the RED loop.+@MainActor @Suite(.serialized)+struct MCPBatchTaskCoordinatorBaselineTests {+    private typealias Fixture = MCPBatchTaskCoordinatorFixture++    @Test+    func terminalReplayAfterRestartIsByteExactWithoutNewComment() async throws {+        let fixture = try Fixture()+        let request = try fixture.request([fixture.item(0, operation: "add_comment")])+        let source = try await fixture.source(request.items[0])+        fixture.restart()+        let replay = try await fixture.source(request.items[0])+        #expect(replay.originalText == source.originalText && replay.originalIsError == source.originalIsError)+        #expect(try fixture.durableComments().count == 1)+    }++    @Test+    func transientStoreBusyRetainsSameRequestRetryWithoutAcceptingKey() async throws {+        let fixture = try Fixture()+        let request = try fixture.request([fixture.item(0)])+        let blocked = MCPWriteCoordinator(services: fixture.services,+            sidecarDirectory: fixture.directory.appendingPathComponent("keys"), persistence: PersistenceAvailability())+        let result = await blocked.execute(tool: request.items[0].operation,+            arguments: request.items[0].command.arguments)+        let value = try MCPJSONDocument.parse(result.content[0].text).value+        #expect(field("outcome", value) == .string("rejected"))+        #expect(field("accepted", value) == .boolean(false))+        #expect(field("retryAction", value) == .string("retry_same_request"))+        #expect(try fixture.owner.context.fetch(FetchDescriptor<MCPWriteReceipt>()).isEmpty)+        fixture.restart()+        let source = try await fixture.source(request.items[0])+        #expect(field("outcome", source.document?.value) == .string("committed"))+    }++    @Test+    func sharedKeyConcurrentSubmissionUsesExistingInProgressAndReplay() async throws {+        let fixture = try Fixture()+        let request = try fixture.request([fixture.item(0, operation: "add_comment")])+        let gate = MCPBatchTaskCoordinatorGate()+        fixture.preparation = { _ in await gate.park() }+        let first = Task { @MainActor in try await fixture.source(request.items[0]) }+        guard await gate.waitForStart() else {+            await gate.release()+            _ = try await first.value+            Issue.record("Existing coordinator failed to reach bounded preparation gate")+            return+        }+        let competing: MCPResultSource+        do { competing = try await fixture.source(request.items[0]) } catch {+            await gate.release()+            _ = try await first.value+            throw error+        }+        #expect(field("outcome", competing.document?.value) == .string("in_progress"))+        #expect(field("retryAction", competing.document?.value) == .string("retry_same_request"))+        await gate.release()+        let committed = try await first.value+        let replay = try await fixture.source(request.items[0])+        #expect(replay.originalText == committed.originalText)+        #expect(try fixture.durableComments().count == 1)+    }++    @Test+    func unresolvedAcceptedOriginalKeyRetryRecoversRejectionWithoutApplying() async throws {+        let fixture = try Fixture()+        let request = try fixture.request([fixture.item(0)])+        fixture.preparation = { [unowned fixture] _ in fixture.tasks[0].name = "Pending accepted UI edit" }+        let stop = try await fixture.source(request.items[0], batchPolicy: MCPBatchWritePolicy())+        #expect(field("outcome", stop.document?.value) == .string("uncertain"))+        #expect(field("accepted", stop.document?.value) == .boolean(true))+        #expect(field("retryAction", stop.document?.value) == .string("reconcile"))+        try fixture.owner.context.save() // Independent owner action; never the batch loop.+        fixture.restart()+        let retry = try await fixture.source(request.items[0])+        #expect(field("outcome", retry.document?.value) == .string("rejected"))+        #expect(field("retryAction", retry.document?.value) == .string("new_request_new_key"))+        #expect(try fixture.durableTasks().first { $0.id == fixture.tasks[0].id }?.taskDescription == nil)+    }++    @Test+    func differentIsolatedLocalStoresDoNotShareRetryNamespace() async throws {+        let first = try Fixture()+        let second = try Fixture()+        let firstRequest = try first.request([first.item(0, operation: "add_comment")])+        let secondRequest = try second.request([second.item(0, operation: "add_comment")])+        #expect(firstRequest.items[0].command.key == secondRequest.items[0].command.key)+        let firstSource = try await first.source(firstRequest.items[0])+        let secondSource = try await second.source(secondRequest.items[0])+        #expect(field("outcome", firstSource.document?.value) == .string("committed"))+        #expect(field("outcome", secondSource.document?.value) == .string("committed"))+        #expect(try first.durableComments().count == 1 && second.durableComments().count == 1)+    }++    @Test(arguments: ["expiry", "receipt"])+    func missingRetentionEvidenceWhileDirtyNeverProvesNoEffect(missing: String) async throws {+        let fixture = try Fixture()+        let request = try fixture.request([fixture.item(0, operation: "add_comment")])+        _ = try await fixture.source(request.items[0])+        let receipt = try #require(try fixture.owner.context.fetch(FetchDescriptor<MCPWriteReceipt>()).first)+        if missing == "expiry" { receipt.expiresAt = nil } else { fixture.owner.context.delete(receipt) }+        try fixture.owner.context.save()+        fixture.tasks[0].name = "Pending retention check"+        let source = try await fixture.source(request.items[0], batchPolicy: MCPBatchWritePolicy())+        #expect(field("outcome", source.document?.value) == .string("uncertain"))+        #expect(field("retryAction", source.document?.value) == .string("reconcile"))+        #expect(fixture.owner.context.hasChanges && fixture.tasks[0].name == "Pending retention check")+        #expect(try fixture.durableComments().count == 1)+    }++    @Test+    func retainedRejectionReplaysExactlyUntilReviewedFreshKeyCorrection() async throws {+        let fixture = try Fixture()+        let bad = try fixture.item(0, changes: ["priority": "invalid"])+        let request = try fixture.request([bad])+        let rejected = try await fixture.source(request.items[0])+        let replay = try await fixture.source(request.items[0])+        #expect(field("outcome", rejected.document?.value) == .string("rejected"))+        #expect(replay.originalText == rejected.originalText && replay.originalIsError == true)+        #expect(field("retryAction", rejected.document?.value) == .string("new_request_new_key"))+        var corrected = bad+        var arguments = try #require(corrected["arguments"] as? [String: Any])+        arguments["priority"] = "high"+        arguments["idempotencyKey"] = "task9.baseline.reviewed.correction"+        corrected["arguments"] = arguments+        let fixedRequest = try fixture.request([corrected])+        let fixed = try await fixture.source(fixedRequest.items[0])+        #expect(field("outcome", fixed.document?.value) == .string("committed"))+    }++    private func field(_ name: String, _ value: MCPJSONValue?) -> MCPJSONValue? {+        MCPBatchTaskResultFixtures.field(name, in: value)+    }+}++actor MCPBatchTaskCoordinatorGate {+    private var parked: CheckedContinuation<Void, Never>?+    private var started = false+    private var released = false++    func park() async {+        started = true+        guard !released else { return }+        await withCheckedContinuation { parked = $0 }+    }++    func waitForStart() async -> Bool {+        for _ in 0..<200 {+            if started { return true }+            do { try await Task.sleep(for: .milliseconds(10)) } catch { return false }+        }+        return false+    }++    func release() {+        released = true+        parked?.resume()+        parked = nil+    }+}+#endif
Transit/TransitTests/MCPBatchTaskCoordinatorDurabilityTests.swift Added +274 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskCoordinatorDurabilityTests.swift b/Transit/TransitTests/MCPBatchTaskCoordinatorDurabilityTests.swiftnew file mode 100644index 00000000..7299ac4c--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskCoordinatorDurabilityTests.swift@@ -0,0 +1,274 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPBatchTaskCoordinatorDurabilityTests {+    private typealias Fixture = MCPBatchTaskCoordinatorFixture+    private typealias Sequence = MCPBatchTaskCoordinatorSequenceFixtures++    private func run(_ request: MCPBatchTaskRequest, fixture: Fixture) async throws -> MCPBatchTaskCoordinator.Report {+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Sequence.prepared(request), executor: {+            try await fixture.execution($0)+        })+        return try await batch.run(request)+    }++    @Test+    func canonicalDescriptionPrecedesDistinctReasonClosures() async throws {+        let fixture = try Fixture()+        let request = try fixture.request([fixture.item(0), fixture.item(1, operation: "update_task_status"),+                                          fixture.item(2, operation: "update_task_status")])+        let report = try await run(request, fixture: fixture)+        #expect(report.summary == "all_committed" && report.confirmedCommittedCount == 3)+        let saved = try fixture.durableTasks()+        #expect(saved.first { $0.id == fixture.tasks[0].id }?.taskDescription == "Canonical description")+        #expect(saved.filter { $0.status == .done }.count == 2)+        let comments = try fixture.durableComments()+        #expect(comments.count == 2 && Set(comments.map(\.id)).count == 2)+        #expect(Set(comments.compactMap { $0.task?.id }) == Set(fixture.tasks.dropFirst().map(\.id)))+        #expect(comments.allSatisfy { $0.content == "Duplicate of canonical" && $0.isAgent })+    }++    @Test(arguments: ["stale", "ambiguous"])+    func freshLaterIdentityOrRevisionFailurePreservesCanonicalPrefix(scenario: String) async throws {+        let fixture = try Fixture()+        let request = try fixture.request([fixture.item(0), fixture.item(1, operation: "update_task_status")])+        if scenario == "stale" { fixture.tasks[1].name = "Saved later edit" } else {+            let duplicate = TransitTask(name: "Duplicate identity", type: .feature,+                project: fixture.project, displayID: .provisional)+            duplicate.id = fixture.tasks[1].id+            fixture.owner.context.insert(duplicate)+        }+        try fixture.owner.context.save()+        let report = try await run(request, fixture: fixture)+        #expect(report.summary == "stopped" && report.confirmedCommittedCount == 1)+        let source = try #require(report.entries[1].originalResult)+        #expect(code(source) == (scenario == "stale" ? "REVISION_CONFLICT" : "DUPLICATE_TASK_IDENTIFIER"))+        #expect(try fixture.durableComments().isEmpty)+        #expect(try fixture.durableTasks().first { $0.id == fixture.tasks[0].id }?.taskDescription+                == "Canonical description")+    }++    @Test(arguments: ["priority", "milestone", "author", "content"])+    func domainFailuresStopWithoutErasingEarlierReceipt(field: String) async throws {+        let fixture = try Fixture()+        let operation = field == "author" ? "update_task_status" : (field == "content" ? "add_comment" : "update_task")+        let changes: [String: Any]+        switch field {+        case "priority": changes = ["priority": "invalid"]+        case "milestone": changes = ["milestoneDisplayId": 999]+        case "author": changes = ["authorName": " \n"]+        default: changes = ["content": " \n"]+        }+        let request = try fixture.request([fixture.item(0), fixture.item(1, operation: operation, changes: changes),+                                          fixture.item(2)])+        let report = try await run(request, fixture: fixture)+        #expect(report.confirmedCommittedCount == 1 && report.summary == "stopped")+        #expect(report.entries[2].state == .notAttempted)+        let source = try #require(report.entries[1].originalResult)+        let expected = field == "priority" ? "INVALID_PRIORITY" :+            (field == "milestone" ? "MILESTONE_NOT_FOUND" : "INVALID_INPUT")+        #expect(code(source) == expected)+        let receipts = try fixture.owner.context.fetch(FetchDescriptor<MCPWriteReceipt>())+        #expect(receipts.contains { $0.key == request.items[0].command.key && $0.stateRawValue == "committed" })+        #expect(!receipts.contains { $0.key == request.items[2].command.key })+    }++    @Test+    func failedStatusCommitPersistsNeitherStatusNorReason() async throws {+        let fixture = try Fixture()+        let request = try fixture.request([fixture.item(0), fixture.item(1, operation: "update_task_status")])+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Sequence.prepared(request), executor: { item in+            fixture.failCommit = item.index == 1+            return try await fixture.execution(item)+        })+        let report = try await batch.run(request)+        #expect(report.confirmedCommittedCount == 1 && report.summary == "stopped")+        #expect(try fixture.durableComments().isEmpty)+        let saved = try fixture.durableTasks()+        #expect(saved.first { $0.id == fixture.tasks[1].id }?.status == .idea)+        #expect(saved.first { $0.id == fixture.tasks[0].id }?.taskDescription == "Canonical description")+    }++    @Test(arguments: ["laterEdit", "deleted"])+    func restartReplayBypassesLiveStateAndPreservesHistoricSource(scenario: String) async throws {+        let fixture = try Fixture()+        let request = try fixture.request([fixture.item(0), fixture.item(1, operation: "update_task_status")])+        let original = try await fixture.source(request.items[0])+        if scenario == "laterEdit" { fixture.tasks[0].taskDescription = "Later canonical contents" } else {+            fixture.owner.context.delete(fixture.tasks[0])+        }+        try fixture.owner.context.save()+        fixture.restart()+        let report = try await run(request, fixture: fixture)+        #expect(report.summary == "all_committed")+        #expect(report.entries[0].originalResult?.originalText == original.originalText)+        #expect(report.entries[0].originalResult?.originalIsError == original.originalIsError)+        let saved = try fixture.durableTasks().first { $0.id == request.items[0].targetTaskId }+        if scenario == "laterEdit" {+            #expect(saved?.taskDescription == "Later canonical contents")+        } else { #expect(saved == nil) }+        #expect(try fixture.durableComments().count == 1)+    }++    @Test+    func regroupingClientMappingDoesNotChangeDirectToolBinding() async throws {+        let fixture = try Fixture()+        var originalItem = try fixture.item(0)+        let direct = try fixture.request([originalItem])+        let original = try await fixture.source(direct.items[0], batchPolicy: nil)+        originalItem["itemId"] = "new caller e\u{301}"+        let regrouped = try fixture.request([fixture.item(1), originalItem])+        let report = try await run(regrouped, fixture: fixture)+        #expect(report.summary == "all_committed")+        #expect(report.entries[1].originalResult?.originalText == original.originalText)+        #expect(report.entries[1].index == 1 && report.entries[1].itemId.utf8.elementsEqual("new caller e\u{301}".utf8))+        #expect(try fixture.owner.context.fetch(FetchDescriptor<MCPWriteReceipt>()).count == 2)+    }++    @Test(arguments: ["payload", "uuidSpelling"])+    func changedOriginalArgumentsUnderRetainedKeyCannotRotateOrReapply(change: String) async throws {+        let fixture = try Fixture()+        let originalItem = try fixture.item(0)+        let originalRequest = try fixture.request([originalItem])+        _ = try await fixture.source(originalRequest.items[0])+        var changed = originalItem+        var arguments = try #require(changed["arguments"] as? [String: Any])+        if change == "payload" { arguments["description"] = "Changed plan" } else {+            arguments["taskId"] = fixture.tasks[0].id.uuidString.lowercased()+        }+        changed["arguments"] = arguments+        let report = try await run(fixture.request([changed, fixture.item(1)]), fixture: fixture)+        #expect(report.summary == "stopped" && report.confirmedCommittedCount == 0)+        #expect(code(try #require(report.entries[0].originalResult)) == "IDEMPOTENCY_KEY_REUSED")+        #expect(report.entries[1].state == .notAttempted)+        #expect(try fixture.owner.context.fetch(FetchDescriptor<MCPWriteReceipt>()).count == 1)+    }++    @Test+    func retainedRejectionNeedsCorrectedFreshKey() async throws {+        let fixture = try Fixture()+        let bad = try fixture.item(0, changes: ["priority": "invalid"])+        let rejectedRequest = try fixture.request([bad])+        let retained = try await fixture.source(rejectedRequest.items[0])+        var corrected = bad+        var arguments = try #require(corrected["arguments"] as? [String: Any])+        arguments["priority"] = "high"+        corrected["arguments"] = arguments+        let reused = try await run(fixture.request([corrected]), fixture: fixture)+        #expect(code(try #require(reused.entries[0].originalResult)) == "IDEMPOTENCY_KEY_REUSED")+        arguments["idempotencyKey"] = "task9.reviewed.correction"+        corrected["arguments"] = arguments+        let result = try await run(fixture.request([corrected]), fixture: fixture)+        #expect(result.summary == "all_committed")+        #expect(MCPBatchTaskResultFixtures.field("retryAction", in: retained.document?.value)+                == .string("new_request_new_key"))+    }++    @Test+    func expiredCommentKeyMayCreateNewEffectWithSameOriginalKey() async throws {+        let fixture = try Fixture()+        let request = try fixture.request([fixture.item(0, operation: "add_comment")])+        let original = try await fixture.source(request.items[0])+        fixture.now = fixture.now.addingTimeInterval(8 * 24 * 60 * 60)+        let report = try await run(request, fixture: fixture)+        #expect(report.summary == "all_committed")+        #expect(report.entries[0].originalKey == request.items[0].command.key)+        #expect(report.entries[0].originalResult?.originalText != original.originalText)+        #expect(try fixture.durableComments().count == 2)+    }++    @Test+    func missingReceiptWhileDirtyRequiresOriginalKeyReconciliation() async throws {+        let fixture = try Fixture()+        let request = try fixture.request([fixture.item(0, operation: "add_comment"), fixture.item(1)])+        _ = try await fixture.source(request.items[0])+        let receipt = try #require(try fixture.owner.context.fetch(FetchDescriptor<MCPWriteReceipt>()).first)+        fixture.owner.context.delete(receipt)+        try fixture.owner.context.save()+        fixture.tasks[0].name = "Pending UI edit"+        let report = try await run(request, fixture: fixture)+        #expect(report.summary == "stopped" && report.confirmedCommittedCount == 0)+        #expect(report.stop?.reason == .pendingEdits)+        let source = try #require(report.entries[0].originalResult)+        #expect(MCPBatchTaskResultFixtures.field("retryAction", in: source.document?.value) == .string("reconcile"))+        #expect(fixture.owner.context.hasChanges && fixture.tasks[0].name == "Pending UI edit")+        #expect(try fixture.durableComments().count == 1)+        #expect(report.entries[1].state == .notAttempted)+    }++    @Test+    func acceptedDirtyPreparationStopDoesNotResumeOrFlushUI() async throws {+        let fixture = try Fixture()+        let request = try fixture.request([fixture.item(0), fixture.item(1)])+        fixture.preparation = { [unowned fixture] _ in fixture.tasks[0].name = "Pending after accept" }+        let report = try await run(request, fixture: fixture)+        #expect(report.summary == "stopped" && report.stop?.reason == .pendingEdits)+        #expect(fixture.owner.context.hasChanges && fixture.tasks[0].name == "Pending after accept")+        let source = try #require(report.entries[0].originalResult)+        #expect(MCPBatchTaskResultFixtures.field("accepted", in: source.document?.value) == .boolean(true))+        #expect(MCPBatchTaskResultFixtures.field("retryAction", in: source.document?.value) == .string("reconcile"))+        #expect(report.entries[1].state == .notAttempted)+        #expect(try fixture.durableTasks().first { $0.id == fixture.tasks[0].id }?.name == "Task 0")+    }++    @Test(arguments: ["milestone", "commentCapture"])+    func realPreApplyReferenceOrCommentCaptureFailurePreservesEarlierCommit(stage: String) async throws {+        let fixture = try Fixture(faultMilestoneReads: stage == "milestone")+        let changes: [String: Any] = stage == "milestone" ? ["milestoneDisplayId": 9] : [:]+        let second = try fixture.item(1, changes: changes)+        let request = try fixture.request([fixture.item(0), second, fixture.item(2)])+        if stage == "commentCapture" {+            fixture.preparation = { [unowned fixture] command in+                if command.arguments["taskId"] as? String == fixture.tasks[1].id.uuidString {+                    _ = try MCPRecordSnapshot.task(fixture.tasks[1]) { _ in throw Fixture.Fault.injected }+                }+            }+        }+        let report = try await run(request, fixture: fixture)+        #expect(report.summary == "stopped" && report.confirmedCommittedCount == 1)+        #expect(code(try #require(report.entries[1].originalResult)) == "INTERNAL_ERROR")+        #expect(report.entries[2].state == .notAttempted)+        #expect(try fixture.durableTasks().first { $0.id == fixture.tasks[0].id }?.taskDescription+                == "Canonical description")+        #expect(try fixture.durableComments().isEmpty)+    }++    @Test+    func competingBatchUsesExistingActiveKeyAndDoesNotContinue() async throws {+        let fixture = try Fixture()+        let request = try fixture.request([fixture.item(0, operation: "add_comment"), fixture.item(1)])+        let gate = MCPBatchTaskCoordinatorGate()+        fixture.preparation = { _ in await gate.park() }+        let first = Task { @MainActor in try await fixture.source(request.items[0]) }+        guard await gate.waitForStart() else {+            await gate.release()+            _ = try await first.value+            Issue.record("Existing coordinator failed to reach bounded preparation gate")+            return+        }+        let report: MCPBatchTaskCoordinator.Report+        do { report = try await run(request, fixture: fixture) } catch {+            await gate.release()+            _ = try await first.value+            throw error+        }+        await gate.release()+        _ = try await first.value+        #expect(report.summary == "stopped" && report.confirmedCommittedCount == 0)+        #expect(MCPBatchTaskResultFixtures.field("outcome", in: report.entries[0].originalResult?.document?.value)+                == .string("in_progress"))+        #expect(report.entries[1].state == .notAttempted)+        #expect(try fixture.durableComments().count == 1)+    }++    private func code(_ source: MCPResultSource) -> String? {+        let error = MCPBatchTaskResultFixtures.field("error", in: source.document?.value)+        guard case .string(let code) = MCPBatchTaskResultFixtures.field("code", in: error) else { return nil }+        return code+    }+}+#endif
Transit/TransitTests/MCPBatchTaskCoordinatorFixture.swift Added +144 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskCoordinatorFixture.swift b/Transit/TransitTests/MCPBatchTaskCoordinatorFixture.swiftnew file mode 100644index 00000000..9196a8fa--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskCoordinatorFixture.swift@@ -0,0 +1,144 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++/// Owns persistent test stores for retained replay, restart and durable readback.+/// Stores outlive fixtures because TestModelContainer retains their containers.+@MainActor final class MCPBatchTaskCoordinatorFixture {+    enum Fault: Error { case injected }+    let directory: URL+    let storeURL: URL+    let owner: TestModelContainer+    let project: Project+    let tasks: [TransitTask]+    let services: MCPWriteCommandServices+    var coordinator: MCPWriteCoordinator?+    var now = Date(timeIntervalSince1970: 1_770_000_000)+    var preparation: @MainActor (MCPWriteCommand) async throws -> Void = { _ in }+    var failCommit = false+    var saveStages: [MCPWriteCoordinator.SaveStage] = []+    var recoveryCalls = 0+    private var independentOwners: [TestModelContainer] = []++    init(faultMilestoneReads: Bool = false) throws {+        directory = FileManager.default.temporaryDirectory+            .appendingPathComponent("T2384Task9Coordinator-" + UUID().uuidString)+        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+        print("T2384_TASK9_COORDINATOR_DIRECTORY=" + directory.path)+        storeURL = directory.appendingPathComponent("coordinator.store")+        owner = try Self.owner(storeURL)+        owner.context.autosaveEnabled = false+        let savedProject = Project(name: "Batch project", description: "", gitRepo: nil, colorHex: "#112233")+        project = savedProject+        tasks = (0..<3).map {+            let task = TransitTask(name: "Task \($0)", type: .feature, project: savedProject,+                displayID: .permanent($0 + 1))+            task.id = UUID(uuidString: String(format: "ABCDEFAB-1234-4123-A123-%012d", $0 + 1))!+            return task+        }+        owner.context.insert(project)+        for task in tasks { owner.context.insert(task) }+        try owner.context.save()+        let allocator = DisplayIDAllocator(store: InMemoryCounterStore(), isCloudSyncActive: false)+        services = MCPWriteCommandServices(tasks: TaskService(modelContext: owner.context,+            displayIDAllocator: allocator),+            projects: ProjectService(modelContext: owner.context),+            comments: CommentService(modelContext: owner.context),+            milestones: MilestoneService(modelContext: owner.context, displayIDAllocator: allocator,+                fetcher: MCPBatchTaskCoordinatorMilestoneFetcher(context: owner.context, fail: faultMilestoneReads)),+            context: owner.context)+        restart()+    }++    static func owner(_ url: URL) throws -> TestModelContainer {+        let schema = Schema([Project.self, TransitTask.self, Transit.Comment.self, Milestone.self,+                             SyncHeartbeat.self, MCPWriteReceipt.self])+        return try TestModelContainer(schema: schema, configurations: [ModelConfiguration(+            "Task9", schema: schema, url: url, cloudKitDatabase: .none)])+    }++    func restart() {+        coordinator = nil+        coordinator = MCPWriteCoordinator(services: services,+            sidecarDirectory: directory.appendingPathComponent("keys"),+            persistence: PersistenceAvailability(), clock: { [unowned self] in now },+            save: { [unowned self] context, stage in+                saveStages.append(stage)+                if failCommit && stage == .commit { throw Fault.injected }+                try context.save()+            }, preparationHook: { [unowned self] command in try await preparation(command) },+            recoveryHook: { [unowned self] in recoveryCalls += 1 })+    }++    func item(_ index: Int, operation: String = "update_task", changes: [String: Any] = [:]) throws -> [String: Any] {+        var arguments: [String: Any] = ["taskId": tasks[index].id.uuidString,+                                      "idempotencyKey": "task9.key.\(index)"]+        if operation != "add_comment" {+            arguments["expectedRevision"] = try MCPRecordSnapshot.task(tasks[index], in: owner.context).revision+        }+        if operation == "update_task" { arguments["description"] = "Canonical description" }+        if operation == "update_task_status" {+            arguments["status"] = "done"+            arguments["comment"] = "Duplicate of canonical"+            arguments["authorName"] = "Agent"+        }+        if operation == "add_comment" {+            arguments.merge(["content": "Reason", "authorName": "Agent"]) { _, new in new }+        }+        arguments.merge(changes) { _, new in new }+        return ["itemId": "task9.original.\(index)", "operation": operation, "arguments": arguments]+    }++    func request(_ items: [[String: Any]]) throws -> MCPBatchTaskRequest {+        let data = try JSONSerialization.data(withJSONObject: ["mode": "execute", "items": items])+        guard case .valid(let request) = try MCPBatchTaskRequest.parse(MCPJSONDocument.parse(data)) else {+            throw MCPResultBoundaryError.invalidJSON+        }+        return request+    }++    func source(+        _ item: MCPBatchTaskRequest.Item, batchPolicy: MCPBatchWritePolicy? = .init()+    ) async throws -> MCPResultSource {+        let coordinator = try #require(coordinator)+        let result = await coordinator.execute(tool: item.command.tool,+            arguments: item.command.arguments, batchPolicy: batchPolicy)+        return try MCPResultAdapter.source(text: result.content[0].text, isError: result.isError,+            origin: .retainedJSON, evidence: .established)+    }++    func execution(_ item: MCPBatchTaskRequest.Item) async throws -> MCPBatchTaskCoordinator.Execution {+        var stopped = false+        let coordinator = try #require(coordinator)+        let policy = MCPBatchWritePolicy(onPendingEditsStop: { stopped = true })+        let result = await coordinator.execute(tool: item.command.tool, arguments: item.command.arguments,+                                               batchPolicy: policy)+        let source = try MCPResultAdapter.source(text: result.content[0].text, isError: result.isError,+            origin: .retainedJSON, evidence: .established)+        return .init(source: source, pendingEditsStop: stopped)+    }++    func durableTasks() throws -> [TransitTask] {+        let independent = try Self.owner(storeURL)+        independentOwners.append(independent)+        return try independent.context.fetch(FetchDescriptor<TransitTask>())+    }++    func durableComments() throws -> [Transit.Comment] {+        let independent = try Self.owner(storeURL)+        independentOwners.append(independent)+        return try independent.context.fetch(FetchDescriptor<Transit.Comment>())+    }+}+@MainActor private struct MCPBatchTaskCoordinatorMilestoneFetcher: ModelFetching {+    let context: ModelContext+    let fail: Bool++    func fetch<T: PersistentModel>(_ descriptor: FetchDescriptor<T>) throws -> [T] {+        if fail { throw MCPBatchTaskCoordinatorFixture.Fault.injected }+        return try context.fetch(descriptor)+    }+}+#endif
Transit/TransitTests/MCPBatchTaskCoordinatorSequenceFixtures.swift Added +63 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskCoordinatorSequenceFixtures.swift b/Transit/TransitTests/MCPBatchTaskCoordinatorSequenceFixtures.swiftnew file mode 100644index 00000000..59477cdb--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskCoordinatorSequenceFixtures.swift@@ -0,0 +1,63 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor enum MCPBatchTaskCoordinatorSequenceFixtures {+    static func request(count: Int = 4) throws -> MCPBatchTaskRequest {+        let values = (0..<count).map { MCPBatchTaskRequestFixtures.item($0) }+        let data = try JSONSerialization.data(withJSONObject: ["mode": "execute", "items": values])+        guard case .valid(let request) = try MCPBatchTaskRequest.parse(MCPJSONDocument.parse(data)) else {+            throw MCPResultBoundaryError.invalidJSON+        }+        return request+    }++    static func prepared(_ request: MCPBatchTaskRequest) throws -> MCPBatchTaskPreparedResponse {+        try MCPBatchTaskPreparedResponse.prepare(id: .string("task9.request"), items: request.items.map {+            MCPBatchRecoveryItem(index: $0.index, itemId: $0.itemId, operation: $0.operation,+                originalKey: .init(tool: $0.command.tool, idempotencyKey: $0.command.key),+                    targetTaskId: $0.targetTaskId)+        }, metadata: nil)+    }++    static func source(_ item: MCPBatchTaskRequest.Item, kind: String = "committed") throws -> MCPResultSource {+        if kind == "malformed" { return try MCPBatchTaskResultFixtures.source("{historic broken", isError: true) }+        if kind == "unknown" {+            return try MCPBatchTaskResultFixtures.source("{\"contractVersion\":2,\"outcome\":\"committed\"}")+        }+        if kind == "committed" || kind == "missingStatusComment" {+            var extra = #", "unknown":{"n":9007199254740993,"huge":1E9999,"null":null}"#+            if item.operation == "update_task_status", kind != "missingStatusComment" {+                extra += ",\"comment\":" + MCPBatchTaskResultFixtures.commentRecord+            }+            let text = MCPBatchTaskResultFixtures.committed(operation: item.operation, extra: extra)+                .replacingOccurrences(of: MCPBatchTaskResultFixtures.taskID.uuidString,+                                      with: item.targetTaskId.uuidString)+                .replacingOccurrences(of: MCPBatchTaskResultFixtures.key, with: item.command.key)+            return try MCPBatchTaskResultFixtures.source(text)+        }+        let uncertain = kind == "pending" || kind == "uncertain"+        let outcome = uncertain ? "uncertain" : kind+        let accepted = kind == "rejected" ? "false" : "true"+        let retry = uncertain ? "reconcile" : (kind == "rejected" ? "new_request_new_key" : "retry_same_request")+        return try MCPBatchTaskResultFixtures.source("""+        {"contractVersion":1,"tool":"\(item.operation)","idempotencyKey":"\(item.command.key)",\+        "outcome":"\(outcome)","accepted":\(accepted),\+        "error":{"code":"TEST_STOP","message":"Original stop"},"retryAction":"\(retry)",\+        "unknown":{"adjacent":9007199254740993,"nullable":null}}+        """, isError: true)+    }++    static func assertMappings(_ report: MCPBatchTaskCoordinator.Report, request: MCPBatchTaskRequest) {+        #expect(report.entries.count == request.items.count)+        for (entry, item) in zip(report.entries, request.items) {+            #expect(entry.index == item.index)+            #expect(entry.itemId.utf8.elementsEqual(item.itemId.utf8))+            #expect(entry.operation.utf8.elementsEqual(item.operation.utf8))+            #expect(entry.originalKey.utf8.elementsEqual(item.command.key.utf8))+            #expect(entry.taskID == item.targetTaskId)+        }+    }+}+#endif
Transit/TransitTests/MCPBatchTaskCoordinatorTests.swift Added +219 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskCoordinatorTests.swift b/Transit/TransitTests/MCPBatchTaskCoordinatorTests.swiftnew file mode 100644index 00000000..22ec65cf--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskCoordinatorTests.swift@@ -0,0 +1,219 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPBatchTaskCoordinatorTests {+    private typealias Fixture = MCPBatchTaskCoordinatorSequenceFixtures++    @Test(arguments: Array(0..<12), ["rejected", "in_progress", "uncertain", "unknown", "malformed", "pending"])+    func seededCallsAreExactCommittedPrefix(seed: Int, kind: String) async throws {+        let count = 1 + seed % 6+        let stopIndex = (seed * 7 + 3) % count+        let request = try Fixture.request(count: count)+        var calls: [Int] = []+        var originals: [Int: MCPResultSource] = [:]+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Fixture.prepared(request), executor: { item in+            calls.append(item.index)+            let source = try Fixture.source(item, kind: item.index == stopIndex ? kind : "committed")+            originals[item.index] = source+            return .init(source: source, pendingEditsStop: item.index == stopIndex && kind == "pending")+        })+        let report = try await batch.run(request)+        #expect(calls == Array(0...stopIndex))+        #expect(report.confirmedCommittedCount == stopIndex)+        #expect(report.summary == (["unknown", "malformed"].contains(kind) ? "evidence_unavailable" : "stopped"))+        let stop = try #require(report.stop)+        #expect(stop.nextUnstartedIndex == stopIndex + 1)+        #expect(stop.blocker == .init(index: stopIndex, itemId: request.items[stopIndex].itemId))+        #expect(stop.reason == (kind == "pending" ? .pendingEdits :+            (["unknown", "malformed"].contains(kind) ? .evidenceUnavailable : .itemResult)))+        #expect(report.isError == true)+        Fixture.assertMappings(report, request: request)+        for entry in report.entries {+            #expect(entry.state == (entry.index <= stopIndex ? .attempted : .notAttempted))+            #expect(entry.originalResult?.originalText == originals[entry.index]?.originalText)+            #expect(entry.originalResult?.originalIsError == originals[entry.index]?.originalIsError)+            #expect(entry.originalResult?.document?.originalUTF8 == originals[entry.index]?.document?.originalUTF8)+            if entry.index > stopIndex { #expect(entry.originalResult == nil) }+        }+    }++    @Test(arguments: Array(0...4))+    func observedCancellationBeforeBetweenAndAfterLast(afterCalls: Int) async throws {+        let request = try Fixture.request()+        var calls: [Int] = []+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Fixture.prepared(request), executor: { item in+            calls.append(item.index)+            return .init(source: try Fixture.source(item))+        }, observedCancellation: { calls.count >= afterCalls })+        let report = try await batch.run(request)+        #expect(calls == Array(0..<afterCalls))+        #expect(report.confirmedCommittedCount == afterCalls)+        #expect(report.observedCancellation)+        #expect(report.summary == (afterCalls == 4 ? "all_committed" : "interrupted"))+        if afterCalls == 4 {+            #expect(report.stop == nil && report.isError == nil)+        } else {+            let stop = try #require(report.stop)+            #expect(stop.reason == .cancelled && stop.nextUnstartedIndex == afterCalls && stop.blocker == nil)+            #expect(report.isError == true)+        }+        Fixture.assertMappings(report, request: request)+    }++    @Test(arguments: ["rejected", "in_progress", "uncertain", "unknown", "malformed", "pending"])+    func unsuccessfulEvidenceWinsCoincidentCancellation(kind: String) async throws {+        let request = try Fixture.request()+        var calls = 0+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Fixture.prepared(request), executor: { item in+            calls += 1+            return .init(source: try Fixture.source(item, kind: kind), pendingEditsStop: kind == "pending")+        }, observedCancellation: { calls > 0 })+        let report = try await batch.run(request)+        #expect(calls == 1 && report.observedCancellation)+        #expect(report.summary == (["unknown", "malformed"].contains(kind) ? "evidence_unavailable" : "stopped"))+        #expect(report.stop?.blocker?.index == 0)+        #expect(report.stop?.reason != .cancelled)+    }++    @Test(arguments: [1, 50])+    func allCommittedRetainsEveryOriginalAndNoError(count: Int) async throws {+        let request = try Fixture.request(count: count)+        var calls: [Int] = []+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Fixture.prepared(request), executor: { item in+            calls.append(item.index)+            return .init(source: try Fixture.source(item))+        })+        let report = try await batch.run(request)+        #expect(calls == Array(0..<count) && report.confirmedCommittedCount == count)+        #expect(report.summary == "all_committed" && report.stop == nil && report.isError == nil)+        #expect(report.entries.allSatisfy { $0.state == .attempted && $0.originalResult != nil })+        Fixture.assertMappings(report, request: request)+    }++    @Test+    func preparedMappingMismatchBlocksEveryDispatch() async throws {+        let request = try Fixture.request(count: 2)+        let other = try Fixture.request(count: 1)+        var calls = 0+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Fixture.prepared(other), executor: { item in+            calls += 1+            return .init(source: try Fixture.source(item))+        })+        do {+            _ = try await batch.run(request)+            Issue.record("Mismatched preencoded recovery mapping must block dispatch")+        } catch let error as MCPBatchTaskCoordinator.Error {+            #expect(error == .preparedRequestMismatch)+        } catch { Issue.record("Unexpected prerequisite error: \(error)") }+        #expect(calls == 0)+    }++    @Test+    func previewModeCannotExecuteEvenWithMatchingCapability() async throws {+        let document = try MCPJSONDocument.parse(JSONSerialization.data(withJSONObject:+            ["mode": "dry_run", "items": [MCPBatchTaskRequestFixtures.item()]]))+        guard case .valid(let request) = try MCPBatchTaskRequest.parse(document) else {+            throw MCPResultBoundaryError.invalidJSON+        }+        var calls = 0+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Fixture.prepared(request), executor: { item in+            calls += 1+            return .init(source: try Fixture.source(item))+        })+        do {+            _ = try await batch.run(request)+            Issue.record("Preview requests must not execute")+        } catch let error as MCPBatchTaskCoordinator.Error {+            #expect(error == .executeModeRequired)+        } catch { Issue.record("Unexpected mode error: \(error)") }+        #expect(calls == 0)+    }++    @Test(arguments: [0, 2])+    func executorFailureAfterInvocationNeverFabricatesNoEffect(index: Int) async throws {+        let request = try Fixture.request()+        var calls: [Int] = []+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Fixture.prepared(request), executor: { item in+            calls.append(item.index)+            if item.index == index { throw MCPBatchTaskCoordinatorFixture.Fault.injected }+            return .init(source: try Fixture.source(item))+        })+        let report = try await batch.run(request)+        #expect(calls == Array(0...index))+        #expect(report.summary == "evidence_unavailable" && report.confirmedCommittedCount == index)+        #expect(report.stop?.reason == .evidenceUnavailable)+        #expect(report.stop?.blocker?.index == index && report.stop?.nextUnstartedIndex == index + 1)+        #expect(report.entries[index].state == .attempted && report.entries[index].originalResult == nil)+        #expect(report.entries[(index + 1)...].allSatisfy { $0.state == .notAttempted })+        #expect(report.isError == true)+        Fixture.assertMappings(report, request: request)+    }++    @Test(arguments: ["committed", "unknown", "malformed"])+    func supplementalPendingHintNeverOverridesSourceEvidence(kind: String) async throws {+        let request = try Fixture.request(count: 1)+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Fixture.prepared(request), executor: { item in+            .init(source: try Fixture.source(item, kind: kind), pendingEditsStop: true)+        })+        let report = try await batch.run(request)+        #expect(report.summary == (kind == "committed" ? "all_committed" : "evidence_unavailable"))+        #expect(report.confirmedCommittedCount == (kind == "committed" ? 1 : 0))+        #expect(report.stop?.reason != .pendingEdits)+    }++    @Test(arguments: ["tool", "key", "uuid"])+    func sameCountDifferentPreparedIdentityBlocksEveryDispatch(field: String) async throws {+        let request = try Fixture.request(count: 1)+        var item = MCPBatchTaskRequestFixtures.item(operation: field == "tool" ? "add_comment" : "update_task")+        var arguments = try #require(item["arguments"] as? [String: Any])+        if field == "key" { arguments["idempotencyKey"] = "different.original.key" }+        if field == "uuid" { arguments["taskId"] = MCPBatchTaskRequestFixtures.taskID(99) }+        item["arguments"] = arguments+        let otherDocument = try MCPBatchTaskRequestFixtures.document(items: [item])+        guard case .valid(let other) = try MCPBatchTaskRequest.parse(otherDocument) else {+            throw MCPResultBoundaryError.invalidJSON+        }+        var calls = 0+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Fixture.prepared(other), executor: { item in+            calls += 1+            return .init(source: try Fixture.source(item))+        })+        do {+            _ = try await batch.run(request)+            Issue.record("Different recovery identity must block dispatch")+        } catch let error as MCPBatchTaskCoordinator.Error {+            #expect(error == .preparedRequestMismatch)+        } catch { Issue.record("Unexpected identity prerequisite error: \(error)") }+        #expect(calls == 0)+    }++    @Test(arguments: ["reason", "blank", "missingEvidence"])+    func mixedOperationSourceRequiresStatusReasonOnlyWhenNonblank(scenario: String) async throws {+        var status = MCPBatchTaskRequestFixtures.item(1, operation: "update_task_status")+        var arguments = try #require(status["arguments"] as? [String: Any])+        arguments["comment"] = scenario == "blank" ? " \n" : " Reason "+        arguments["authorName"] = "Agent"+        status["arguments"] = arguments+        let values = [MCPBatchTaskRequestFixtures.item(0), status,+                      MCPBatchTaskRequestFixtures.item(2, operation: "add_comment")]+        let document = try MCPBatchTaskRequestFixtures.document(items: values)+        guard case .valid(let request) = try MCPBatchTaskRequest.parse(document) else {+            throw MCPResultBoundaryError.invalidJSON+        }+        var calls: [String] = []+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Fixture.prepared(request), executor: { item in+            calls.append(item.operation)+            let kind = item.index == 1 && scenario != "reason" ? "missingStatusComment" : "committed"+            return .init(source: try Fixture.source(item, kind: kind))+        })+        let report = try await batch.run(request)+        #expect(calls == (scenario == "missingEvidence" ? ["update_task", "update_task_status"] :+            ["update_task", "update_task_status", "add_comment"]))+        #expect(report.summary == (scenario == "missingEvidence" ? "evidence_unavailable" : "all_committed"))+        #expect(report.confirmedCommittedCount == (scenario == "missingEvidence" ? 1 : 3))+    }+}+#endif
Transit/TransitTests/MCPBatchTaskEncodingTests.swift Added +184 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskEncodingTests.swift b/Transit/TransitTests/MCPBatchTaskEncodingTests.swiftnew file mode 100644index 00000000..d7b59ba6--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskEncodingTests.swift@@ -0,0 +1,184 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPBatchTaskEncodingTests {+    private typealias Fixture = MCPBatchTaskResultFixtures++    @Test(arguments: [nil, false, true] as [Bool?])+    func generatedAggregateKeepsNestedOriginalEvidenceSeparateFromOuterError(itemIsError: Bool?) throws {+        let original = Fixture.committed(version: "1.0", extra:+            #", "source":{"future":null},"presentation":{"retryAction":"untouched"},"n":1E+9999"#)+        let aggregate = try Fixture.aggregate(original: original, itemIsError: itemIsError)+        let source = try MCPResultAdapter.source(text: aggregate, isError: true,+                                                origin: .generatedJSON, evidence: .established)+        let context = Fixture.context(items: Fixture.recoveryItems())+        let presentation = try MCPResultAdapter.present(source, context: context)+        let metadata = try Fixture.metadata()+        let bytes = try MCPResultEncoder.encode(source: source, presentation: presentation,+                                                id: .string("rpc-correlated"), metadata: metadata)+        let result = try Fixture.result(bytes)+        #expect(Fixture.field("isError", in: result) == .boolean(true))+        #expect(Fixture.field("_meta", in: result) == metadata.document.value)+        let structured = Fixture.field("structuredContent", in: result)+        let payload = Fixture.field("payload", in: Fixture.field("source", in: structured))+        #expect(payload == source.document?.value)+        guard case .array(let items) = Fixture.field("items", in: payload) else {+            Issue.record("Expected the original batch-owned items"); return+        }+        let nested = Fixture.field("originalResult", in: items.first)+        #expect(Fixture.field("text", in: nested) == .string(original))+        #expect(Fixture.field("payload", in: nested) == (try MCPJSONDocument.parse(original).value))+        #expect(Fixture.field("isError", in: nested) == itemIsError.map(MCPJSONValue.boolean))+        let wire = try #require(String(data: bytes, encoding: .utf8))+        #expect(wire.contains(#""id":"rpc-correlated""#))+        #expect(wire.contains(#""n":1E+9999"#))+        #expect(wire.contains(#""contractVersion":1.0"#))+    }++    @Test func compactFallbackStripsGiantItemRecordsDiagnosticsAndEntityLinks() throws {+        let giant = "unbounded-item-" + String(repeating: "x", count: 200_000)+        let items = Fixture.recoveryItems(itemID: giant)+        let context = Fixture.context(items: items, diagnostic: giant,+            links: [.init(entityType: .task, sourcePath: "/items/0/originalResult/payload/record")])+        // Intentionally absent batch-owned builder is the encoding RED seam.+        let source = try MCPBatchTaskFallback.source(items: items)+        #expect(source.kind == .json && source.evidence == .unestablished && source.originalIsError == true)+        #expect(Fixture.field("summary", in: source.document?.value) == .string("serialization_failed"))+        #expect(Fixture.field("outcome", in: source.document?.value) == nil)+        #expect(Fixture.field("accepted", in: source.document?.value) == nil)+        let bytes = try MCPResultEncoder.prepareMutationFallback(id: .integer(7), source: source,+                                                                 context: context, metadata: nil)+        let result = try Fixture.result(bytes)+        #expect(Fixture.field("resultType", in: result) == .string("complete"))+        let structured = Fixture.field("structuredContent", in: result)+        let presentation = Fixture.field("presentation", in: structured)+        #expect(Fixture.field("evidence", in: presentation) == .string("unestablished"))+        #expect(Fixture.field("links", in: presentation) == .array([]))+        let recovery = Fixture.field("recovery", in: presentation)+        #expect(Fixture.field("direction", in: recovery) == .string("reconcile_original_write"))+        guard case .array(let mapped) = Fixture.field("items", in: recovery) else {+            Issue.record("Expected original item recovery mapping"); return+        }+        #expect(mapped.count == 1)+        #expect(Fixture.field("index", in: mapped.first) == (try MCPJSONDocument.parse("0").value))+        #expect(Fixture.field("itemId", in: mapped.first) == nil)+        #expect(Fixture.field("operation", in: mapped.first) == .string("update_task"))+        #expect(Fixture.field("tool", in: mapped.first) == .string("update_task"))+        #expect(Fixture.field("idempotencyKey", in: mapped.first) == .string(Fixture.key))+        #expect(Fixture.field("targetTaskId", in: mapped.first) == .string(Fixture.taskID.uuidString))+        let wire = try #require(String(data: bytes, encoding: .utf8))+        #expect(!wire.contains(giant) && !wire.contains("itemId") && !wire.contains("Saved task"))+        #expect(!wire.contains("new_request_new_key") && !wire.contains("no_effect"))+        #expect(bytes.count < giant.utf8.count)+    }++    @Test func preparationFailureDoesNotDispatchOrTryNormalEncoding() async throws {+        let counts = MCPBatchTaskEncodingCounts()+        let items = Fixture.recoveryItems()+        let source = try MCPBatchTaskFallback.source(items: items)+        do {+            _ = try await MCPResultProviderSelection.mutation(id: .integer(1), context: Fixture.context(items: items),+                metadata: nil, fallbackSource: source, prepareFallback: { id, fallback, context, metadata in+                    counts.record("prepare")+                    return try MCPResultEncoder.prepareMutationFallback(id: id, source: fallback,+                        context: context, metadata: metadata,+                        checkpoint: { throw MCPResultBoundaryError.resourceLimit })+                }, encodeOutcome: { _, _, _ in+                    counts.record("encode"); throw MCPResultBoundaryError.invalidJSON+                }, dispatch: {+                    counts.record("dispatch"); throw MCPResultBoundaryError.unsupportedEvidence+                })+            Issue.record("Preparation failure must propagate before dispatch")+        } catch let error as MCPResultBoundaryError { #expect(error == .resourceLimit) }+        let final = counts.snapshot()+        #expect(final.prepare == 1 && final.dispatch == 0 && final.encode == 0)+    }++    @Test(arguments: ["payload", "presentation", "envelope"])+    func postEffectFailureSelectsCompletePreparedBytesWithoutSecondEncoding(stage: String) async throws {+        let counts = MCPBatchTaskEncodingCounts()+        let items = Fixture.recoveryItems()+        let context = Fixture.context(items: items)+        let fallback = try MCPBatchTaskFallback.source(items: items)+        let normal = try MCPResultAdapter.source(text: Fixture.aggregate(original: Fixture.committed()),+                                                isError: nil, origin: .generatedJSON, evidence: .established)+        let metadata = try Fixture.metadata()+        let selected = try await MCPResultProviderSelection.mutation(id: .string("rpc-after-effect"), context: context,+            metadata: metadata, fallbackSource: fallback, prepareFallback: { id, source, fixed, meta in+                #expect(counts.snapshot().dispatch == 0)+                let bytes = try MCPResultEncoder.prepareMutationFallback(id: id, source: source,+                                                                        context: fixed, metadata: meta)+                counts.record("prepare", prepared: bytes)+                return bytes+            }, encodeOutcome: { outcome, id, meta in+                counts.record("encode")+                if stage == "presentation" {+                    _ = try MCPResultAdapter.present(outcome.source, context: outcome.context,+                                                     checkpoint: { throw MCPResultBoundaryError.resourceLimit })+                }+                let presentation = try MCPResultAdapter.present(outcome.source, context: outcome.context)+                return try MCPResultEncoder.encode(source: outcome.source, presentation: presentation,+                    id: id, metadata: meta, checkpoint: { throw MCPResultBoundaryError.resourceLimit })+            }, dispatch: {+                counts.record("dispatch")+                if stage == "payload" {+                    _ = try MCPResultAdapter.source(text: "{malformed", isError: nil,+                                                     origin: .generatedJSON, evidence: .established)+                }+                return .init(source: normal, context: context)+            })+        let bytes = try Fixture.reconciliation(selected)+        let final = counts.snapshot()+        #expect(final.prepare == 1 && final.dispatch == 1)+        #expect(final.encode == (stage == "payload" ? 0 : 1))+        #expect(bytes == final.prepared)+        #expect(final.events == (stage == "payload" ? ["prepare", "dispatch"] : ["prepare", "dispatch", "encode"]))+        let result = try Fixture.result(bytes)+        #expect(Fixture.field("_meta", in: result) == metadata.document.value)+        #expect(Fixture.field("id", in: try MCPJSONDocument.parse(bytes).value) == .string("rpc-after-effect"))+    }++    @Test func readableDepth32ReceiptOverflowsGeneratedAggregateAfterSyntheticCommit() async throws {+        let original = Fixture.committed(extra: ",\"unknownDepth\":\(Fixture.nestedArrays(31))")+        let retained = try Fixture.source(original)+        #expect(retained.kind == .json && retained.document != nil)+        let counts = MCPBatchTaskEncodingCounts()+        let items = Fixture.recoveryItems()+        let context = Fixture.context(items: items)+        let fallback = try MCPBatchTaskFallback.source(items: items)+        let selected = try await MCPResultProviderSelection.mutation(id: .integer(32), context: context,+            metadata: nil, fallbackSource: fallback, prepareFallback: { id, source, fixed, meta in+                let bytes = try MCPResultEncoder.prepareMutationFallback(id: id, source: source,+                                                                        context: fixed, metadata: meta)+                counts.record("prepare", prepared: bytes)+                return bytes+            }, encodeOutcome: { _, _, _ in+                counts.record("encode"); throw MCPResultBoundaryError.unsupportedEvidence+            }, dispatch: {+                counts.record("dispatch") // Represents one established synthetic effect only.+                let aggregate = try Fixture.aggregate(original: retained.originalText)+                do {+                    let source = try MCPResultAdapter.source(text: aggregate, isError: nil,+                                                            origin: .generatedJSON, evidence: .established)+                    return .init(source: source, context: context)+                } catch let error as MCPResultBoundaryError {+                    #expect(error == .resourceLimit)+                    throw error+                }+            })+        #expect(try Fixture.reconciliation(selected) == counts.snapshot().prepared)+        #expect(counts.snapshot().prepare == 1 && counts.snapshot().dispatch == 1 && counts.snapshot().encode == 0)+        #expect(retained.originalText == original && retained.document?.originalUTF8 == Data(original.utf8))+    }++    @Test func depth33RetainedTextAndOptionalFlagSurviveAsUnreadable() throws {+        let text = Fixture.nestedArrays(33)+        let retained = try Fixture.source(text, isError: false)+        #expect(retained.kind == .unreadable && retained.evidence == .unestablished && retained.document == nil)+        #expect(retained.originalText == text && retained.originalIsError == false)+    }+}+#endif
Transit/TransitTests/MCPBatchTaskEvidenceBoundaryTests.swift Added +111 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskEvidenceBoundaryTests.swift b/Transit/TransitTests/MCPBatchTaskEvidenceBoundaryTests.swiftnew file mode 100644index 00000000..e6fc5230--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskEvidenceBoundaryTests.swift@@ -0,0 +1,111 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPBatchTaskEvidenceBoundaryTests {+    private typealias Fixture = MCPBatchTaskResultFixtures++    @Test(arguments: ["1.0000000000000000000000001", "0.9999999999999999999999999", "-1",+                      "1e999999999999999999999", "100e-2", "0.0100e2", "10.0e-1", "1E+0000"])+    func exactDecimalVersionDoesNotRoundAdjacentValues(version: String) throws {+        let source = try Fixture.source(Fixture.committed(version: version))+        let assessment = MCPBatchTaskEvidence.assess(source: source, operation: "update_task",+            originalKey: Fixture.key, taskID: Fixture.taskID, requiresStatusComment: false)+        let equivalent = ["100e-2", "0.0100e2", "10.0e-1", "1E+0000"].contains(version)+        #expect(assessment.canAdvance == equivalent)+        #expect(assessment.source.originalText == source.originalText)+        #expect(assessment.source.document?.originalUTF8 == source.document?.originalUTF8)+    }++    @Test(arguments: ["2026-02-30T00:00:00.000Z", "2026-01-01T24:00:00.000Z",+                      "2026-01-01T00:00:00.000+00:00", "2026-01-01T00:00:00.0000Z"])+    func noncanonicalOrNormalizedInvalidDateCannotEstablishCommit(timestamp: String) throws {+        let original = Fixture.committed()+        let text = original.replacingOccurrences(of: #""completedAt":"2026-01-01T00:00:00.000Z""#,+                                                with: "\"completedAt\":\"\(timestamp)\"")+        #expect(text != original)+        let source = try Fixture.source(text)+        let assessment = MCPBatchTaskEvidence.assess(source: source, operation: "update_task",+            originalKey: Fixture.key, taskID: Fixture.taskID, requiresStatusComment: false)+        #expect(!assessment.canAdvance)+        #expect(assessment.source.originalText == text)+    }++    @Test(arguments: ["unicode", "case"])+    func opaqueKeyIdentityUsesExactScalarsRatherThanCanonicalEquality(kind: String) throws {+        let savedKey = kind == "unicode" ? "saved.\u{00E9}" : "batch.original"+        let requestedKey = kind == "unicode" ? "saved.e\u{0301}" : "Batch.Original"+        let text = Fixture.committed().replacingOccurrences(of: Fixture.key, with: savedKey)+        let source = try Fixture.source(text)+        let assessment = MCPBatchTaskEvidence.assess(source: source, operation: "update_task",+            originalKey: requestedKey, taskID: Fixture.taskID, requiresStatusComment: false)+        #expect(!assessment.canAdvance)+        #expect(assessment.source.originalText == text)+    }++    @Test(arguments: ["error", "retry", "both", "direction"])+    func committedOptionalNullsPreserveEvidenceWithoutInventingFailure(kind: String) throws {+        let extra: String+        switch kind {+        case "error": extra = ",\"error\":null"+        case "retry": extra = ",\"retryAction\":null"+        case "both": extra = ",\"error\":null,\"retryAction\":null"+        default: extra = ",\"retryAction\":\"reconcile\""+        }+        let text = Fixture.committed(extra: extra)+        let source = try Fixture.source(text)+        let assessment = MCPBatchTaskEvidence.assess(source: source, operation: "update_task",+            originalKey: Fixture.key, taskID: Fixture.taskID, requiresStatusComment: false)+        #expect(assessment.canAdvance == (kind != "direction"))+        #expect(assessment.source.originalText == text)+        #expect(assessment.source.document?.value == source.document?.value)+        if kind == "error" || kind == "both" {+            #expect(Fixture.field("error", in: assessment.source.document?.value) == .null)+        }+        if kind == "retry" || kind == "both" {+            #expect(Fixture.field("retryAction", in: assessment.source.document?.value) == .null)+        }+    }++    @Test(arguments: ["rejected", "in_progress", "uncertain", "missingError", "wrongError", "missingCode",+                      "wrongMessage", "missingRetry", "wrongRetry", "acceptedConflict", "unknownOutcome"])+    func supportedFailuresRemainDistinctFromUnavailableEvidence(kind: String) throws {+        let outcome = ["rejected", "in_progress", "uncertain"].contains(kind) ? kind : "uncertain"+        let code = outcome == "in_progress" ? "OPERATION_IN_PROGRESS" : "OUTCOME_UNCERTAIN"+        let retry = outcome == "uncertain" ? "reconcile" : "retry_same_request"+        let error = "\"error\":{\"code\":\"\(code)\",\"message\":\"saved\"}"+        let retryField = "\"retryAction\":\"\(retry)\""+        var text = """+        {"contractVersion":1,"tool":"update_task","idempotencyKey":"\(Fixture.key)",+        "outcome":"\(outcome)","accepted":true,\(error),\(retryField),"unknown":null}+        """+        let baseline = text+        switch kind {+        case "missingError": text = text.replacingOccurrences(of: error + ",", with: "")+        case "wrongError": text = text.replacingOccurrences(of: error, with: "\"error\":null")+        case "missingCode": text = text.replacingOccurrences(of: "\"code\":\"\(code)\",", with: "")+        case "wrongMessage":+            text = text.replacingOccurrences(of: "\"message\":\"saved\"", with: "\"message\":false")+        case "missingRetry": text = text.replacingOccurrences(of: retryField + ",", with: "")+        case "wrongRetry":+            text = text.replacingOccurrences(of: retryField, with: "\"retryAction\":\"new_request_new_key\"")+        case "acceptedConflict": text = text.replacingOccurrences(of: "\"accepted\":true", with: "\"accepted\":false")+        case "unknownOutcome":+            text = text.replacingOccurrences(of: "\"outcome\":\"uncertain\"", with: "\"outcome\":\"unknown\"")+        default: break+        }+        let supported = ["rejected", "in_progress", "uncertain"].contains(kind)+        #expect(supported || text != baseline)+        let source = try Fixture.source(text, isError: true)+        let assessment = MCPBatchTaskEvidence.assess(source: source, operation: "update_task",+            originalKey: Fixture.key, taskID: Fixture.taskID, requiresStatusComment: false)+        #expect(assessment.kind == (supported ? .itemResult : .unavailable))+        #expect(!assessment.canAdvance && assessment.source.originalText == text)+        #expect(assessment.source.originalIsError == true)+        #expect(assessment.source.document?.value == source.document?.value)+    }++}+#endif
Transit/TransitTests/MCPBatchTaskEvidenceTests.swift Added +126 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskEvidenceTests.swift b/Transit/TransitTests/MCPBatchTaskEvidenceTests.swiftnew file mode 100644index 00000000..9d12abd5--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskEvidenceTests.swift@@ -0,0 +1,126 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPBatchTaskEvidenceTests {+    private typealias Fixture = MCPBatchTaskResultFixtures++    // Intentionally absent batch-local classifier is Task 3's RED boundary.+    @Test(arguments: ["1", "1.0", "1e0"], [nil, false] as [Bool?])+    func equivalentNumericVersionAndOriginalOptionalFlagCanAdvance(version: String, isError: Bool?) throws {+        let text = Fixture.committed(version: version, extra:+            #", "unknown":{"n":1E+9999,"adjacent":9007199254740993,"explicitNull":null}"#)+        let source = try Fixture.source(text, isError: isError)+        let result = MCPBatchTaskEvidence.assess(source: source, operation: "update_task",+            originalKey: Fixture.key, taskID: Fixture.taskID, requiresStatusComment: false)+        #expect(result.canAdvance)+        #expect(result.source.originalText == text && result.source.originalIsError == isError)+        #expect(result.source.document?.originalUTF8 == Data(text.utf8))+        #expect(result.source.document?.value == source.document?.value)+        // January expiry is historical: current classification must not deny+        // the established saved commit or remint a revision/expiry.+    }++    @Test(arguments: ["2", "true", #""1""#, "null"])+    func unsupportedOrWrongVersionStopsWithoutRewriting(version: String) throws {+        let source = try Fixture.source(Fixture.committed(version: version))+        let result = MCPBatchTaskEvidence.assess(source: source, operation: "update_task",+            originalKey: Fixture.key, taskID: Fixture.taskID, requiresStatusComment: false)+        #expect(!result.canAdvance)+        #expect(result.source.originalText == source.originalText)+        #expect(result.source.document?.value == source.document?.value)+    }++    @Test(arguments: ["acceptedFalse", "acceptedNumber", "acceptedString", "acceptedNull", "acceptedMissing",+                      "versionMissing", "entityMismatch", "recordMismatch", "recordMissing", "revision",+                      "completedAt", "expiry", "wrongTool", "wrongKey", "error"])+    func missingMalformedOrContradictoryCommitEvidenceStops(caseName: String) throws {+        let replacements: [String: (String, String)] = [+            "acceptedFalse": (#""accepted":true"#, #""accepted":false"#),+            "acceptedNumber": (#""accepted":true"#, #""accepted":1"#),+            "acceptedString": (#""accepted":true"#, #""accepted":"true""#),+            "acceptedNull": (#""accepted":true"#, #""accepted":null"#),+            "acceptedMissing": (#","accepted":true"#, ""),+            "versionMissing": (#""contractVersion":1,"#, ""),+            "entityMismatch": ("\"entityId\":\"\(Fixture.taskID.uuidString)\"", "\"entityId\":\"bad\""),+            "recordMismatch": ("\"taskId\":\"\(Fixture.taskID.uuidString)\"",+                               "\"taskId\":\"\(Fixture.commentID.uuidString)\""),+            "recordMissing": (",\"record\":\(Fixture.taskRecord)", ""),+            "revision": (Fixture.revision, "r1:bad"),+            "completedAt": (#""completedAt":"2026-01-01T00:00:00.000Z""#,+                            #""completedAt":"2026-01-01T00:00:00Z""#),+            "expiry": ("2026-01-08T00:00:00.000Z", "2025-12-31T00:00:00.000Z"),+            "wrongTool": (#""tool":"update_task""#, #""tool":"add_comment""#),+            "wrongKey": ("\"idempotencyKey\":\"\(Fixture.key)\"", #""idempotencyKey":"other""#),+            "error": (#""outcome":"committed""#,+                      #""outcome":"committed","error":{"code":"INTERNAL_ERROR","message":"contradiction"}"#)+        ]+        let replacement = try #require(replacements[caseName])+        let original = Fixture.committed()+        let text = original.replacingOccurrences(of: replacement.0, with: replacement.1)+        #expect(text != original)+        let source = try Fixture.source(text)+        let result = MCPBatchTaskEvidence.assess(source: source, operation: "update_task",+            originalKey: Fixture.key, taskID: Fixture.taskID, requiresStatusComment: false)+        #expect(!result.canAdvance)+        #expect(result.source.originalText == text)+    }++    @Test(arguments: ["update_task", "update_task_status", "add_comment"])+    func operationSpecificSavedIdentityCanAdvance(operation: String) throws {+        let source = try Fixture.source(Fixture.committed(operation: operation))+        let result = MCPBatchTaskEvidence.assess(source: source, operation: operation,+            originalKey: Fixture.key, taskID: Fixture.taskID, requiresStatusComment: false)+        #expect(result.canAdvance)+    }++    @Test(arguments: ["valid", "missing", "null", "wrongTask", "badRevision", "badID"])+    func requestedStatusReasonRequiresItsOwnSavedComment(kind: String) throws {+        var comment = Fixture.commentRecord+        if kind == "wrongTask" {+            comment = comment.replacingOccurrences(of: Fixture.taskID.uuidString, with: Fixture.commentID.uuidString)+        }+        if kind == "badRevision" { comment = comment.replacingOccurrences(of: Fixture.revision, with: "bad") }+        if kind == "badID" { comment = comment.replacingOccurrences(of: Fixture.commentID.uuidString, with: "bad") }+        let extra = kind == "missing" ? "" : ",\"comment\":\(kind == "null" ? "null" : comment)"+        let source = try Fixture.source(Fixture.committed(operation: "update_task_status", extra: extra))+        let result = MCPBatchTaskEvidence.assess(source: source, operation: "update_task_status",+            originalKey: Fixture.key, taskID: Fixture.taskID, requiresStatusComment: true)+        #expect(result.canAdvance == (kind == "valid"))+        #expect(result.source.document?.value == source.document?.value)+    }++    @Test(arguments: ["rejected", "in_progress", "uncertain", "unknown"])+    func unsuccessfulOriginalOutcomeAndRetryDirectionRemainSourceOwned(outcome: String) throws {+        let text = """+        {"contractVersion":1,"outcome":"\(outcome)","accepted":null,"retryAction":"retry_same_request",\+        "error":{"code":"INTERNAL_ERROR","message":"saved"},"unknown":null}+        """+        let source = try Fixture.source(text, isError: true)+        let result = MCPBatchTaskEvidence.assess(source: source, operation: "update_task",+            originalKey: Fixture.key, taskID: Fixture.taskID, requiresStatusComment: false)+        #expect(!result.canAdvance)+        #expect(result.source.originalText == text && result.source.originalIsError == true)+        #expect(Fixture.field("retryAction", in: result.source.document?.value) == .string("retry_same_request"))+        #expect(Fixture.field("unknown", in: result.source.document?.value) == .null)+        #expect(Fixture.field("missing", in: result.source.document?.value) == nil)+    }++    @Test(arguments: ["malformed", "depth33", "unestablished", "errorFlag"])+    func unreadableOrUnestablishedEvidenceCannotAdvance(kind: String) throws {+        let text = kind == "malformed" ? "{broken" : kind == "depth33" ? Fixture.nestedArrays(33) : Fixture.committed()+        let source = try Fixture.source(text, isError: kind == "errorFlag" ? true : nil,+                                        evidence: kind == "unestablished" ? .unestablished : .established)+        let result = MCPBatchTaskEvidence.assess(source: source, operation: "update_task",+            originalKey: Fixture.key, taskID: Fixture.taskID, requiresStatusComment: false)+        #expect(!result.canAdvance)+        #expect(result.source.originalText == text && result.source.originalIsError == source.originalIsError)+        if kind == "malformed" || kind == "depth33" {+            #expect(result.source.kind == .unreadable && result.source.evidence == .unestablished)+            #expect(result.source.document == nil)+        }+    }+}+#endif
Transit/TransitTests/MCPBatchTaskExecutionAdapterTests.swift Added +82 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskExecutionAdapterTests.swift b/Transit/TransitTests/MCPBatchTaskExecutionAdapterTests.swiftnew file mode 100644index 00000000..0d0f7a05--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskExecutionAdapterTests.swift@@ -0,0 +1,82 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPBatchTaskExecutionAdapterTests {+    private typealias Fixture = MCPBatchTaskCoordinatorFixture+    private typealias Sequence = MCPBatchTaskCoordinatorSequenceFixtures++    @Test+    func actualAdapterReplaysOriginalEvidenceWhileDirtyWithoutPendingStop() async throws {+        let fixture = try Fixture()+        let request = try fixture.request([fixture.item(0)])+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Sequence.prepared(request),+            writeCoordinator: try #require(fixture.coordinator))+        let first = try await batch.run(request)+        #expect(first.summary == "all_committed")+        let original = try #require(first.entries[0].originalResult)+        fixture.tasks[1].name = "Pending UI name"+        let saves = fixture.saveStages+        let replay = try await batch.run(request)+        #expect(replay.summary == "all_committed" && replay.stop == nil)+        #expect(replay.entries[0].originalResult?.originalText.utf8.elementsEqual(original.originalText.utf8) == true)+        #expect(replay.entries[0].originalResult?.document?.originalUTF8 == original.document?.originalUTF8)+        #expect(replay.entries[0].originalResult?.originalIsError == original.originalIsError)+        #expect(fixture.tasks[1].name == "Pending UI name" && fixture.owner.context.hasChanges)+        #expect(fixture.saveStages == saves && fixture.recoveryCalls == 0)+        #expect(try fixture.durableTasks().first { $0.id == fixture.tasks[1].id }?.name == "Task 1")+    }++    @Test+    func actualAdapterFreshDirtyStopBindsPerInvocationFact() async throws {+        let fixture = try Fixture()+        let request = try fixture.request([fixture.item(0)])+        fixture.tasks[1].name = "Pending UI name"+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Sequence.prepared(request),+            writeCoordinator: try #require(fixture.coordinator))+        let report = try await batch.run(request)+        #expect(report.summary == "stopped" && report.stop?.reason == .pendingEdits)+        #expect(report.confirmedCommittedCount == 0 && report.entries[0].state == .attempted)+        let source = try #require(report.entries[0].originalResult)+        #expect(source.originalIsError == true && source.originalText.contains("reconcile"))+        #expect(fixture.owner.context.hasChanges && fixture.tasks[1].name == "Pending UI name")+        #expect(fixture.saveStages.isEmpty && fixture.recoveryCalls == 0)+        #expect(try fixture.durableTasks().first { $0.id == fixture.tasks[0].id }?.taskDescription == nil)+    }++    @Test+    func localHandlerSelectsPreviewWithoutCapabilityAndRequiresItForExecute() async throws {+        let fixture = try Fixture()+        let item = try fixture.item(0)+        func value(mode: String) throws -> MCPJSONValue {+            try MCPJSONDocument.parse(JSONSerialization.data(withJSONObject:+                ["mode": mode, "items": [item]])).value+        }+        let preview = try await MCPBatchTaskHandler.handle(arguments: value(mode: "dry_run"),+            container: fixture.owner.container, persistence: PersistenceAvailability())+        guard case .preview = preview else { Issue.record("Dry run requires no prepared capability"); return }+        #expect(fixture.saveStages.isEmpty && !fixture.owner.context.hasChanges)+        do {+            _ = try await MCPBatchTaskHandler.handle(arguments: value(mode: "execute"),+                container: fixture.owner.container, persistence: PersistenceAvailability())+            Issue.record("Execute without prepared capability must fail before effects")+        } catch let error as MCPBatchTaskHandler.Error {+            guard case .executionUnavailable = error else { Issue.record("Unexpected availability error"); return }+        }+        #expect(fixture.saveStages.isEmpty && !fixture.owner.context.hasChanges)+        let request = try fixture.request([item])+        let batch = MCPBatchTaskCoordinator(preparedResponse: try Sequence.prepared(request),+            writeCoordinator: try #require(fixture.coordinator))+        let execution = try await MCPBatchTaskHandler.handle(arguments: value(mode: "execute"),+            container: fixture.owner.container, persistence: PersistenceAvailability(), coordinator: batch)+        guard case .execution(_, let report) = execution else { Issue.record("Expected execute mode"); return }+        #expect(report.summary == "all_committed" && report.confirmedCommittedCount == 1)+        #expect(report.entries[0].originalKey.utf8.elementsEqual(request.items[0].command.key.utf8))+        #expect(try fixture.durableTasks().first { $0.id == fixture.tasks[0].id }?.taskDescription ==+            "Canonical description")+    }+}+#endif
Transit/TransitTests/MCPBatchTaskModernFixture.swift Added +50 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskModernFixture.swift b/Transit/TransitTests/MCPBatchTaskModernFixture.swiftnew file mode 100644index 00000000..f69ad502--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskModernFixture.swift@@ -0,0 +1,50 @@+#if os(macOS)+import Foundation+import HTTPTypes+import Testing+@testable import Transit++/// Owns retained persistent stores for the entire fixture lifetime. No listener,+/// client activation, global defaults writes or production storage is involved.+@MainActor final class MCPBatchTaskModernFixture {+    let domain: MCPBatchTaskCoordinatorFixture+    let handler: MCPToolHandler++    init(fallback: Bool = false, missingCoordinator: Bool = false,+         encoder: MCPResultProviderSelection.EncodeOutcome? = nil) throws {+        let domain = try MCPBatchTaskCoordinatorFixture()+        self.domain = domain+        let allocator = DisplayIDAllocator(store: InMemoryCounterStore(), isCloudSyncActive: false)+        let maintenance = DisplayIDMaintenanceService(modelContext: domain.owner.context,+            taskAllocator: allocator, milestoneAllocator: allocator, commentService: domain.services.comments)+        handler = MCPToolHandler(taskService: domain.services.tasks, projectService: domain.services.projects,+            commentService: domain.services.comments, milestoneService: domain.services.milestones,+            maintenanceService: maintenance, settings: MCPSettings(),+            persistence: PersistenceAvailability(isFallbackStorageActive: fallback),+            writeCoordinator: missingCoordinator ? nil : domain.coordinator,+            batchContainer: domain.owner.container, batchResultEncoder: encoder)+    }++    func call(mode: String, items: [[String: Any]], id: Any = "batch.real.rpc") async throws -> MCPHTTPTestResponse {+        let params: [String: Any] = ["name": "mutate_tasks", "arguments": ["mode": mode, "items": items]]+        return try await raw(MCPModernResultFixture.body(method: "tools/call", id: id, parameters: params))+    }++    func raw(_ body: String) async throws -> MCPHTTPTestResponse {+        try await MCPModernResultFixture.transport(handler: handler, contentType: "application/json",+            accept: "application/json, text/event-stream", protocolVersion: "2026-07-28",+            orderedHeaders: [HTTPField(name: HTTPField.Name("Mcp-Method")!, value: "tools/call"),+                HTTPField(name: HTTPField.Name("Mcp-Name")!, value: "mutate_tasks")],+            body: body, loggerLabel: "t2384-real-batch")+    }++    static func payload(_ response: MCPHTTPTestResponse) throws -> MCPJSONValue {+        #expect(response.status == .ok)+        let document = try MCPJSONDocument.parse(response.body)+        let result = try #require(MCPBatchTaskResultFixtures.field("result", in: document.value))+        let structured = try #require(MCPBatchTaskResultFixtures.field("structuredContent", in: result))+        let source = try #require(MCPBatchTaskResultFixtures.field("source", in: structured))+        return try #require(MCPBatchTaskResultFixtures.field("payload", in: source))+    }+}+#endif
Transit/TransitTests/MCPBatchTaskModernTests.swift Added +142 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskModernTests.swift b/Transit/TransitTests/MCPBatchTaskModernTests.swiftnew file mode 100644index 00000000..8d707acf--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskModernTests.swift@@ -0,0 +1,142 @@+#if os(macOS)+import Foundation+import SwiftData+import HTTPTypes+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPBatchTaskModernTests {+    private typealias Fixture = MCPBatchTaskModernFixture+    private typealias JSON = MCPBatchTaskResultFixtures++    @Test func registeredToolPublishesRichSchemaAndBatchClassification() throws {+        let definitions = try MCPToolDefinitions.modernTools(includingMaintenance: false)+        let descriptor = try #require(definitions.first { $0.name == "mutate_tasks" })+        let properties = JSON.field("properties", in: descriptor.inputSchema.value)+        let items = JSON.field("items", in: properties)+        #expect(JSON.field("minItems", in: items) != nil && JSON.field("maxItems", in: items) != nil)+        #expect(JSON.field("oneOf", in: JSON.field("items", in: items)) != nil)+        #expect(JSON.field("batchPayload", in:+            JSON.field("$defs", in: descriptor.resultSchema.outputSchema.value)) != nil)+        let availability = MCPModernProviderBinding.availability(maintenanceEnabled: false)+        let tool = try #require(availability.tools.first { $0.name == "mutate_tasks" })+        guard case .applicationBatch = tool.execution else {+            Issue.record("Expected application batch execution"); return+        }+        #expect(!MCPWriteCommand.protectedTools.contains("mutate_tasks"))+        #expect(!MCPWriteCommand.revisionTools.contains("mutate_tasks"))+        #expect(MCPBoundedReadDispatcher.classify(+            MCPTestHelpers.toolCallRequest(tool: "mutate_tasks", arguments: [:])) == nil)+        #expect(definitions.map(\.name) == MCPToolDefinitions.coreTools.map(\.name))+    }++    @Test func realPreviewThenCanonicalConsolidationAndReplay() async throws {+        let fixture = try Fixture()+        let domain = fixture.domain+        let items = try [domain.item(0, changes: ["description": " Combined rationale "]),+            domain.item(1, operation: "update_task_status", changes: ["comment": "Duplicate one"]),+            domain.item(2, operation: "update_task_status", changes: ["comment": "Duplicate two"])]+        let preview = try Fixture.payload(await fixture.call(mode: "dry_run", items: items))+        #expect(JSON.field("summary", in: preview) == .string("preview_valid"))+        #expect(domain.saveStages.isEmpty && domain.owner.context.hasChanges == false)+        let response = try await fixture.call(mode: "execute", items: items)+        let execution = try Fixture.payload(response)+        #expect(JSON.field("summary", in: execution) == .string("all_committed"))+        #expect(try domain.durableTasks().first { $0.id == domain.tasks[0].id }?.taskDescription ==+            "Combined rationale")+        #expect(try domain.durableComments().map(\.content).sorted() == ["Duplicate one", "Duplicate two"])+        let replay = try await fixture.call(mode: "execute", items: items, id: "replay.rpc")+        #expect(try Fixture.payload(replay) == execution)+        #expect(try domain.durableComments().count == 2)+        let request = try domain.request(items)+        guard case .array(let mapped) = JSON.field("items", in: execution) else {+            Issue.record("Expected original item evidence"); return+        }+        for item in request.items {+            let historic = try await domain.source(item, batchPolicy: nil)+            let original = JSON.field("originalResult", in: mapped[item.index])+            let rawText = try #require(MCPBatchTaskInputValue.string(JSON.field("text", in: original)))+            #expect(rawText.utf8.elementsEqual(historic.originalText.utf8))+            #expect(JSON.field("isError", in: original) == historic.originalIsError.map(MCPJSONValue.boolean))+            let bytes = try #require(historic.document?.originalUTF8)+            #expect(response.body.range(of: bytes) != nil)+        }+        let result = JSON.field("result", in: try MCPJSONDocument.parse(response.body).value)+        let links = JSON.field("links", in: JSON.field("presentation", in: JSON.field("structuredContent", in: result)))+        guard case .array(let values) = links else { Issue.record("Expected task navigation links"); return }+        #expect(values.count == 3)+        #expect(JSON.field("sourcePath", in: values[0]) == .string("/items/0/taskId"))+    }++    @Test func domainStopAndCorrectedFreshKeyResumePreservePrefix() async throws {+        let fixture = try Fixture()+        let first = try fixture.domain.item(0)+        let invalid = try fixture.domain.item(1, changes: ["priority": "invalid-domain-priority"])+        let items = try [first, invalid, fixture.domain.item(2)]+        let stopped = try Fixture.payload(await fixture.call(mode: "execute", items: items))+        #expect(JSON.field("summary", in: stopped) == .string("stopped"))+        guard case .array(let mapped) = JSON.field("items", in: stopped) else {+            Issue.record("Expected mapped outcomes"); return+        }+        #expect(JSON.field("state", in: mapped[2]) == .string("not_attempted"))+        let fixed = try fixture.domain.item(1, changes: ["priority": "high", "idempotencyKey": "corrected.fresh.key"])+        let resumed = try Fixture.payload(await fixture.call(mode: "execute", items: [first, fixed, items[2]]))+        #expect(JSON.field("summary", in: resumed) == .string("all_committed"))+    }++    @Test(arguments: [false, true])+    func previewRemainsAvailableWithoutWriteCoordinator(fallback: Bool) async throws {+        let fixture = try Fixture(fallback: fallback, missingCoordinator: true)+        let item = try fixture.domain.item(0)+        let preview = try Fixture.payload(await fixture.call(mode: "dry_run", items: [item]))+        #expect(JSON.field("summary", in: preview) == .string(fallback ? "preview_invalid" : "preview_valid"))+        let execute = try Fixture.payload(await fixture.call(mode: "execute", items: [item]))+        #expect(JSON.field("summary", in: execute) == .string("stopped"))+        #expect(fixture.domain.saveStages.isEmpty)+    }++    @Test func notificationShapeNeverExecutesOrFabricatesAResponseID() async throws {+        let fixture = try Fixture()+        let item = try fixture.domain.item(0)+        let object: [String: Any] = ["jsonrpc": "2.0", "method": "tools/call", "params": [+            "_meta": MCPModernResultFixture.meta, "name": "mutate_tasks",+            "arguments": ["mode": "execute", "items": [item]]]]+        let bytes = try JSONSerialization.data(withJSONObject: object)+        let response = try await fixture.raw(try #require(String(data: bytes, encoding: .utf8)))+        #expect(response.status == .badRequest && response.body.isEmpty)+        #expect(fixture.domain.saveStages.isEmpty)+    }++    @Test func exactRawFractionalIntegerRejectsBeforeAnyEffects() async throws {+        let fixture = try Fixture()+        let item = try fixture.domain.item(0, changes: ["milestoneDisplayId": 1])+        let body = try MCPModernResultFixture.body(method: "tools/call", parameters: ["name": "mutate_tasks",+            "arguments": ["mode": "execute", "items": [item]]])+        let mutated = body.replacingOccurrences(of: "\"milestoneDisplayId\":1", with:+            "\"milestoneDisplayId\":1.000000000000000000000000000000000000001")+        #expect(mutated != body)+        let payload = try Fixture.payload(await fixture.raw(mutated))+        #expect(JSON.field("summary", in: payload) == .string("rejected_input"))+        #expect(fixture.domain.saveStages.isEmpty)+    }++    @Test func actualRouteEncodingFailureAfterCommitReturnsCorrelatedCompactFallback() async throws {+        let fixture = try Fixture(encoder: { _, _, _ in throw MCPResultBoundaryError.resourceLimit })+        var item = try fixture.domain.item(0, operation: "add_comment")+        let giant = String(repeating: "giant-caller-label", count: 10_000)+        item["itemId"] = giant+        let response = try await fixture.call(mode: "execute", items: [item], id: "fault.rpc")+        let payload = try Fixture.payload(response)+        #expect(JSON.field("summary", in: payload) == .string("serialization_failed"))+        let wire = try #require(String(data: response.body, encoding: .utf8))+        #expect(!wire.contains(giant))+        #expect(JSON.field("id", in: try MCPJSONDocument.parse(response.body).value) == .string("fault.rpc"))+        #expect(try fixture.domain.durableComments().count == 1)+        let request = try fixture.domain.request([item])+        let replay = try await fixture.domain.source(request.items[0])+        #expect(replay.originalIsError == nil)+        #expect(try fixture.domain.durableComments().count == 1)+    }+}+#endif
Transit/TransitTests/MCPBatchTaskPreparedResponseTests.swift Added +76 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskPreparedResponseTests.swift b/Transit/TransitTests/MCPBatchTaskPreparedResponseTests.swiftnew file mode 100644index 00000000..373e9843--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskPreparedResponseTests.swift@@ -0,0 +1,76 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPBatchTaskPreparedResponseTests {+    private typealias Fixture = MCPBatchTaskResultFixtures++    @Test func failedPreparationCannotConstructADispatchCapability() async throws {+        let counts = MCPBatchTaskEncodingCounts()+        do {+            let prepared = try MCPBatchTaskPreparedResponse.prepare(id: .integer(1),+                items: Fixture.recoveryItems(), metadata: nil, checkpoint: {+                    counts.record("prepare"); throw MCPResultBoundaryError.resourceLimit+                })+            _ = try await prepared.select(dispatch: {+                counts.record("dispatch"); throw MCPResultBoundaryError.unsupportedEvidence+            })+            Issue.record("Preparation failure must block capability construction")+        } catch let error as MCPResultBoundaryError { #expect(error == .resourceLimit) }+        #expect(counts.snapshot().prepare == 1 && counts.snapshot().dispatch == 0)+    }++    @Test func readyCapabilitySelectsExactBytesAfterEncodingFailureWithoutPreparingAgain() async throws {+        let counts = MCPBatchTaskEncodingCounts()+        let giantID = "giant-caller-id-" + String(repeating: "x", count: 200_000)+        let items = Fixture.recoveryItems(itemID: giantID)+        let id = JSONRPCId.string("rpc-\"\\")+        let metadata = try Fixture.metadata()+        let expected = try MCPResultEncoder.prepareMutationFallback(id: id,+            source: MCPBatchTaskFallback.source(items: items),+            context: Fixture.context(items: items), metadata: metadata)+        let prepared = try MCPBatchTaskPreparedResponse.prepare(id: id, items: items, metadata: metadata,+                                                               checkpoint: { counts.record("prepare") })+        let checksBeforeDispatch = counts.snapshot().prepare+        #expect(checksBeforeDispatch > 0 && counts.snapshot().dispatch == 0)+        let normal = try MCPResultAdapter.source(text: Fixture.aggregate(original: Fixture.committed()),+                                                isError: nil, origin: .generatedJSON, evidence: .established)+        let context = prepared.context+        let selected = try await prepared.select(encodeOutcome: { _, _, _ in+            counts.record("encode"); throw MCPResultBoundaryError.resourceLimit+        }, dispatch: {+            #expect(counts.snapshot().prepare == checksBeforeDispatch)+            counts.record("dispatch")+            return .init(source: normal, context: context)+        })+        let bytes = try Fixture.reconciliation(selected)+        #expect(bytes == expected)+        #expect(counts.snapshot().prepare == checksBeforeDispatch)+        #expect(counts.snapshot().dispatch == 1 && counts.snapshot().encode == 1)+        let wire = try #require(String(data: bytes, encoding: .utf8))+        #expect(!wire.contains(giantID) && !wire.contains("itemId"))+        #expect(Fixture.field("id", in: try MCPJSONDocument.parse(bytes).value) == .string("rpc-\"\\"))+        #expect(Fixture.field("_meta", in: try Fixture.result(bytes)) == metadata.document.value)+    }++    @Test func providerFailureAfterSyntheticEffectUsesCapabilityWithoutNormalEncoding() async throws {+        let counts = MCPBatchTaskEncodingCounts()+        let items = Fixture.recoveryItems()+        let prepared = try MCPBatchTaskPreparedResponse.prepare(id: .integer(3), items: items, metadata: nil,+                                                               checkpoint: { counts.record("prepare") })+        let checksBeforeDispatch = counts.snapshot().prepare+        let expected = try MCPResultEncoder.prepareMutationFallback(id: .integer(3),+            source: MCPBatchTaskFallback.source(items: items), context: prepared.context, metadata: nil)+        let selected = try await prepared.select(encodeOutcome: { _, _, _ in+            counts.record("encode"); throw MCPResultBoundaryError.invalidJSON+        }, dispatch: {+            counts.record("dispatch"); throw MCPResultBoundaryError.resourceLimit+        })+        #expect(try Fixture.reconciliation(selected) == expected)+        #expect(counts.snapshot().prepare == checksBeforeDispatch)+        #expect(counts.snapshot().dispatch == 1 && counts.snapshot().encode == 0)+    }+}+#endif
Transit/TransitTests/MCPBatchTaskPreviewFixture.swift Added +242 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskPreviewFixture.swift b/Transit/TransitTests/MCPBatchTaskPreviewFixture.swiftnew file mode 100644index 00000000..6fc09a21--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskPreviewFixture.swift@@ -0,0 +1,242 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++/// Persistent saved evidence with a separate dirty UI context. No coordinator,+/// sidecar, recovery store or write admission is constructed by this fixture.+@MainActor final class MCPBatchTaskPreviewFixture {+    enum Fault: Error { case injected }+    let directory: URL+    let storeURL: URL+    let owner: TestModelContainer+    let project: Project+    let targets: [TransitTask]+    let deletion: TransitTask+    let milestone: Milestone+    let comment: Transit.Comment+    let deletedComment: Transit.Comment+    let deletedMilestone: Milestone+    let markerURL: URL+    let marker = Data("preview must not touch reservation evidence".utf8)+    private var savedTaskEvidence: [UUID: String] = [:]+    private var savedCommentEvidence: [UUID: String] = [:]+    private var savedMilestoneEvidence: [UUID: String] = [:]+    var pending: TransitTask?+    var taskReads = 0+    var commentReads = 0+    var milestoneReads = 0+    var privateContexts: [ModelContext] = []+    var taskFault: UUID?+    var commentFault: UUID?+    var milestoneFault = false+    var forcedMatches: Int?+    var failEveryCommentRead = false+    var pendingComment: Transit.Comment?+    var pendingMilestone: Milestone?++    init() throws {+        directory = FileManager.default.temporaryDirectory+            .appendingPathComponent("T2384Task7Preview-" + UUID().uuidString)+        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+        print("T2384_TASK7_PREVIEW_DIRECTORY=" + directory.path)+        storeURL = directory.appendingPathComponent("preview.store")+        markerURL = directory.appendingPathComponent("untouched.guard")+        owner = try Self.diskOwner(storeURL)+        let savedProject = Project(name: "Saved project", description: "", gitRepo: nil, colorHex: "#112233")+        project = savedProject+        targets = (1...3).map {+            TransitTask(name: "Saved \($0)", type: .feature, project: savedProject, displayID: .permanent($0))+        }+        deletion = TransitTask(name: "Saved deletion", type: .feature, project: project, displayID: .permanent(4))+        milestone = Milestone(name: "Saved milestone", project: project, displayID: .permanent(9))+        comment = Comment(content: "Saved full comment", authorName: "Saved author", isAgent: true, task: targets[0])+        deletedComment = Comment(content: "Saved deleted comment", authorName: "Saved author",+                                 isAgent: true, task: targets[0])+        deletedMilestone = Milestone(name: "Saved deleted milestone", project: project, displayID: .permanent(10))+        owner.context.insert(project)+        for task in targets + [deletion] { owner.context.insert(task) }+        owner.context.insert(milestone)+        owner.context.insert(comment)+        owner.context.insert(deletedComment)+        owner.context.insert(deletedMilestone)+        try owner.context.save()+        try marker.write(to: markerURL)+        for task in targets + [deletion] {+            let snapshot = try MCPRecordSnapshot.task(task, in: owner.context)+            savedTaskEvidence[task.id] = try MCPCanonicalJSON.encode(snapshot.coveredFields)+        }+        for value in [comment, deletedComment] {+            savedCommentEvidence[value.id] = try MCPCanonicalJSON.encode(MCPRecordSnapshot.comment(value).coveredFields)+        }+        for value in [milestone, deletedMilestone] {+            let snapshot = try MCPRecordSnapshot.milestone(value)+            savedMilestoneEvidence[value.id] = try MCPCanonicalJSON.encode(snapshot.coveredFields)+        }+    }++    // TestModelContainer retains every container for the test process lifetime.+    // Its backing files must outlive this fixture too. The pinned off-process+    // cleanup consumes only the marker above after all owned hosts drain.++    static func diskOwner(_ url: URL) throws -> TestModelContainer {+        let schema = Schema([Project.self, TransitTask.self, Comment.self, Milestone.self,+                             SyncHeartbeat.self, MCPWriteReceipt.self])+        let configuration = ModelConfiguration(schema: schema, url: url, cloudKitDatabase: .none)+        let owner = try TestModelContainer(schema: schema, configurations: [configuration])+        owner.context.autosaveEnabled = false+        return owner+    }++    func revision(_ index: Int = 0) throws -> String {+        try MCPRecordSnapshot.task(targets[index], in: owner.context).revision+    }++    func item(_ index: Int = 0, operation: String = "update_task",+              changes: [String: Any] = [:]) throws -> [String: Any] {+        var arguments: [String: Any] = ["taskId": targets[index].id.uuidString,+                                        "idempotencyKey": "preview.\(index)"]+        if operation != "add_comment" { arguments["expectedRevision"] = try revision(index) }+        if operation == "update_task_status" { arguments["status"] = "done" }+        if operation == "add_comment" {+            arguments["content"] = " reason "+            arguments["authorName"] = " agent "+        }+        arguments.merge(changes) { _, new in new }+        return ["itemId": "original.\(index)", "operation": operation, "arguments": arguments]+    }++    func request(_ items: [[String: Any]]) throws -> MCPBatchTaskRequest {+        try MCPBatchTaskRequestFixtures.valid(MCPBatchTaskRequestFixtures.document(mode: "dry_run", items: items))+    }++    func reads() -> MCPBatchTaskPreview.Reads {+        MCPBatchTaskPreview.Reads(tasks: { [unowned self] descriptor, context in+            observe(context, pending: descriptor.includePendingChanges)+            taskReads += 1+            let matches = try context.fetch(descriptor)+            if let taskFault, matches.contains(where: { $0.id == taskFault }) { throw Fault.injected }+            if let forcedMatches {+                return Array(matches.prefix(1)).flatMap { Array(repeating: $0, count: forcedMatches) }+            }+            return matches+        }, comments: { [unowned self] descriptor, context in+            observe(context, pending: descriptor.includePendingChanges)+            commentReads += 1+            if failEveryCommentRead { throw Fault.injected }+            let matches = try context.fetch(descriptor)+            if let commentFault, matches.contains(where: { $0.task?.id == commentFault }) { throw Fault.injected }+            return matches+        }, milestones: { [unowned self] context in+            PreviewMilestoneFetcher(context: context, fixture: self)+        })+    }++    func observe(_ context: ModelContext, pending: Bool) {+        #expect(context !== owner.context)+        #expect(!context.autosaveEnabled)+        #expect(!pending)+        #expect(!context.hasChanges)+        if !privateContexts.contains(where: { $0 === context }) { privateContexts.append(context) }+    }++    func makePending(autosave: Bool) {+        targets[0].name = "UI unsaved edit"+        owner.context.delete(deletion)+        let task = TransitTask(name: "UI unsaved insert", type: .feature, project: project, displayID: .provisional)+        owner.context.insert(task)+        pending = task+        comment.content = "UI unsaved comment edit"+        owner.context.delete(deletedComment)+        let insertedComment = Comment(content: "UI unsaved comment insert", authorName: "UI",+                                      isAgent: false, task: targets[0])+        owner.context.insert(insertedComment)+        pendingComment = insertedComment+        milestone.name = "UI unsaved milestone edit"+        owner.context.delete(deletedMilestone)+        let insertedMilestone = Milestone(name: "UI unsaved milestone insert", project: project,+                                         displayID: .permanent(11))+        owner.context.insert(insertedMilestone)+        pendingMilestone = insertedMilestone+        owner.context.autosaveEnabled = autosave+    }++    func assertUntouched(autosave: Bool? = nil) throws {+        #expect(try Data(contentsOf: markerURL) == marker)+        #expect(privateContexts.allSatisfy { !$0.hasChanges && !$0.autosaveEnabled })+        #expect(try owner.context.fetch(FetchDescriptor<MCPWriteReceipt>()).isEmpty)+        if let autosave {+            #expect(owner.context.autosaveEnabled == autosave)+            #expect(owner.context.hasChanges)+            #expect(targets[0].name == "UI unsaved edit")+            #expect(owner.context.insertedModelsArray.contains { $0 === pending })+            #expect(owner.context.deletedModelsArray.contains { $0 === deletion })+            #expect(comment.content == "UI unsaved comment edit")+            #expect(milestone.name == "UI unsaved milestone edit")+            #expect(owner.context.insertedModelsArray.contains { $0 === pendingComment })+            #expect(owner.context.insertedModelsArray.contains { $0 === pendingMilestone })+            #expect(owner.context.deletedModelsArray.contains { $0 === deletedComment })+            #expect(owner.context.deletedModelsArray.contains { $0 === deletedMilestone })+        }+        let durable = try Self.diskOwner(storeURL)+        let tasks = try durable.context.fetch(FetchDescriptor<TransitTask>())+        #expect(tasks.count == 4)+        #expect(tasks.first { $0.id == targets[0].id }?.name == "Saved 1")+        #expect(tasks.contains { $0.id == deletion.id })+        #expect(!tasks.contains { $0.name == "UI unsaved insert" })+        for task in tasks {+            let snapshot = try MCPRecordSnapshot.task(task, in: durable.context)+            #expect(try MCPCanonicalJSON.encode(snapshot.coveredFields) == savedTaskEvidence[task.id])+        }+        let comments = try durable.context.fetch(FetchDescriptor<Transit.Comment>())+        #expect(comments.count == 2)+        #expect(comments.first { $0.id == comment.id }?.content == "Saved full comment")+        #expect(comments.contains { $0.id == deletedComment.id })+        for value in comments {+            let snapshot = try MCPRecordSnapshot.comment(value)+            #expect(try MCPCanonicalJSON.encode(snapshot.coveredFields) == savedCommentEvidence[value.id])+        }+        let milestones = try durable.context.fetch(FetchDescriptor<Milestone>())+        #expect(milestones.count == 2)+        #expect(milestones.first { $0.id == milestone.id }?.name == "Saved milestone")+        #expect(milestones.contains { $0.id == deletedMilestone.id })+        for value in milestones {+            let snapshot = try MCPRecordSnapshot.milestone(value)+            #expect(try MCPCanonicalJSON.encode(snapshot.coveredFields) == savedMilestoneEvidence[value.id])+        }+        #expect(try durable.context.fetch(FetchDescriptor<Project>()).count == 1)+        #expect(try durable.context.fetch(FetchDescriptor<SyncHeartbeat>()).isEmpty)+        #expect(try durable.context.fetch(FetchDescriptor<MCPWriteReceipt>()).isEmpty)+    }++    func verifyPendingAfterReturn(autosave: Bool) {+        do {+            try assertUntouched(autosave: autosave)+        } catch { Issue.record("Pending/durable verification failed: \(error)") }+    }++    func preview(_ items: [[String: Any]], includeComments: Bool = true,+                 fallback: Bool = false) throws -> MCPBatchTaskPreview.Report {+        try MCPBatchTaskPreview.evaluate(request(items), container: owner.container,+            persistence: PersistenceAvailability(isFallbackStorageActive: fallback),+            includeComments: includeComments, reads: reads())+    }++    static func field(_ name: String, _ document: MCPJSONDocument?) -> MCPJSONValue? {+        MCPBatchTaskRequestFixtures.field(name, in: document?.value)+    }+}++@MainActor private struct PreviewMilestoneFetcher: ModelFetching {+    let context: ModelContext+    unowned let fixture: MCPBatchTaskPreviewFixture++    func fetch<T: PersistentModel>(_ descriptor: FetchDescriptor<T>) throws -> [T] {+        fixture.observe(context, pending: descriptor.includePendingChanges)+        fixture.milestoneReads += 1+        if fixture.milestoneFault { throw MCPBatchTaskPreviewFixture.Fault.injected }+        return try context.fetch(descriptor)+    }+}+#endif
Transit/TransitTests/MCPBatchTaskPreviewTests.swift Added +325 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskPreviewTests.swift b/Transit/TransitTests/MCPBatchTaskPreviewTests.swiftnew file mode 100644index 00000000..55323d00--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskPreviewTests.swift@@ -0,0 +1,325 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++// One serialized table-driven suite keeps the owning disk fixture boundary visible.+// swiftlint:disable type_body_length+@MainActor @Suite(.serialized)+struct MCPBatchTaskPreviewTests {+    typealias Fixture = MCPBatchTaskPreviewFixture++    @Test(arguments: ["deleted", "inserted"])+    func pendingMilestoneDeletionAndInsertionUseSavedIdentity(scenario: String) throws {+        let fixture = try Fixture()+        let name = scenario == "deleted" ? "Saved deleted milestone" : "UI unsaved milestone insert"+        let item = try fixture.item(changes: ["milestone": name])+        fixture.makePending(autosave: false)+        defer { fixture.verifyPendingAfterReturn(autosave: false) }+        let report = try fixture.preview([item])+        if scenario == "deleted" {+            #expect(report.entries[0].state == .valid)+            #expect(Fixture.field("milestoneId", report.entries[0].proposedEffects)+                    == .string(fixture.deletedMilestone.id.uuidString))+        } else {+            #expect(report.entries[0].state == .invalid)+            #expect(report.entries[0].code == "MILESTONE_NOT_FOUND")+            #expect(report.entries[0].proposedEffects == nil)+        }+        #expect(fixture.milestoneReads > 0)+        try fixture.assertUntouched(autosave: false)+    }++    @Test+    func pendingInsertionIsMissingButPendingDeletionRemainsSaved() throws {+        let fixture = try Fixture()+        let deletionRevision = try MCPRecordSnapshot.task(fixture.deletion, in: fixture.owner.context).revision+        fixture.makePending(autosave: false)+        let inserted = try #require(fixture.pending)+        let items: [[String: Any]] = [+            ["itemId": "inserted", "operation": "add_comment", "arguments": [+                "taskId": inserted.id.uuidString, "idempotencyKey": "inserted",+                "content": "reason", "authorName": "agent"]],+            ["itemId": "deleted", "operation": "update_task", "arguments": [+                "taskId": fixture.deletion.id.uuidString, "idempotencyKey": "deleted",+                "expectedRevision": deletionRevision]]+        ]+        defer { fixture.verifyPendingAfterReturn(autosave: false) }+        let report = try fixture.preview(items)+        #expect(report.entries.map(\.state) == [.invalid, .valid])+        #expect(report.entries[0].code == "TASK_NOT_FOUND")+        #expect(Fixture.field("name", report.entries[1].current) == .string("Saved deletion"))+        try fixture.assertUntouched(autosave: false)+    }++    @Test(arguments: ["absent", "blank", "content", "invalid", "missingAuthor"])+    func integratedStatusValidationAndSymbolicEffects(scenario: String) throws {+        let fixture = try Fixture()+        var changes: [String: Any] = ["status": scenario == "invalid" ? "unsupported" : "idea"]+        if scenario != "absent" && scenario != "invalid" {+            changes["comment"] = scenario == "content" ? " Reason " : " \n"+            if scenario != "missingAuthor" { changes["authorName"] = " Agent " }+        }+        let report = try fixture.preview([fixture.item(operation: "update_task_status", changes: changes)])+        let entry = report.entries[0]+        if scenario == "invalid" || scenario == "missingAuthor" {+            #expect(entry.state == .invalid)+            #expect(entry.code == (scenario == "invalid" ? "INVALID_STATUS" : "INVALID_INPUT"))+            #expect(entry.proposedEffects == nil)+        } else {+            #expect(entry.state == .valid)+            let effects = try #require(entry.proposedEffects)+            #expect(Fixture.field("statusChanged", effects) == .boolean(false))+            #expect(Fixture.field("lastStatusChange", effects) == .string("unchanged"))+            #expect(Fixture.field("completion", effects) == .string("unchanged"))+            if scenario == "content" {+                let comment = Fixture.field("comment", effects)+                #expect(MCPBatchTaskRequestFixtures.field("content", in: comment) == .string("Reason"))+                #expect(MCPBatchTaskRequestFixtures.field("authorName", in: comment) == .string("Agent"))+            } else { #expect(Fixture.field("comment", effects) == .null) }+        }+        try fixture.assertUntouched()+    }++    @Test(arguments: [false, true])+    func pendingCommentsAndMilestonesNeverAffectSavedPreview(autosave: Bool) throws {+        let fixture = try Fixture()+        let revision = try fixture.revision()+        let item = try fixture.item(changes: ["milestone": "Saved milestone"])+        fixture.makePending(autosave: autosave)+        defer { fixture.verifyPendingAfterReturn(autosave: autosave) }+        let report = try fixture.preview([item])+        #expect(report.entries[0].state == .valid)+        #expect(Fixture.field("revision", report.entries[0].current) == .string(revision))+        #expect(Fixture.field("milestoneId", report.entries[0].proposedEffects)+                == .string(fixture.milestone.id.uuidString))+        #expect(fixture.milestoneReads > 0)+        guard case .array(let comments) = Fixture.field("comments", report.entries[0].current) else {+            Issue.record("Saved full comments required"); return+        }+        #expect(comments.count == 2)+        let texts = comments.compactMap { value -> String? in+            if case .string(let text) = MCPBatchTaskRequestFixtures.field("content", in: value) { return text }+            return nil+        }+        #expect(Set(texts) == ["Saved full comment", "Saved deleted comment"])+        let ids = comments.compactMap { value -> String? in+            if case .string(let id) = MCPBatchTaskRequestFixtures.field("id", in: value) { return id }+            return nil+        }+        #expect(Set(ids) == [fixture.comment.id.uuidString, fixture.deletedComment.id.uuidString])+        try fixture.assertUntouched(autosave: autosave)+    }++    @Test+    func emptyCommentReadFailureDoesNotInventEmptyObservation() throws {+        let fixture = try Fixture()+        fixture.failEveryCommentRead = true+        let report = try fixture.preview([fixture.item(1)], includeComments: false)+        #expect(report.entries[0].state == .unavailable)+        #expect(report.entries[0].current == nil && report.entries[0].proposedEffects == nil)+        #expect(fixture.commentReads == 1)+        try fixture.assertUntouched()+    }++    @Test(arguments: [false, true])+    func savedOnlyPreservesDirtyUI(autosave: Bool) throws {+        let fixture = try Fixture()+        let item = try fixture.item(changes: ["name": " Proposed "])+        fixture.makePending(autosave: autosave)+        defer { fixture.verifyPendingAfterReturn(autosave: autosave) }+        let report = try fixture.preview([item])+        #expect(report.entries.count == 1)+        #expect(report.entries[0].state == .valid)+        #expect(Fixture.field("name", report.entries[0].current) == .string("Saved 1"))+        #expect(Fixture.field("name", report.entries[0].proposedEffects) == .string("Proposed"))+        #expect(report.observation == "saved_local_store")+        #expect(report.keyState == "unchecked")+        #expect(report.advisory)+        #expect(report.isError == nil)+        #expect(fixture.taskReads == 1 && fixture.commentReads == 1)+        try fixture.assertUntouched(autosave: autosave)+    }++    @Test(arguments: [false, true])+    func failedReadPreservesDirtyUI(autosave: Bool) throws {+        let fixture = try Fixture()+        let item = try fixture.item()+        fixture.taskFault = fixture.targets[0].id+        fixture.makePending(autosave: autosave)+        defer { fixture.verifyPendingAfterReturn(autosave: autosave) }+        let report = try fixture.preview([item])+        #expect(report.entries[0].state == .unavailable)+        #expect(report.entries[0].current == nil)+        #expect(report.entries[0].proposedEffects == nil)+        #expect(report.isError == true)+        try fixture.assertUntouched(autosave: autosave)+    }++    @Test(arguments: [0, 1, 2])+    func UUIDCardinality(matches: Int) throws {+        let fixture = try Fixture()+        fixture.forcedMatches = matches+        let report = try fixture.preview([fixture.item()])+        let entry = report.entries[0]+        #expect(entry.state == (matches == 1 ? .valid : .invalid))+        if matches == 0 { #expect(entry.code == "TASK_NOT_FOUND") }+        if matches == 2 { #expect(entry.code == "DUPLICATE_TASK_IDENTIFIER") }+        #expect(fixture.commentReads == (matches == 1 ? 1 : 0))+        try fixture.assertUntouched()+    }++    @Test+    func mixedPreviewVisitsEveryItem() throws {+        let fixture = try Fixture()+        fixture.commentFault = fixture.targets[2].id+        // A required comment read must fail even when that task has no comments.+        let originalReads = fixture.reads()+        var reads = originalReads+        var commentCalls = 0+        reads.comments = { descriptor, context in+            commentCalls += 1+            if commentCalls == 3 {+                fixture.observe(context, pending: descriptor.includePendingChanges)+                throw Fixture.Fault.injected+            }+            return try originalReads.comments(descriptor, context)+        }+        let request = try fixture.request([+            fixture.item(0, changes: ["name": " Valid "]),+            fixture.item(1, changes: ["priority": "unsupported"]),+            fixture.item(2, operation: "add_comment")+        ])+        let report = try MCPBatchTaskPreview.evaluate(request, container: fixture.owner.container,+            persistence: PersistenceAvailability(), reads: reads)+        #expect(report.entries.map(\.index) == [0, 1, 2])+        #expect(report.entries.map(\.itemId) == ["original.0", "original.1", "original.2"])+        #expect(report.entries.map(\.state) == [.valid, .invalid, .unavailable])+        #expect(report.entries[1].code == "INVALID_PRIORITY")+        #expect(report.entries[2].proposedEffects == nil)+        #expect(fixture.taskReads == 3 && commentCalls == 3)+        #expect(report.isError == true && report.advisory && report.keyState == "unchecked")+        try fixture.assertUntouched()+    }++    @Test(arguments: [false, true])+    func commentCoveredRevisionBeforeProjection(includeComments: Bool) throws {+        let fixture = try Fixture()+        let revision = try fixture.revision()+        let report = try fixture.preview([fixture.item()], includeComments: includeComments)+        let current = try #require(report.entries[0].current)+        #expect(Fixture.field("revision", current) == .string(revision))+        if includeComments {+            guard case .array(let comments) = Fixture.field("comments", current) else {+                Issue.record("Full preview must include saved comments"); return+            }+            #expect(comments.count == 2)+        } else { #expect(Fixture.field("comments", current) == nil) }+        #expect(fixture.commentReads == 1)+        try fixture.assertUntouched()+    }++    @Test(arguments: ["task", "comment", "milestone"])+    func requiredReadFailureIsUnavailable(stage: String) throws {+        let fixture = try Fixture()+        let item = try fixture.item(changes: ["milestoneDisplayId": 9])+        if stage == "task" { fixture.taskFault = fixture.targets[0].id }+        if stage == "comment" { fixture.commentFault = fixture.targets[0].id }+        if stage == "milestone" { fixture.milestoneFault = true }+        let report = try fixture.preview([item], includeComments: false)+        #expect(report.entries[0].state == .unavailable)+        #expect(report.entries[0].proposedEffects == nil)+        #expect(report.isError == true)+        try fixture.assertUntouched()+    }++    @Test+    func staleRevisionPrecedesInvalidDomain() throws {+        let fixture = try Fixture()+        let report = try fixture.preview([fixture.item(changes: [+            "expectedRevision": MCPBatchTaskRequestFixtures.revision, "priority": "invalid"+        ])])+        #expect(report.entries[0].state == .invalid)+        #expect(report.entries[0].code == "REVISION_CONFLICT")+        #expect(report.entries[0].current != nil)+        #expect(report.entries[0].proposedEffects == nil)+        try fixture.assertUntouched()+    }++    @Test+    func fallbackHasNoSavedEvidenceOrReads() throws {+        let fixture = try Fixture()+        let report = try fixture.preview([fixture.item(), fixture.item(1)], fallback: true)+        #expect(report.entries.map(\.state) == [.unavailable, .unavailable])+        #expect(report.entries.allSatisfy { $0.code == "PERSISTENCE_UNAVAILABLE" && $0.current == nil })+        #expect(fixture.taskReads == 0 && fixture.commentReads == 0 && fixture.milestoneReads == 0)+        #expect(report.observation == "saved_local_store" && report.keyState == "unchecked" && report.advisory)+        #expect(report.isError == true)+        try fixture.assertUntouched()+    }++    @Test+    func independentSavedCommentInvalidatesEarlierRevision() throws {+        let fixture = try Fixture()+        let item = try fixture.item()+        let first = try fixture.preview([item], includeComments: false)+        #expect(first.entries[0].state == .valid)+        let independent = try Fixture.diskOwner(fixture.storeURL)+        let id = fixture.targets[0].id+        let task = try #require(independent.context.fetch(FetchDescriptor<TransitTask>(+            predicate: #Predicate { $0.id == id })).first)+        let comment = Comment(content: "Later saved evidence", authorName: "Other", isAgent: false, task: task)+        independent.context.insert(comment)+        try independent.context.save()+        let second = try fixture.preview([item], includeComments: false)+        #expect(second.entries[0].state == .invalid)+        #expect(second.entries[0].code == "REVISION_CONFLICT")+        #expect(Fixture.field("revision", first.entries[0].current)+                != Fixture.field("revision", second.entries[0].current))+        #expect(fixture.privateContexts.count == 2)+        #expect(fixture.privateContexts.allSatisfy { !$0.hasChanges })+    }++    @Test(arguments: ["trim", "clear", "metadata", "clearMilestone", "displayPrecedence", "comment"])+    // Each branch asserts a different operation's exact proposed effect.+    // swiftlint:disable:next cyclomatic_complexity+    func proposedEffectsAreNormalizedValuesOnly(scenario: String) throws {+        let fixture = try Fixture()+        let changes: [String: Any]+        switch scenario {+        case "trim": changes = ["name": " Name ", "description": " Description "]+        case "clear": changes = ["description": " \n\t "]+        case "metadata": changes = ["metadata": [:] as [String: String]]+        case "clearMilestone": changes = ["clearMilestone": true, "milestoneDisplayId": 999, "milestone": "Missing"]+        case "displayPrecedence": changes = ["milestoneDisplayId": 9, "milestone": "Missing"]+        default: changes = ["content": " Reason \n", "authorName": " Agent \t"]+        }+        let operation = scenario == "comment" ? "add_comment" : "update_task"+        let report = try fixture.preview([fixture.item(operation: operation, changes: changes)])+        let entry = report.entries[0]+        #expect(entry.state == .valid)+        let effects = try #require(entry.proposedEffects)+        if scenario == "trim" {+            #expect(Fixture.field("name", effects) == .string("Name"))+            #expect(Fixture.field("description", effects) == .string("Description"))+        }+        if scenario == "clear" { #expect(Fixture.field("description", effects) == .null) }+        if scenario == "metadata" { #expect(Fixture.field("metadata", effects) == .null) }+        if scenario == "clearMilestone" { #expect(Fixture.field("milestone", effects) == .null) }+        if scenario == "displayPrecedence" {+            #expect(Fixture.field("milestoneId", effects) == .string(fixture.milestone.id.uuidString))+        }+        if scenario == "comment" {+            #expect(Fixture.field("content", effects) == .string("Reason"))+            #expect(Fixture.field("authorName", effects) == .string("Agent"))+            #expect(Fixture.field("isAgent", effects) == .boolean(true))+        }+        for field in ["commentId", "creationDate", "lastStatusChangeDate", "completionDate", "displayId"] {+            #expect(Fixture.field(field, effects) == nil)+        }+        try fixture.assertUntouched()+    }+}+// swiftlint:enable type_body_length+#endif
Transit/TransitTests/MCPBatchTaskRequestBoundaryTests.swift Added +111 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskRequestBoundaryTests.swift b/Transit/TransitTests/MCPBatchTaskRequestBoundaryTests.swiftnew file mode 100644index 00000000..9bf90645--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskRequestBoundaryTests.swift@@ -0,0 +1,111 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPBatchTaskRequestBoundaryTests {+    private typealias Fixture = MCPBatchTaskRequestFixtures++    @Test(arguments: ["1.0", "1e0", "10e-1", "-0.0", "0e999999999999999999999", "9007199254740993",+                      "9223372036854775807", "-9223372036854775808", "1.0000000000000000000000001",+                      "0.9999999999999999999999999", "1e-999", "-1e-999", "9223372036854775808",+                      "-9223372036854775809", "1e999999999999999999999"])+    func exactIntegerBridgeRejectsRoundedFractionsAndRangeOverflow(lexeme: String) throws {+        let text = """+        {"mode":"execute","items":[{"itemId":"caller","operation":"update_task","arguments":{+          "taskId":"\(Fixture.taskID(0))","idempotencyKey":"key","expectedRevision":"\(Fixture.revision)",+          "milestoneDisplayId":\(lexeme)}}]}+        """+        let document = try MCPJSONDocument.parse(text)+        let expected: [String: Int] = ["1.0": 1, "1e0": 1, "10e-1": 1, "-0.0": 0,+                                     "0e999999999999999999999": 0, "9007199254740993": 9_007_199_254_740_993,+                                     "9223372036854775807": Int.max, "-9223372036854775808": Int.min]+        if let integer = expected[lexeme] {+            let item = try #require(Fixture.valid(document).items.first)+            #expect(item.command.arguments["milestoneDisplayId"] as? Int == integer)+            guard case .number(let number) = Fixture.field("milestoneDisplayId", in: item.originalArguments) else {+                Issue.record("Lossless original numeric evidence required"); return+            }+            #expect(number.lexeme == lexeme)+        } else {+            try Fixture.invalid(document, index: 0, itemId: "caller", field: "milestoneDisplayId")+        }+    }++    @Test(arguments: ["collision", "singleDecomposed"])+    func metadataNamesMustSurviveExistingDictionaryBridgeWithoutLoss(kind: String) throws {+        let members = kind == "collision" ? #""é":"first","e\u0301":"second""# : #""e\u0301":" untouched ""#+        let text = """+        {"mode":"execute","items":[{"itemId":"caller","operation":"update_task","arguments":{+          "taskId":"\(Fixture.taskID(0))","idempotencyKey":"key","expectedRevision":"\(Fixture.revision)",+          "metadata":{\(members)}}}]}+        """+        let document = try MCPJSONDocument.parse(text)+        if kind == "collision" {+            try Fixture.invalid(document, index: 0, itemId: "caller", field: "metadata")+        } else {+            let item = try #require(Fixture.valid(document).items.first)+            let metadata = try #require(item.command.arguments["metadata"] as? [String: String])+            let key = try #require(metadata.keys.first)+            #expect(key.utf8.elementsEqual("e\u{0301}".utf8))+            #expect(metadata[key]?.utf8.elementsEqual(" untouched ".utf8) == true)+            #expect(metadata.count == 1)+        }+        #expect(document.originalUTF8.elementsEqual(text.utf8))+    }++    @Test(arguments: ["idempotencyKey", "unknowné", "unknowne\u{0301}"])+    func structuralFieldNamesCannotMasqueradeThroughCanonicalEquality(name: String) throws {+        let text = """+        {"mode":"execute","items":[{"itemId":"caller.0","operation":"update_task","arguments":{+          "taskId":"\(Fixture.taskID(0))","idempotencyKey":"key","expectedRevision":"\(Fixture.revision)",+          "\(name)":"key"}}]}+        """+        let document = try MCPJSONDocument.parse(text)+        switch try MCPBatchTaskRequest.parse(document) {+        case .valid: Issue.record("Closed structural names require scalar-exact matching")+        case .invalid(let diagnostics):+            #expect(diagnostics.contains {+                $0.index == 0 && $0.itemId == "caller.0" && $0.code == "INVALID_INPUT" &&+                    $0.field.utf8.elementsEqual(name.utf8)+            })+        }+    }++    @Test(arguments: ["root", "item", "arguments"])+    func rawValueSeamStillRejectsDuplicateStructuralMembers(location: String) throws {+        let source = try Fixture.document(items: [Fixture.item()]).value+        func duplicated(_ value: MCPJSONValue, name: String) throws -> MCPJSONValue {+            guard case .object(var members) = value else { throw MCPResultBoundaryError.unsupportedEvidence }+            let original = try #require(members.first { $0.name == name })+            members.append(original)+            return .object(members)+        }+        let changed: MCPJSONValue+        let field: String+        if location == "root" {+            changed = try duplicated(source, name: "mode"); field = "mode"+        } else {+            guard case .object(var root) = source else { throw MCPResultBoundaryError.unsupportedEvidence }+            let item = try #require(Fixture.array(Fixture.field("items", in: source)).first)+            let mutated: MCPJSONValue+            if location == "item" { mutated = try duplicated(item, name: "itemId"); field = "itemId" } else {+                guard case .object(var members) = item else { throw MCPResultBoundaryError.unsupportedEvidence }+                let arguments = try #require(Fixture.field("arguments", in: item))+                members.removeAll { $0.name == "arguments" }+                members.append(.init(name: "arguments", value: try duplicated(arguments, name: "taskId")))+                mutated = .object(members); field = "taskId"+            }+            root.removeAll { $0.name == "items" }+            root.append(.init(name: "items", value: .array([mutated])))+            changed = .object(root)+        }+        switch try MCPBatchTaskRequest.parse(validatedValue: changed) {+        case .valid: Issue.record("Raw immutable argument seam cannot bypass duplicate member rejection")+        case .invalid(let diagnostics):+            #expect(diagnostics.contains { $0.field == field && $0.code == "INVALID_INPUT" })+        }+    }+}+#endif
Transit/TransitTests/MCPBatchTaskRequestFixtures.swift Added +86 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskRequestFixtures.swift b/Transit/TransitTests/MCPBatchTaskRequestFixtures.swiftnew file mode 100644index 00000000..97f13126--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskRequestFixtures.swift@@ -0,0 +1,86 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++/// JSON and admitted-item counters only; no stores, models or write services.+@MainActor enum MCPBatchTaskRequestFixtures {+    static let revision = "r1:" + String(repeating: "a", count: 64)++    static func taskID(_ index: Int) -> String {+        String(format: "12345678-1234-4123-a123-%012d", index + 1)+    }++    static func item(_ index: Int = 0, operation: String = "update_task") -> [String: Any] {+        var arguments: [String: Any] = ["taskId": taskID(index), "idempotencyKey": "batch.key.\(index)"]+        if operation != "add_comment" { arguments["expectedRevision"] = revision }+        if operation == "update_task" { arguments["name"] = " Original name " }+        if operation == "update_task_status" { arguments["status"] = "done" }+        if operation == "add_comment" {+            arguments["content"] = " Original reason "+            arguments["authorName"] = " Agent "+        }+        return ["itemId": "caller.\(index)", "operation": operation, "arguments": arguments]+    }++    static func document(mode: Any = "execute", items: [[String: Any]]) throws -> MCPJSONDocument {+        try document(["mode": mode, "items": items])+    }++    static func document(_ value: Any) throws -> MCPJSONDocument {+        try MCPJSONDocument.parse(JSONSerialization.data(withJSONObject: value, options: [.fragmentsAllowed]))+    }++    static func valid(_ document: MCPJSONDocument) throws -> MCPBatchTaskRequest {+        switch try MCPBatchTaskRequest.parse(document) {+        case .valid(let request): return request+        case .invalid(let diagnostics):+            Issue.record("Expected valid whole shape, got \(diagnostics.map(\.field))")+            throw MCPResultBoundaryError.unsupportedEvidence+        }+    }++    static func invalid(_ document: MCPJSONDocument, index: Int? = nil, itemId: String? = nil,+                        field: String? = nil) throws {+        switch try MCPBatchTaskRequest.parse(document) {+        case .valid: Issue.record("Malformed whole shape must not be admitted")+        case .invalid(let diagnostics):+            #expect(!diagnostics.isEmpty)+            #expect(diagnostics.allSatisfy { $0.code == "INVALID_INPUT" && !$0.field.isEmpty })+            if let index {+                #expect(diagnostics.contains { $0.index == index && (itemId == nil || $0.itemId == itemId) })+            }+            if let field { #expect(diagnostics.contains { $0.field == field }) }+        }+    }++    static func field(_ name: String, in value: MCPJSONValue?) -> MCPJSONValue? {+        guard case .object(let members) = value else { return nil }+        return members.first { $0.name == name }?.value+    }++    static func array(_ value: MCPJSONValue?) throws -> [MCPJSONValue] {+        guard case .array(let elements) = value else {+            Issue.record("Expected a schema array"); throw MCPResultBoundaryError.unsupportedEvidence+        }+        return elements+    }++    static func names(_ value: MCPJSONValue?) throws -> Set<String> {+        Set(try array(value).compactMap {+            if case .string(let name) = $0 { return name }+            return nil+        })+    }++    static func permuted(_ items: [[String: Any]], seed: UInt64) -> [[String: Any]] {+        var shuffled = items+        var state = seed+        for index in stride(from: shuffled.count - 1, through: 1, by: -1) {+            state = state &* 6_364_136_223_846_793_005 &+ 1+            shuffled.swapAt(index, Int(state % UInt64(index + 1)))+        }+        return shuffled+    }+}+#endif
Transit/TransitTests/MCPBatchTaskRequestTests.swift Added +282 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskRequestTests.swift b/Transit/TransitTests/MCPBatchTaskRequestTests.swiftnew file mode 100644index 00000000..468a28ab--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskRequestTests.swift@@ -0,0 +1,282 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPBatchTaskRequestTests {+    private typealias Fixture = MCPBatchTaskRequestFixtures++    @Test(arguments: [0, 1, 50, 51])+    func itemCountBoundsApplyBeforeAdmission(count: Int) throws {+        let document = try Fixture.document(items: (0..<count).map { Fixture.item($0) })+        if (1...50).contains(count) {+            let request = try Fixture.valid(document)+            #expect(request.items.count == count && request.mode == .execute)+            #expect(request.items.map(\.index) == Array(0..<count))+        } else { try Fixture.invalid(document, field: "items") }+    }++    @Test(arguments: ["execute", "dry_run", "Execute", "dry-run", "", "number", "boolean", "null"])+    func explicitModeUsesExactStringValues(mode: String) throws {+        let value: Any+        switch mode {+        case "number": value = 1+        case "boolean": value = true+        case "null": value = NSNull()+        default: value = mode+        }+        let document = try Fixture.document(mode: value, items: [Fixture.item()])+        if mode == "execute" || mode == "dry_run" {+            #expect(try Fixture.valid(document).mode.rawValue == mode)+        } else { try Fixture.invalid(document, field: "mode") }+    }++    @Test(arguments: ["update_task", "update_task_status", "add_comment", "create_task", "UPDATE_TASK"])+    func onlyExplicitProtectedTaskOperationsAreAdmitted(operation: String) throws {+        let document = try Fixture.document(items: [Fixture.item(operation: operation)])+        if ["update_task", "update_task_status", "add_comment"].contains(operation) {+            let item = try #require(Fixture.valid(document).items.first)+            #expect(item.operation == operation && item.command.tool == operation)+        } else { try Fixture.invalid(document, index: 0, itemId: "caller.0", field: "operation") }+    }++    @Test(arguments: ["missingMode", "missingItems", "outerKey", "correlation", "itemsObject",+                      "itemsNull", "outerArray", "outerBoolean"])+    func outerMissingUnknownAndWrongTypesRejectWholeShape(kind: String) throws {+        var root: [String: Any] = ["mode": "execute", "items": [Fixture.item()]]+        switch kind {+        case "missingMode": root.removeValue(forKey: "mode")+        case "missingItems": root.removeValue(forKey: "items")+        case "outerKey": root["idempotencyKey"] = "outer.forbidden"+        case "correlation": root["batchId"] = "unsupported"+        case "itemsObject": root["items"] = ["0": Fixture.item()]+        case "itemsNull": root["items"] = NSNull()+        default: break+        }+        let value: Any+        switch kind {+        case "outerArray": value = [root]+        case "outerBoolean": value = true+        default: value = root+        }+        try Fixture.invalid(Fixture.document(value))+    }++    @Test(arguments: ["missingID", "missingOperation", "missingArguments", "extra", "idBoolean",+                      "idNumber", "idEmpty", "idBlank", "operationNumber", "argumentsArray", "argumentsNull",+                      "argumentsScalar",+                      "itemNull"])+    func itemShapeDiagnosticsRetainUsableCallerMapping(kind: String) throws {+        var item = Fixture.item()+        let mutations: [String: (String, Any?)] = [+            "missingID": ("itemId", nil), "missingOperation": ("operation", nil),+            "missingArguments": ("arguments", nil), "extra": ("retry", true),+            "idBoolean": ("itemId", true), "idNumber": ("itemId", 1), "idEmpty": ("itemId", ""),+            "idBlank": ("itemId", " \n\t "), "operationNumber": ("operation", 1),+            "argumentsArray": ("arguments", [] as [String]), "argumentsNull": ("arguments", NSNull()),+            "argumentsScalar": ("arguments", "arguments")+        ]+        if let (field, value) = mutations[kind] { item[field] = value }+        if kind == "itemNull" {+            try Fixture.invalid(Fixture.document(["mode": "execute", "items": [NSNull()]]), index: 0)+        } else {+            let usable = ["missingOperation", "missingArguments", "extra", "operationNumber", "argumentsArray",+                          "argumentsNull", "argumentsScalar"]+            try Fixture.invalid(Fixture.document(items: [item]), index: 0,+                                itemId: usable.contains(kind) ? "caller.0" : nil)+        }+    }++    @Test(arguments: ["missingTask", "displayID", "invalidUUID", "taskNull", "taskNumber",+                      "missingKey", "blankKey", "unicodeKey", "longKey", "keyNull", "keyBoolean", "keyNewline",+                      "keyTrailingNewline",+                      "missingRevision", "badRevision", "upperRevision", "revisionNumber", "revisionNewline",+                      "statusMissing", "contentMissing", "commentAuthorMissing", "commentRevision", "unknownArgument"])+    func requiredSafetyAndOperationFieldsRejectBeforeAnyItem(kind: String) throws {+        let operation = kind.hasPrefix("comment") || kind == "contentMissing" ? "add_comment" :+            kind == "statusMissing" ? "update_task_status" : "update_task"+        var item = Fixture.item(1, operation: operation)+        var arguments = try #require(item["arguments"] as? [String: Any])+        let mutations: [String: (String, Any?)] = [+            "missingTask": ("taskId", nil), "displayID": ("displayId", 42), "invalidUUID": ("taskId", "T-42"),+            "taskNull": ("taskId", NSNull()), "taskNumber": ("taskId", 42),+            "missingKey": ("idempotencyKey", nil), "blankKey": ("idempotencyKey", ""),+            "unicodeKey": ("idempotencyKey", "key.é"),+            "longKey": ("idempotencyKey", String(repeating: "k", count: 129)),+            "keyNull": ("idempotencyKey", NSNull()), "keyBoolean": ("idempotencyKey", true),+            "keyNewline": ("idempotencyKey", "key\ninside"), "keyTrailingNewline": ("idempotencyKey", "key\n"),+            "missingRevision": ("expectedRevision", nil),+            "badRevision": ("expectedRevision", "r1:" + String(repeating: "a", count: 63)),+            "upperRevision": ("expectedRevision", Fixture.revision.uppercased()),+            "revisionNumber": ("expectedRevision", 1), "revisionNewline": ("expectedRevision", Fixture.revision + "\n"),+            "statusMissing": ("status", nil), "contentMissing": ("content", nil),+            "commentAuthorMissing": ("authorName", nil), "commentRevision": ("expectedRevision", Fixture.revision),+            "unknownArgument": ("unsupported", "value")+        ]+        let (field, value) = try #require(mutations[kind])+        arguments[field] = value+        item["arguments"] = arguments+        try Fixture.invalid(Fixture.document(items: [Fixture.item(), item]), index: 1, itemId: "caller.1", field: field)+    }++    @Test(arguments: ["nameBoolean", "descriptionNull", "typeNumber", "priorityArray", "statusBoolean",+                      "commentObject", "authorNumber", "contentBoolean", "milestoneBoolean", "integerBoolean",+                      "integerFraction", "integerString", "boolNumber", "boolString", "metadataArray", "metadataNumber",+                      "metadataBoolean", "metadataNull"])+    func actualJSONTypesDoNotCoerceBooleansNumbersOrMetadata(kind: String) throws {+        let operation = kind == "contentBoolean" ? "add_comment" :+            ["statusBoolean", "commentObject", "authorNumber"].contains(kind) ? "update_task_status" : "update_task"+        var item = Fixture.item(operation: operation)+        var arguments = try #require(item["arguments"] as? [String: Any])+        let mutations: [String: (String, Any)] = [+            "nameBoolean": ("name", true), "descriptionNull": ("description", NSNull()),+            "typeNumber": ("type", 1), "priorityArray": ("priority", ["high"]), "statusBoolean": ("status", true),+            "commentObject": ("comment", ["content": "reason"]), "authorNumber": ("authorName", 1),+            "contentBoolean": ("content", true), "milestoneBoolean": ("milestone", false),+            "integerBoolean": ("milestoneDisplayId", true), "integerFraction": ("milestoneDisplayId", 1.5),+            "integerString": ("milestoneDisplayId", "1"), "boolNumber": ("clearMilestone", 1),+            "boolString": ("clearMilestone", "true"), "metadataArray": ("metadata", ["tag"]),+            "metadataBoolean": ("metadata", ["tag": true]), "metadataNull": ("metadata", ["tag": NSNull()]),+            "metadataNumber": ("metadata", ["tag": 1])+        ]+        let (field, value) = try #require(mutations[kind])+        arguments[field] = value+        item["arguments"] = arguments+        try Fixture.invalid(Fixture.document(items: [item]), index: 0, itemId: "caller.0", field: field)+    }++}++@MainActor extension MCPBatchTaskRequestTests {+    @Test(arguments: ["boolean", "integer", "equivalentInteger", "metadata", "keyBoundary"])+    func validTypedArgumentsRemainUnnormalizedForOriginalBinding(kind: String) throws {+        var item = Fixture.item()+        var arguments = try #require(item["arguments"] as? [String: Any])+        switch kind {+        case "boolean": arguments["clearMilestone"] = false+        case "integer", "equivalentInteger": arguments["milestoneDisplayId"] = 1+        case "metadata": arguments["metadata"] = ["tag": " Original value "]+        default: arguments["idempotencyKey"] = String(repeating: "a", count: 128)+        }+        arguments["taskId"] = Fixture.taskID(0).lowercased()+        arguments["description"] = " Original e\u{0301} description "+        item["arguments"] = arguments+        var document = try Fixture.document(items: [item])+        if kind == "equivalentInteger" {+            let text = try #require(String(data: document.originalUTF8, encoding: .utf8))+            let replaced = text.replacingOccurrences(of: "\"milestoneDisplayId\":1",+                                                      with: "\"milestoneDisplayId\":1.0")+            #expect(replaced != text)+            document = try MCPJSONDocument.parse(replaced)+        }+        let parsed = try #require(Fixture.valid(document).items.first)+        for field in ["taskId", "name", "description"] {+            let original = try #require(arguments[field] as? String)+            let retained = try #require(parsed.command.arguments[field] as? String)+            #expect(retained.utf8.elementsEqual(original.utf8))+        }+        if kind == "equivalentInteger" {+            guard case .number(let value) = Fixture.field("milestoneDisplayId", in: parsed.originalArguments) else {+                Issue.record("Expected original exact numeric lexeme"); return+            }+            #expect(value.lexeme == "1.0")+        }+        #expect(parsed.targetTaskId == UUID(uuidString: Fixture.taskID(0)))+        let logicalItems = try Fixture.array(Fixture.field("items", in: document.value))+        #expect(parsed.originalArguments == Fixture.field("arguments", in: logicalItems.first))+        #expect(try MCPCanonicalJSON.encode(parsed.command.arguments) == MCPCanonicalJSON.encode(arguments))+    }++    @Test func updateWithOnlyRequiredSafetyFieldsRemainsAValidNoOpShape() throws {+        var item = Fixture.item()+        var arguments = try #require(item["arguments"] as? [String: Any])+        arguments.removeValue(forKey: "name")+        item["arguments"] = arguments+        let parsed = try #require(Fixture.valid(Fixture.document(items: [item])).items.first)+        #expect(Set(parsed.command.arguments.keys) == ["taskId", "expectedRevision", "idempotencyKey"])+        #expect(try MCPCanonicalJSON.encode(parsed.command.arguments) == MCPCanonicalJSON.encode(arguments))+    }++    @Test(arguments: ["status", "type", "priority", "statusEmpty", "typeEmpty", "priorityEmpty", "statusCommentAuthor"])+    func domainStringsAndConditionalAuthorStayOutsideWholeShapeValidation(kind: String) throws {+        let operation = kind.hasPrefix("status") ? "update_task_status" : "update_task"+        var item = Fixture.item(operation: operation)+        var arguments = try #require(item["arguments"] as? [String: Any])+        if kind == "statusCommentAuthor" {+            arguments["comment"] = "Reason"+        } else if kind.hasSuffix("Empty") {+            arguments[String(kind.dropLast(5))] = ""+        } else { arguments[kind] = "not-a-domain-value" }+        item["arguments"] = arguments+        let parsed = try #require(Fixture.valid(Fixture.document(items: [item])).items.first)+        #expect(parsed.command.tool == operation)+        #expect(try MCPCanonicalJSON.encode(parsed.command.arguments) == MCPCanonicalJSON.encode(arguments))+    }++    @Test(arguments: ["itemId", "taskAlias", "toolKey", "sameTaskDifferentOperation"])+    func collisionNamespacesAreDistinctAndCheckedOverTheWholeRequest(kind: String) throws {+        var first = Fixture.item()+        var second = Fixture.item(1)+        var arguments = try #require(second["arguments"] as? [String: Any])+        switch kind {+        case "itemId": second["itemId"] = first["itemId"]+        case "taskAlias": arguments["taskId"] = Fixture.taskID(0).uppercased()+        case "toolKey": arguments["idempotencyKey"] = "batch.key.0"+        default:+            first = Fixture.item(operation: "add_comment")+            arguments["taskId"] = Fixture.taskID(0)+        }+        second["arguments"] = arguments+        try Fixture.invalid(Fixture.document(items: [first, second]), index: 1, itemId: second["itemId"] as? String)+    }++    @Test(arguments: ["case", "unicode", "sameKeyDifferentTool"])+    func opaqueCallerIDsAndToolScopedKeysDoNotAcquireExtraNormalization(kind: String) throws {+        var first = Fixture.item()+        var second = Fixture.item(1, operation: kind == "sameKeyDifferentTool" ? "add_comment" : "update_task")+        if kind == "unicode" {+            first["itemId"] = "é"; second["itemId"] = "e\u{0301}"+        } else { first["itemId"] = "Caller"; second["itemId"] = "caller" }+        if kind == "sameKeyDifferentTool" {+            var arguments = try #require(second["arguments"] as? [String: Any])+            arguments["idempotencyKey"] = "batch.key.0"+            second["arguments"] = arguments+        }+        let parsed = try Fixture.valid(Fixture.document(items: [first, second]))+        #expect(parsed.items.count == 2)+        #expect(parsed.items[0].itemId.unicodeScalars.elementsEqual((first["itemId"] as? String ?? "").unicodeScalars))+        #expect(parsed.items[1].itemId.unicodeScalars.elementsEqual((second["itemId"] as? String ?? "").unicodeScalars))+    }++    @Test(arguments: [UInt64(1), 7, 41, 2_384])+    func seededPermutationsPreserveInputOrderAndRejectInjectedCollisions(seed: UInt64) throws {+        let shuffled = Fixture.permuted((0..<12).map { Fixture.item($0) }, seed: seed)+        let request = try Fixture.valid(Fixture.document(items: shuffled))+        #expect(request.items.map(\.itemId) == shuffled.compactMap { $0["itemId"] as? String })+        #expect(request.items.map(\.index) == Array(0..<12))+        for collision in ["itemId", "taskId", "idempotencyKey"] {+            var items = shuffled+            if collision == "itemId" { items[11][collision] = items[0][collision] } else {+                var last = try #require(items[11]["arguments"] as? [String: Any])+                let first = try #require(items[0]["arguments"] as? [String: Any])+                last[collision] = first[collision]+                items[11]["arguments"] = last+            }+            try Fixture.invalid(Fixture.document(items: items), index: 11, itemId: items[11]["itemId"] as? String)+        }+    }++    @Test func invalidLastItemPreventsAdmissionOfEveryEarlierValidItem() throws {+        var invalid = Fixture.item(2)+        invalid["arguments"] = ["taskId": Fixture.taskID(2)]+        let document = try Fixture.document(items: [Fixture.item(), Fixture.item(1), invalid])+        var admissions = 0+        switch try MCPBatchTaskRequest.parse(document) {+        case .valid(let request): admissions += request.items.count+        case .invalid(let diagnostics): #expect(diagnostics.contains { $0.index == 2 && $0.itemId == "caller.2" })+        }+        #expect(admissions == 0)+    }+}+#endif
Transit/TransitTests/MCPBatchTaskResponseTests.swift Added +70 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskResponseTests.swift b/Transit/TransitTests/MCPBatchTaskResponseTests.swiftnew file mode 100644index 00000000..7e992185--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskResponseTests.swift@@ -0,0 +1,70 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPBatchTaskResponseTests {+    private typealias Fixture = MCPBatchTaskResultFixtures+    private typealias Sequence = MCPBatchTaskCoordinatorSequenceFixtures++    @Test(arguments: [false, true])+    func actualResponseAdapterUsesOneEncoderAndPreservesCommittedReceipt(failEncoding: Bool) async throws {+        let fixture = try MCPBatchTaskCoordinatorFixture()+        let request = try fixture.request([fixture.item(0, operation: "add_comment")])+        let prepared = try Sequence.prepared(request)+        let counts = MCPBatchTaskEncodingCounts()+        let selected = try await MCPBatchTaskResponse.execute(request, prepared: prepared,+            writeCoordinator: try #require(fixture.coordinator), encodeOutcome: { outcome, id, metadata in+                counts.record("encode")+                if failEncoding { throw MCPResultBoundaryError.resourceLimit }+                return try MCPResultProviderSelection.encode(outcome: outcome, id: id, metadata: metadata)+            })+        #expect(counts.snapshot().encode == 1)+        let bytes: Data+        switch selected {+        case .normal(let value): #expect(!failEncoding); bytes = value+        case .reconciliation(let value): #expect(failEncoding); bytes = value+        case .suppressed: Issue.record("Unexpected delivery suppression"); return+        }+        let result = try Fixture.result(bytes)+        let payload = Fixture.field("payload", in: Fixture.field("source",+            in: Fixture.field("structuredContent", in: result)))+        #expect(Fixture.field("summary", in: payload) ==+            .string(failEncoding ? "serialization_failed" : "all_committed"))+        #expect(try fixture.durableComments().count == 1)+        let replay = try await fixture.source(request.items[0])+        #expect(replay.originalIsError == nil)+        #expect(try fixture.durableComments().count == 1)+    }++    @Test func failedPreparationPreventsResponseAdapterAndEffects() throws {+        let fixture = try MCPBatchTaskCoordinatorFixture()+        let request = try fixture.request([fixture.item(0)])+        do {+            _ = try MCPBatchTaskPreparedResponse.prepare(id: .integer(42), items: request.items.map {+                .init(index: $0.index, itemId: $0.itemId, operation: $0.operation,+                    originalKey: .init(tool: $0.command.tool, idempotencyKey: $0.command.key),+                    targetTaskId: $0.targetTaskId)+            }, metadata: nil, checkpoint: { throw MCPResultBoundaryError.resourceLimit })+            Issue.record("Preparation fault must produce no execution capability")+        } catch let error as MCPResultBoundaryError { #expect(error == .resourceLimit) }+        #expect(fixture.saveStages.isEmpty)+        #expect(try fixture.durableTasks().first { $0.id == fixture.tasks[0].id }?.taskDescription == nil)+    }++    @Test func outputSchemaPreservesCommonWrapperAndUnrestrictedOriginalJSON() throws {+        let descriptor = try MCPBatchTaskOutputSchema.descriptor(description: "Batch mutations")+        let root = descriptor.outputSchema.value+        let definitions = Fixture.field("$defs", in: root)+        let payload = Fixture.field("batchPayload", in: definitions)+        #expect(Fixture.field("type", in: root) == .string("object"))+        #expect(Fixture.field("additionalProperties", in: root) == .boolean(false))+        let items = Fixture.field("items", in: Fixture.field("items", in: Fixture.field("properties", in: payload)))+        let original = Fixture.field("originalResult", in: Fixture.field("properties", in: items))+        #expect(Fixture.field("payload", in: Fixture.field("properties", in: original)) == .object([]))+        #expect(Fixture.field("type", in: Fixture.field("text", in: Fixture.field("properties", in: original))) ==+            .string("string"))+    }+}+#endif
Transit/TransitTests/MCPBatchTaskResultFixtures.swift Added +113 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskResultFixtures.swift b/Transit/TransitTests/MCPBatchTaskResultFixtures.swiftnew file mode 100644index 00000000..88c41d34--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskResultFixtures.swift@@ -0,0 +1,113 @@+#if os(macOS)+import Foundation+import Synchronization+import Testing+@testable import Transit++/// Synthetic, immutable evidence only: no models, receipt store or live writes.+nonisolated enum MCPBatchTaskResultFixtures {+    static let taskID = UUID(uuidString: "11111111-1111-4111-8111-a11111111111")!+    static let commentID = UUID(uuidString: "22222222-2222-4222-8222-b22222222222")!+    static let revision = "r1:" + String(repeating: "a", count: 64)+    static let key = "batch.original"+    static let taskRecord = """+    {"taskId":"\(taskID.uuidString)","name":"Saved task","description":null,"status":"done",\+    "type":"feature","priority":"medium","metadata":{},"comments":[],\+    "creationDate":"2026-01-01T00:00:00.000Z","lastStatusChangeDate":"2026-01-01T00:00:00.000Z",\+    "revision":"\(revision)"}+    """+    static let commentRecord = """+    {"id":"\(commentID.uuidString)","taskId":"\(taskID.uuidString)","content":"Saved reason",\+    "authorName":"Agent","isAgent":true,"creationDate":"2026-01-01T00:00:00.000Z",\+    "revision":"\(revision)"}+    """++    static func committed(operation: String = "update_task", version: String = "1", extra: String = "") -> String {+        let record = operation == "add_comment" ? commentRecord : taskRecord+        let entity = operation == "add_comment" ? commentID : taskID+        return """+        {"contractVersion":\(version),"tool":"\(operation)","idempotencyKey":"\(key)",\+        "outcome":"committed","accepted":true,"entityId":"\(entity.uuidString)","record":\(record),\+        "completedAt":"2026-01-01T00:00:00.000Z","replayExpiresAt":"2026-01-08T00:00:00.000Z"\(extra)}+        """+    }++    static func source(_ text: String, isError: Bool? = nil, evidence: MCPResultEvidence = .established)+        throws -> MCPResultSource {+        try MCPResultAdapter.source(text: text, isError: isError, origin: .retainedJSON, evidence: evidence)+    }++    static func recoveryItems(itemID: String = "caller-item") -> [MCPBatchRecoveryItem] {+        [.init(index: 0, itemId: itemID, operation: "update_task",+               originalKey: .init(tool: "update_task", idempotencyKey: key), targetTaskId: taskID)]+    }++    static func context(items: [MCPBatchRecoveryItem], diagnostic: String? = nil,+                        links: [MCPResultEntityPosition] = []) -> MCPResultContext {+        .init(tool: "mutate_tasks", semanticFailure: diagnostic.map {+            .init(category: .serializationFailure, diagnostic: $0)+        }, mutationRecovery: .applicationBatch(items: items), entityPositions: links)+    }++    static func metadata() throws -> MCPResultMetadata {+        try MCPResultMetadata.make(document: MCPJSONDocument.parse(+            #"{"example.test/request":{"n":1E+9999,"explicitNull":null}}"#))+    }++    static func field(_ name: String, in value: MCPJSONValue?) -> MCPJSONValue? {+        guard case .object(let members) = value else { return nil }+        return members.first { $0.name == name }?.value+    }++    static func result(_ bytes: Data) throws -> MCPJSONValue {+        let document = try MCPJSONDocument.parse(bytes)+        return try #require(field("result", in: document.value))+    }++    static func reconciliation(_ selected: MCPResultResponseSelection) throws -> Data {+        guard case .reconciliation(let bytes) = selected else {+            Issue.record("Expected ready reconciliation bytes after synthetic effect failure")+            throw MCPResultBoundaryError.unsupportedEvidence+        }+        return bytes+    }++    static func aggregate(original: String, itemID: String = "caller-item", itemIsError: Bool? = nil) throws -> String {+        let quotedText = try #require(String(data: JSONEncoder().encode(original), encoding: .utf8))+        let flag = itemIsError.map { ",\"isError\":\($0)" } ?? ""+        return """+        {"contractVersion":1,"mode":"execute","atomicity":"per_item","summary":"all_committed",\+        "items":[{"index":0,"itemId":"\(itemID)",\+        "originalResult":{"payload":\(original),"text":\(quotedText)\(flag)}}]}+        """+    }++    static func nestedArrays(_ count: Int) -> String {+        String(repeating: "[", count: count) + "0" + String(repeating: "]", count: count)+    }+}++/// Mutex-backed counters can be used by actual @Sendable common checkpoints.+nonisolated final class MCPBatchTaskEncodingCounts: Sendable {+    nonisolated struct Snapshot: Sendable {+        var prepare = 0+        var dispatch = 0+        var encode = 0+        var prepared: Data?+        var events: [String] = []+    }+    private let state = Mutex(Snapshot())++    func record(_ stage: String, prepared: Data? = nil) {+        state.withLock {+            if stage == "prepare" { $0.prepare += 1 }+            if stage == "dispatch" { $0.dispatch += 1 }+            if stage == "encode" { $0.encode += 1 }+            if let prepared { $0.prepared = prepared }+            $0.events.append(stage)+        }+    }++    func snapshot() -> Snapshot { state.withLock { $0 } }+}+#endif
Transit/TransitTests/MCPBatchTaskSafetyFixture.swift Added +199 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskSafetyFixture.swift b/Transit/TransitTests/MCPBatchTaskSafetyFixture.swiftnew file mode 100644index 00000000..ef54e28f--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskSafetyFixture.swift@@ -0,0 +1,199 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++/// Owns disk storage, UI context and retry directory for the batch safety suite.+/// Production guard files are never opened by these fixtures.+@MainActor final class MCPBatchTaskSafetyFixture {+    enum Fault: Error { case injected }++    let directory: URL+    let storeURL: URL+    let owner: TestModelContainer+    let services: MCPWriteCommandServices+    let project: Project+    let target: TransitTask+    let pendingDeletion: TransitTask+    let clock = Date(timeIntervalSince1970: 1_800_000_000)+    var coordinator: MCPWriteCoordinator!+    var saves: [MCPWriteCoordinator.SaveStage] = []+    var recoveryCalls = 0+    var identityCalls = 0+    var failingStage: MCPWriteCoordinator.SaveStage?+    private var pendingReceiptEvidence: [UUID: String]?++    init() throws {+        directory = FileManager.default.temporaryDirectory+            .appendingPathComponent("T2384BatchSafety-" + UUID().uuidString)+        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+        print("T2384_BATCH_SAFETY_DIRECTORY=" + directory.path)+        storeURL = directory.appendingPathComponent("safety.store")+        owner = try Self.diskOwner(at: storeURL)+        project = Project(name: "Saved project", description: "", gitRepo: nil, colorHex: "#112233")+        target = TransitTask(name: "Saved target", type: .feature, project: project, displayID: .permanent(1))+        pendingDeletion = TransitTask(+            name: "Saved deletion", type: .feature, project: project, displayID: .permanent(2))+        owner.context.insert(project)+        owner.context.insert(target)+        owner.context.insert(pendingDeletion)+        try owner.context.save()+        let allocator = DisplayIDAllocator(store: InMemoryCounterStore(), isCloudSyncActive: false)+        services = MCPWriteCommandServices(+            tasks: TaskService(modelContext: owner.context, displayIDAllocator: allocator),+            projects: ProjectService(modelContext: owner.context),+            comments: CommentService(modelContext: owner.context),+            milestones: MilestoneService(modelContext: owner.context, displayIDAllocator: allocator),+            context: owner.context)+        installCoordinator()+    }++    static func diskOwner(at url: URL) throws -> TestModelContainer {+        let schema = Schema([Project.self, TransitTask.self, Comment.self, Milestone.self,+                             SyncHeartbeat.self, MCPWriteReceipt.self])+        let configuration = ModelConfiguration(schema: schema, url: url, cloudKitDatabase: .none)+        let result = try TestModelContainer(schema: schema, configurations: [configuration])+        result.context.autosaveEnabled = false+        return result+    }++    func installCoordinator(+        preparation: @escaping @MainActor (MCPWriteCommand) async throws -> Void = { _ in }+    ) {+        coordinator = nil+        let fixedClock = clock+        coordinator = MCPWriteCoordinator(+            services: services, sidecarDirectory: directory.appendingPathComponent("retry"),+            persistence: PersistenceAvailability(), clock: { fixedClock },+            save: { [weak self] context, stage in+                guard let self else { throw Fault.injected }+                saves.append(stage)+                if stage == failingStage { throw Fault.injected }+                try context.save()+            }, preparationHook: preparation,+            recoveryHook: { [weak self] in self?.recoveryCalls += 1 })+    }++    func arguments(key: String = "item", name: String = "Committed target") throws -> [String: Any] {+        ["taskId": target.id.uuidString, "name": name, "idempotencyKey": key,+         "expectedRevision": try MCPRecordSnapshot.task(target, in: owner.context).revision]+    }++    // RED seam: the optional batch policy and saved-context factory are task 2+    // interfaces, not substitutes for T2383's still-undelivered result API.+    func policy(fetchFailure: Bool = false) -> MCPBatchWritePolicy {+        MCPBatchWritePolicy(validateBeforeApply: { [weak self] command, context in+            guard let self else { throw Fault.injected }+            identityCalls += 1+            if fetchFailure { throw Fault.injected }+            try MCPBatchWritePolicy().validateBeforeApply(command, context)+        })+    }++    func execute(_ arguments: [String: Any], fetchFailure: Bool = false) async -> MCPToolResult {+        await coordinator.execute(tool: "update_task", arguments: arguments,+                                  batchPolicy: policy(fetchFailure: fetchFailure))+    }++    func decode(_ result: MCPToolResult) throws -> [String: Any] {+        let text = try #require(result.content.first?.text)+        return try #require(JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any])+    }++    func receipt(key: String = "item") throws -> MCPWriteReceipt {+        try #require(owner.context.fetch(FetchDescriptor<MCPWriteReceipt>()).first { $0.key == key })+    }++    func guardFiles() throws -> [URL] {+        try FileManager.default.contentsOfDirectory(+            at: directory.appendingPathComponent("retry/guards"), includingPropertiesForKeys: nil)+            .filter { $0.pathExtension == "json" }.sorted { $0.path < $1.path }+    }++    func guardBytes() throws -> [String: Data] {+        // Include modification time: rewriting identical expiry bytes is also+        // forbidden, so byte equality alone cannot prove read-only replay.+        try Dictionary(uniqueKeysWithValues: guardFiles().map { file in+            var evidence = try Data(contentsOf: file)+            let modified = try file.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate+            evidence.append(Data(String(reflecting: modified).utf8))+            return (file.lastPathComponent, evidence)+        })+    }++    func durableReceiptEvidence() throws -> [UUID: String] {+        let durableOwner = try Self.diskOwner(at: storeURL)+        return try Dictionary(uniqueKeysWithValues:+            durableOwner.context.fetch(FetchDescriptor<MCPWriteReceipt>()).map { receipt in+                let fields: [String] = [+                    receipt.localScopeID, receipt.tool, receipt.key, String(receipt.formatVersion),+                    receipt.requestJSON, receipt.stateRawValue, String(reflecting: receipt.acceptedAt),+                    String(reflecting: receipt.completedAt), String(reflecting: receipt.expiresAt),+                    String(reflecting: receipt.resultJSON), String(reflecting: receipt.resultIsError)+                ]+                return (receipt.id, String(reflecting: fields))+            })+    }++    func makePendingEdits() throws -> TransitTask {+        pendingReceiptEvidence = try durableReceiptEvidence()+        target.name = "UI unsaved edit"+        owner.context.delete(pendingDeletion)+        let inserted = TransitTask(name: "UI unsaved insert", type: .feature,+                                   project: project, displayID: .permanent(3))+        owner.context.insert(inserted)+        return inserted+    }++    func assertPendingPreserved(+        _ inserted: TransitTask, savedTargetName: String, expectedAutosave: Bool = false+    ) throws {+        #expect(try durableReceiptEvidence() == #require(pendingReceiptEvidence))+        #expect(owner.context.hasChanges)+        #expect(owner.context.autosaveEnabled == expectedAutosave)+        #expect(target.name == "UI unsaved edit")+        #expect(owner.context.insertedModelsArray.contains { $0.persistentModelID == inserted.persistentModelID })+        #expect(owner.context.deletedModelsArray.contains {+            $0.persistentModelID == pendingDeletion.persistentModelID+        })+        let durableOwner = try Self.diskOwner(at: storeURL)+        let durable = try durableOwner.context.fetch(FetchDescriptor<TransitTask>())+        #expect(durable.first { $0.id == target.id }?.name == savedTargetName)+        #expect(durable.contains { $0.id == pendingDeletion.id })+        #expect(!durable.contains { $0.id == inserted.id })+    }++    func resetSpies() {+        saves = []+        recoveryCalls = 0+        identityCalls = 0+    }+}++/// Bounded wait avoids wedging the suite if admission/preparation changes.+actor MCPBatchSafetyPreparationGate {+    private var started = false+    private var released = false+    private var continuation: CheckedContinuation<Void, Never>?++    func park() async {+        started = true+        if !released { await withCheckedContinuation { continuation = $0 } }+    }++    func waitForStart() async -> Bool {+        let deadline = ContinuousClock.now + .seconds(10)+        while !started && ContinuousClock.now < deadline {+            try? await Task.sleep(for: .milliseconds(5))+        }+        return started+    }++    func release() {+        released = true+        continuation?.resume()+        continuation = nil+    }+}+#endif
Transit/TransitTests/MCPBatchTaskSafetyTests.swift Added +316 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskSafetyTests.swift b/Transit/TransitTests/MCPBatchTaskSafetyTests.swiftnew file mode 100644index 00000000..d45680c3--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskSafetyTests.swift@@ -0,0 +1,316 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPBatchTaskSafetyTests {+    @Test(arguments: [false, true], [false, true])+    func savedObservationPreservesPendingInsertEditDelete(fetchFails: Bool, sharedAutosave: Bool) throws {+        let fixture = try MCPBatchTaskSafetyFixture()+        // Synchronous only: no run-loop suspension may independently autosave.+        fixture.owner.context.autosaveEnabled = sharedAutosave+        let inserted = try fixture.makePendingEdits()+        let guards = try fixture.guardBytes()+        let persistence = PersistenceAvailability()+        do {+            try MCPBatchSavedReadContext.withContext(+                container: fixture.owner.container, persistence: persistence+            ) { (context: ModelContext) in+                #expect(context !== fixture.owner.context)+                #expect(!context.autosaveEnabled)+                #expect(fixture.owner.context.autosaveEnabled == sharedAutosave)+                if fetchFails { throw MCPBatchTaskSafetyFixture.Fault.injected }+                var descriptor = FetchDescriptor<TransitTask>()+                descriptor.includePendingChanges = false+                let tasks = try context.fetch(descriptor)+                #expect(tasks.first { $0.id == fixture.target.id }?.name == "Saved target")+                #expect(tasks.contains { $0.id == fixture.pendingDeletion.id })+                #expect(!tasks.contains { $0.id == inserted.id })+            }+            #expect(!fetchFails)+        } catch { #expect(fetchFails) }+        try fixture.assertPendingPreserved(+            inserted, savedTargetName: "Saved target", expectedAutosave: sharedAutosave)+        #expect(try fixture.guardBytes() == guards)+        #expect(try fixture.owner.context.fetch(FetchDescriptor<MCPWriteReceipt>()).isEmpty)+        #expect(fixture.saves.isEmpty && fixture.recoveryCalls == 0)+    }++    @Test func fallbackStorageNeverSuppliesSavedEvidence() throws {+        let owner = try TestModelContainer()+        var called = false+        #expect(throws: (any Error).self) {+            try MCPBatchSavedReadContext.withContext(+                container: owner.container, persistence: PersistenceAvailability(isFallbackStorageActive: true)+            ) { _ in called = true }+        }+        #expect(!called)+    }+}++extension MCPBatchTaskSafetyTests {+    @Test(arguments: [false, true])+    func dirtyTerminalReplayPreservesOriginalBytes(rejected: Bool) async throws {+        let fixture = try MCPBatchTaskSafetyFixture()+        let args = try fixture.arguments(name: rejected ? "" : "Committed target")+        let first = await fixture.execute(args)+        #expect(try fixture.decode(first)["outcome"] as? String == (rejected ? "rejected" : "committed"))+        let receipt = try fixture.receipt()+        let receiptText = receipt.resultJSON+        let completion = receipt.completedAt+        let expiry = receipt.expiresAt+        let guards = try fixture.guardBytes()+        let inserted = try fixture.makePendingEdits()+        fixture.resetSpies()+        let replay = await fixture.execute(args)+        #expect(replay.content.first?.text == first.content.first?.text)+        #expect(replay.isError == first.isError)+        #expect(receipt.resultJSON == receiptText && receipt.completedAt == completion && receipt.expiresAt == expiry)+        #expect(try fixture.guardBytes() == guards)+        #expect(fixture.saves.isEmpty && fixture.recoveryCalls == 0 && fixture.identityCalls == 0)+        try fixture.assertPendingPreserved(inserted, savedTargetName: rejected ? "Saved target" : "Committed target")+    }++    @Test(arguments: [false, true])+    func dirtyPayloadMismatchChecksRetainedBindingBeforeLiveIdentity(malformedReceipt: Bool) async throws {+        let fixture = try MCPBatchTaskSafetyFixture()+        var args = try fixture.arguments()+        _ = await fixture.execute(args)+        if malformedReceipt {+            try fixture.receipt().resultJSON = "{unreadable"+            try fixture.owner.context.save()+        }+        let guards = try fixture.guardBytes()+        let inserted = try fixture.makePendingEdits()+        args["name"] = "Changed arguments"+        fixture.resetSpies()+        let result = try fixture.decode(await fixture.execute(args, fetchFailure: true))+        #expect((result["error"] as? [String: Any])?["code"] as? String == "IDEMPOTENCY_KEY_REUSED")+        #expect(fixture.saves.isEmpty && fixture.recoveryCalls == 0 && fixture.identityCalls == 0)+        #expect(try fixture.guardBytes() == guards)+        try fixture.assertPendingPreserved(inserted, savedTargetName: "Committed target")+    }++    @Test(arguments: [false, true])+    func dirtyMissingOrInconsistentSidecarDoesNotRepair(inconsistent: Bool) async throws {+        let fixture = try MCPBatchTaskSafetyFixture()+        let args = try fixture.arguments()+        let first = await fixture.execute(args)+        let file = try #require(fixture.guardFiles().first)+        if inconsistent {+            var binding = try JSONDecoder().decode(MCPLocalReservation.self, from: Data(contentsOf: file))+            binding.receiptID = UUID()+            try JSONEncoder().encode(binding).write(to: file)+        } else { try FileManager.default.removeItem(at: file) }+        let guards = try fixture.guardBytes()+        let inserted = try fixture.makePendingEdits()+        fixture.resetSpies()+        let result = await fixture.execute(args)+        if inconsistent {+            #expect(try fixture.decode(result)["outcome"] as? String == "uncertain")+        } else { #expect(result.content.first?.text == first.content.first?.text) }+        #expect(try fixture.guardBytes() == guards)+        #expect(fixture.saves.isEmpty && fixture.recoveryCalls == 0 && fixture.identityCalls == 0)+        try fixture.assertPendingPreserved(inserted, savedTargetName: "Committed target")+    }++    @Test(arguments: ["new", "missing", "expired", "unresolved", "malformed"])+    func dirtyUnestablishedEvidenceStopsWithoutRecovery(kind: String) async throws {+        let fixture = try MCPBatchTaskSafetyFixture()+        let args = try fixture.arguments()+        if kind != "new" {+            _ = await fixture.execute(args)+            let receipt = try fixture.receipt()+            if kind == "missing" { fixture.owner.context.delete(receipt) }+            if kind == "expired" {+                let file = try #require(fixture.guardFiles().first)+                var binding = try JSONDecoder().decode(MCPLocalReservation.self, from: Data(contentsOf: file))+                binding.expiresAt = fixture.clock.addingTimeInterval(-1)+                try JSONEncoder().encode(binding).write(to: file)+                fixture.owner.context.delete(receipt)+            }+            if kind == "unresolved" {+                receipt.stateRawValue = "accepted"+                receipt.resultJSON = nil+                receipt.resultIsError = nil+                receipt.completedAt = nil+                receipt.expiresAt = nil+                let file = try #require(fixture.guardFiles().first)+                var binding = try JSONDecoder().decode(MCPLocalReservation.self, from: Data(contentsOf: file))+                binding.expiresAt = nil+                try JSONEncoder().encode(binding).write(to: file)+            }+            if kind == "malformed" { receipt.resultJSON = "{unreadable" }+            try fixture.owner.context.save()+        }+        let guards = try fixture.guardBytes()+        let inserted = try fixture.makePendingEdits()+        fixture.resetSpies()+        let result = try fixture.decode(await fixture.execute(args))+        #expect(result["outcome"] as? String == "uncertain")+        #expect(result["retryAction"] as? String == "reconcile")+        #expect(try fixture.guardBytes() == guards)+        #expect(fixture.saves.isEmpty && fixture.recoveryCalls == 0 && fixture.identityCalls == 0)+        try fixture.assertPendingPreserved(+            inserted, savedTargetName: kind == "new" ? "Saved target" : "Committed target")+    }++    @Test(arguments: ["success", "error", "cancelled"])+    func editsDuringPreparationPreserveAcceptedBinding(continuation: String) async throws {+        let fixture = try MCPBatchTaskSafetyFixture()+        let gate = MCPBatchSafetyPreparationGate()+        fixture.installCoordinator(preparation: { _ in+            await gate.park()+            if continuation == "error" { throw MCPBatchTaskSafetyFixture.Fault.injected }+        })+        let args = try fixture.arguments()+        let running = Task { await fixture.execute(args) }+        guard await gate.waitForStart() else {+            await gate.release()+            _ = await running.value+            Issue.record("Expected accepted preparation to suspend")+            return+        }+        let guards = try fixture.guardBytes()+        let inserted = try fixture.makePendingEdits()+        fixture.resetSpies()+        if continuation == "cancelled" { running.cancel() }+        await gate.release()+        let result = try fixture.decode(await running.value)+        #expect(result["outcome"] as? String == "uncertain")+        #expect(result["accepted"] as? Bool == true)+        #expect(result["retryAction"] as? String == "reconcile")+        #expect(try fixture.guardBytes() == guards)+        #expect(fixture.saves.isEmpty && fixture.recoveryCalls == 0 && fixture.identityCalls == 0)+        try fixture.assertPendingPreserved(inserted, savedTargetName: "Saved target")+        let durableOwner = try MCPBatchTaskSafetyFixture.diskOwner(at: fixture.storeURL)+        let receipt = try #require(durableOwner.context.fetch(FetchDescriptor<MCPWriteReceipt>()).first)+        #expect(receipt.stateRawValue == "accepted" && receipt.resultJSON == nil)+    }++    @Test func activeKeyResponseDoesNotFlushConcurrentUIEdits() async throws {+        let fixture = try MCPBatchTaskSafetyFixture()+        let gate = MCPBatchSafetyPreparationGate()+        fixture.installCoordinator(preparation: { _ in await gate.park() })+        let args = try fixture.arguments()+        let running = Task { await fixture.execute(args) }+        guard await gate.waitForStart() else {+            await gate.release()+            _ = await running.value+            Issue.record("Expected active key")+            return+        }+        let inserted = try fixture.makePendingEdits()+        let guards = try fixture.guardBytes()+        fixture.resetSpies()+        let active = try fixture.decode(await fixture.execute(args))+        #expect(active["outcome"] as? String == "in_progress")+        var different = args+        different["name"] = "Different"+        let mismatch = try fixture.decode(await fixture.execute(different))+        #expect((mismatch["error"] as? [String: Any])?["code"] as? String == "IDEMPOTENCY_KEY_REUSED")+        await gate.release()+        #expect(try fixture.decode(await running.value)["outcome"] as? String == "uncertain")+        #expect(fixture.saves.isEmpty && fixture.recoveryCalls == 0 && fixture.identityCalls == 0)+        #expect(try fixture.guardBytes() == guards)+        try fixture.assertPendingPreserved(inserted, savedTargetName: "Saved target")+    }++    @Test(arguments: ["missing", "duplicate", "fetchFailure"])+    func preApplyIdentityRejectsNewEffectsAfterPreparation(kind: String) async throws {+        let fixture = try MCPBatchTaskSafetyFixture()+        let args = try fixture.arguments()+        fixture.installCoordinator(preparation: { [weak fixture] _ in+            guard let fixture else { throw MCPBatchTaskSafetyFixture.Fault.injected }+            if kind == "missing" { fixture.owner.context.delete(fixture.target) }+            if kind == "duplicate" {+                let duplicate = TransitTask(name: "UUID collision", type: .feature,+                                            project: fixture.project, displayID: .permanent(4))+                duplicate.id = fixture.target.id+                fixture.owner.context.insert(duplicate)+            }+            // A peer save precedes the fresh synchronous phase; it is not an+            // impossible UI interleaving inside that phase.+            try fixture.owner.context.save()+        })+        let result = try fixture.decode(await fixture.execute(args, fetchFailure: kind == "fetchFailure"))+        #expect(result["outcome"] as? String == "rejected")+        let code = (result["error"] as? [String: Any])?["code"] as? String+        #expect(code == (kind == "missing" ? "TASK_NOT_FOUND" :+            kind == "duplicate" ? "DUPLICATE_TASK_IDENTIFIER" : "INTERNAL_ERROR"))+        // Missing before preparation is rejected by the original resolver;+        // ambiguity and injected callback failure reach the fresh apply gate.+        #expect(fixture.identityCalls == (kind == "missing" ? 0 : 1))+        let durableOwner = try MCPBatchTaskSafetyFixture.diskOwner(at: fixture.storeURL)+        #expect(try durableOwner.context.fetch(FetchDescriptor<TransitTask>()).allSatisfy {+            $0.name != "Committed target"+        })+    }++    @Test func defaultPreApplyPolicyRejectsMissingSavedIdentity() throws {+        let fixture = try MCPBatchTaskSafetyFixture()+        let command = try MCPWriteCommand.validate(tool: "update_task", arguments: fixture.arguments())+        fixture.owner.context.delete(fixture.target)+        try fixture.owner.context.save()+        do {+            try fixture.policy().validateBeforeApply(command, fixture.owner.context)+            Issue.record("Missing UUID must fail the fresh synchronous callback")+        } catch let failure as MCPWriteFailure {+            #expect(failure.code == "TASK_NOT_FOUND")+        }+        #expect(fixture.identityCalls == 1)+        #expect(fixture.saves.isEmpty && fixture.recoveryCalls == 0)+    }++    @Test(arguments: [false, true])+    func historicalReplayBypassesDeletedOrAmbiguousTarget(duplicate: Bool) async throws {+        let fixture = try MCPBatchTaskSafetyFixture()+        let args = try fixture.arguments()+        let first = await fixture.execute(args)+        if duplicate {+            let collision = TransitTask(name: "Collision", type: .feature,+                                        project: fixture.project, displayID: .permanent(4))+            collision.id = fixture.target.id+            fixture.owner.context.insert(collision)+        } else { fixture.owner.context.delete(fixture.target) }+        try fixture.owner.context.save()+        fixture.resetSpies()+        let replay = await fixture.execute(args, fetchFailure: true)+        #expect(replay.content.first?.text == first.content.first?.text && replay.isError == first.isError)+        #expect(fixture.identityCalls == 0)+    }++    @Test(arguments: ["acceptance", "commit", "rejection"])+    func cleanPhaseFaultsRollbackOnlyTheirOwnStagedChanges(stage: String) async throws {+        let fixture = try MCPBatchTaskSafetyFixture()+        fixture.failingStage = stage == "acceptance" ? .acceptance : stage == "commit" ? .commit : .rejection+        let args = try fixture.arguments(name: stage == "rejection" ? "" : "Committed target")+        let result = try fixture.decode(await fixture.execute(args))+        #expect(result["outcome"] as? String != "committed")+        let durableOwner = try MCPBatchTaskSafetyFixture.diskOwner(at: fixture.storeURL)+        #expect(try durableOwner.context.fetch(FetchDescriptor<TransitTask>()).first {+            $0.id == fixture.target.id+        }?.name == "Saved target")+        // Subsequent UI work must not accidentally persist a failed domain edit.+        fixture.project.name = "Later independently saved UI work"+        try fixture.owner.context.save()+        let afterUI = try MCPBatchTaskSafetyFixture.diskOwner(at: fixture.storeURL)+        #expect(try afterUI.context.fetch(FetchDescriptor<TransitTask>()).first {+            $0.id == fixture.target.id+        }?.name == "Saved target")+    }++    @Test func standaloneNilPolicyRetainsExistingPendingBaselineBehavior() async throws {+        let fixture = try MCPBatchTaskSafetyFixture()+        let args = try fixture.arguments()+        fixture.project.name = "Standalone pending baseline"+        let result = try fixture.decode(await fixture.coordinator.execute(tool: "update_task", arguments: args))+        #expect(result["outcome"] as? String == "committed")+        let durableOwner = try MCPBatchTaskSafetyFixture.diskOwner(at: fixture.storeURL)+        #expect(try durableOwner.context.fetch(FetchDescriptor<Project>()).first?.name == "Standalone pending baseline")+        #expect(fixture.identityCalls == 0)+    }+}+#endif
Transit/TransitTests/MCPBatchTaskSchemaTests.swift Added +142 / -0
diff --git a/Transit/TransitTests/MCPBatchTaskSchemaTests.swift b/Transit/TransitTests/MCPBatchTaskSchemaTests.swiftnew file mode 100644index 00000000..3993579c--- /dev/null+++ b/Transit/TransitTests/MCPBatchTaskSchemaTests.swift@@ -0,0 +1,142 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPBatchTaskSchemaTests {+    private typealias Fixture = MCPBatchTaskRequestFixtures++    @Test func wholeRequestSchemaRequiresExplicitModeAndBoundedClosedItems() throws {+        let schema = try MCPBatchTaskSchema.inputSchema().value+        #expect(Fixture.field("type", in: schema) == .string("object"))+        #expect(Fixture.field("additionalProperties", in: schema) == .boolean(false))+        #expect(try Fixture.names(Fixture.field("required", in: schema)) == ["mode", "items"])+        let properties = Fixture.field("properties", in: schema)+        let mode = Fixture.field("mode", in: properties)+        #expect(Fixture.field("type", in: mode) == .string("string"))+        #expect(try Fixture.names(Fixture.field("enum", in: mode)) == ["dry_run", "execute"])+        let items = Fixture.field("items", in: properties)+        #expect(Fixture.field("type", in: items) == .string("array"))+        #expect(number(Fixture.field("minItems", in: items)) == "1")+        #expect(number(Fixture.field("maxItems", in: items)) == "50")+        #expect(try Fixture.array(Fixture.field("oneOf", in: Fixture.field("items", in: items))).count == 3)+        #expect(Fixture.field("idempotencyKey", in: properties) == nil)+        #expect(Fixture.field("batchId", in: properties) == nil)+    }++    @Test(arguments: ["update_task", "update_task_status", "add_comment"])+    func conditionalOperationBranchesPublishClosedTypedSafetyShapes(operation: String) throws {+        let branch = try branch(operation)+        #expect(Fixture.field("type", in: branch) == .string("object"))+        #expect(Fixture.field("additionalProperties", in: branch) == .boolean(false))+        #expect(try Fixture.names(Fixture.field("required", in: branch)) == ["itemId", "operation", "arguments"])+        let properties = Fixture.field("properties", in: branch)+        let itemId = Fixture.field("itemId", in: properties)+        #expect(Fixture.field("type", in: itemId) == .string("string"))+        #expect(number(Fixture.field("minLength", in: itemId)) == "1")+        #expect(Fixture.field("const", in: Fixture.field("operation", in: properties)) == .string(operation))+        let arguments = Fixture.field("arguments", in: properties)+        #expect(Fixture.field("type", in: arguments) == .string("object"))+        #expect(Fixture.field("additionalProperties", in: arguments) == .boolean(false))+        let required = try Fixture.names(Fixture.field("required", in: arguments))+        #expect(required.contains("taskId") && required.contains("idempotencyKey"))+        let fields = Fixture.field("properties", in: arguments)+        let taskId = Fixture.field("taskId", in: fields)+        #expect(Fixture.field("type", in: taskId) == .string("string"))+        #expect(Fixture.field("format", in: taskId) == .string("uuid"))+        assertExactArguments(operation: operation, fields: fields, required: required)+        #expect(Fixture.field("displayId", in: fields) == nil)+        let key = Fixture.field("idempotencyKey", in: fields)+        #expect(Fixture.field("type", in: key) == .string("string"))+        #expect(Fixture.field("pattern", in: key) == .string("^[A-Za-z0-9._:-]{1,128}$"))+        if operation == "add_comment" {+            #expect(required == ["taskId", "idempotencyKey", "content", "authorName"])+            #expect(Fixture.field("expectedRevision", in: fields) == nil)+        } else {+            #expect(required.contains("expectedRevision"))+            let revision = Fixture.field("expectedRevision", in: fields)+            #expect(Fixture.field("pattern", in: revision) == .string("^r1:[0-9a-f]{64}$"))+            if operation == "update_task_status" {+                #expect(required.contains("status") && !required.contains("authorName"))+            }+        }+    }++    @Test func domainStringsDescribeValuesWithoutWholeShapeEnumOrAuthorConstraints() throws {+        for operation in ["update_task", "update_task_status"] {+            let item = try branch(operation)+            let arguments = Fixture.field("arguments", in: Fixture.field("properties", in: item))+            let fields = Fixture.field("properties", in: arguments)+            for name in operation == "update_task" ? ["type", "priority"] : ["status"] {+                let domain = try #require(Fixture.field(name, in: fields))+                #expect(Fixture.field("type", in: domain) == .string("string"))+                #expect(Fixture.field("enum", in: domain) == nil && Fixture.field("const", in: domain) == nil)+                guard case .string(let description) = Fixture.field("description", in: domain) else {+                    Issue.record("Domain descriptions must explain supported values"); continue+                }+                let allowed: [String]+                switch name {+                case "type": allowed = TaskType.allCases.map(\.rawValue)+                case "priority": allowed = TaskPriority.allCases.map(\.rawValue)+                default: allowed = TaskStatus.allCases.map(\.rawValue)+                }+                #expect(allowed.allSatisfy { description.contains($0) })+            }+            #expect(Fixture.field("if", in: arguments) == nil && Fixture.field("then", in: arguments) == nil)+            #expect(Fixture.field("dependentRequired", in: arguments) == nil)+            if operation == "update_task" {+                let metadata = Fixture.field("metadata", in: fields)+                #expect(Fixture.field("type", in: metadata) == .string("object"))+                let values = Fixture.field("additionalProperties", in: metadata)+                #expect(Fixture.field("type", in: values) == .string("string"))+                #expect(Fixture.field("type", in: Fixture.field("clearMilestone", in: fields)) == .string("boolean"))+                let milestoneId = Fixture.field("milestoneDisplayId", in: fields)+                #expect(Fixture.field("type", in: milestoneId) == .string("integer"))+            }+        }+    }++    private func assertExactArguments(operation: String, fields: MCPJSONValue?, required: Set<String>) {+        let common: Set<String> = ["taskId", "idempotencyKey"]+        let expectedFields: Set<String>+        let expectedRequired: Set<String>+        switch operation {+        case "update_task":+            expectedFields = common.union(["expectedRevision", "name", "description", "type", "priority",+                                           "metadata", "milestone", "milestoneDisplayId", "clearMilestone"])+            expectedRequired = common.union(["expectedRevision"])+        case "update_task_status":+            expectedFields = common.union(["expectedRevision", "status", "comment", "authorName"])+            expectedRequired = common.union(["expectedRevision", "status"])+        default:+            expectedFields = common.union(["content", "authorName"])+            expectedRequired = common.union(["content", "authorName"])+        }+        guard case .object(let members) = fields else {+            Issue.record("Expected exact operation argument properties"); return+        }+        #expect(Set(members.map(\.name)) == expectedFields && required == expectedRequired)+        for field in expectedFields {+            let type = field == "metadata" ? "object" : field == "milestoneDisplayId" ? "integer" :+                field == "clearMilestone" ? "boolean" : "string"+            #expect(Fixture.field("type", in: Fixture.field(field, in: fields)) == .string(type))+        }+    }++    private func branch(_ operation: String) throws -> MCPJSONValue {+        let schema = try MCPBatchTaskSchema.inputSchema().value+        let items = Fixture.field("items", in: Fixture.field("properties", in: schema))+        let choices = try Fixture.array(Fixture.field("oneOf", in: Fixture.field("items", in: items)))+        return try #require(choices.first {+            Fixture.field("const", in: Fixture.field("operation", in: Fixture.field("properties", in: $0))) ==+                .string(operation)+        })+    }++    private func number(_ value: MCPJSONValue?) -> String? {+        guard case .number(let number) = value else { return nil }+        return number.lexeme+    }+}+#endif
Transit/TransitTests/MCPMaintenanceHandlerTests.swift Modified +4 / -4
diff --git a/Transit/TransitTests/MCPMaintenanceHandlerTests.swift b/Transit/TransitTests/MCPMaintenanceHandlerTests.swiftindex 84171506..84663eda 100644--- a/Transit/TransitTests/MCPMaintenanceHandlerTests.swift+++ b/Transit/TransitTests/MCPMaintenanceHandlerTests.swift@@ -21,10 +21,10 @@ struct MCPMaintenanceHandlerTests {         #expect(!names.contains("reassign_duplicate_display_ids"))         // Core tools still present.         #expect(names.contains("create_task"))-        #expect(names.count == 12)+        #expect(names.count == 13)         #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"]))+            "delete_milestone", "query_project_summaries", "mutate_tasks"]))     }      @Test func toolsListWithMaintenanceOnIncludesBothMaintenanceTools() async throws {@@ -36,10 +36,10 @@ struct MCPMaintenanceHandlerTests {          #expect(names.contains("scan_duplicate_display_ids"))         #expect(names.contains("reassign_duplicate_display_ids"))-        #expect(names.count == 14)+        #expect(names.count == 15)         #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"] + [+            "delete_milestone", "query_project_summaries", "mutate_tasks"] + [             "scan_duplicate_display_ids", "reassign_duplicate_display_ids"         ]))     }
Transit/TransitTests/MCPMilestoneToolTests.swift Modified +2 / -2
diff --git a/Transit/TransitTests/MCPMilestoneToolTests.swift b/Transit/TransitTests/MCPMilestoneToolTests.swiftindex 2271ef07..a1590051 100644--- a/Transit/TransitTests/MCPMilestoneToolTests.swift+++ b/Transit/TransitTests/MCPMilestoneToolTests.swift@@ -23,13 +23,13 @@ struct MCPMilestoneToolTests {         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"]))+            "delete_milestone", "query_project_summaries", "mutate_tasks"]))         #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 == 12)+        #expect(tools.count == 13)     }      // MARK: - create_milestone
Transit/TransitTests/MCPModernResultFixture.swift Modified +5 / -1
diff --git a/Transit/TransitTests/MCPModernResultFixture.swift b/Transit/TransitTests/MCPModernResultFixture.swiftindex eee56d3e..701054f7 100644--- a/Transit/TransitTests/MCPModernResultFixture.swift+++ b/Transit/TransitTests/MCPModernResultFixture.swift@@ -28,7 +28,7 @@ import Testing             commentService: env.commentService, milestoneService: env.milestoneService,             maintenanceService: env.maintenanceService, settings: env.mcpSettings,             taskQuerySnapshots: snapshots, writeCoordinator: env.writeCoordinator, readService: service,-            readCoordinator: env.handler.readCoordinator)+            readCoordinator: env.handler.readCoordinator, batchContainer: env.context.container)         return MCPTestEnv(handler: handler, taskService: env.taskService, projectService: env.projectService,             commentService: env.commentService, milestoneService: env.milestoneService,             maintenanceService: env.maintenanceService, mcpSettings: env.mcpSettings, context: env.context,@@ -40,6 +40,10 @@ import Testing                                task: TransitTask, milestone: Milestone) throws -> [String: Any] {         var args: [String: Any] = [:]         switch tool {+        case "mutate_tasks":+            args = ["mode": "dry_run", "items": [["itemId": "modern.smoke", "operation": "update_task",+                "arguments": ["taskId": task.id.uuidString, "idempotencyKey": "modern.batch.smoke",+                    "expectedRevision": try MCPRecordSnapshot.task(task, in: env.context).revision]]]]         case "create_project": args = ["name": "New Project", "colorHex": "#334455"]         case "create_task": args = ["name": "New Task", "type": "feature", "projectId": project.id.uuidString]         case "create_milestone": args = ["name": "New Milestone", "projectId": project.id.uuidString]
Transit/TransitTests/MCPTaskMutationSavedStatusBoundaryTests.swift Added +59 / -0
diff --git a/Transit/TransitTests/MCPTaskMutationSavedStatusBoundaryTests.swift b/Transit/TransitTests/MCPTaskMutationSavedStatusBoundaryTests.swiftnew file mode 100644index 00000000..bb4d93a9--- /dev/null+++ b/Transit/TransitTests/MCPTaskMutationSavedStatusBoundaryTests.swift@@ -0,0 +1,59 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPTaskMutationSavedStatusBoundaryTests {+    @Test+    func unknownSavedStatusUsesServiceIdeaFallback() throws {+        let owner = try TestModelContainer()+        owner.context.autosaveEnabled = false+        let project = Project(name: "Status parity project", description: "", gitRepo: nil, colorHex: "#112233")+        owner.context.insert(project)+        let task = TransitTask(name: "Saved unknown status", type: .feature, project: project, displayID: .provisional)+        task.statusRawValue = "unknown-saved-status"+        let fixed = Date(timeIntervalSince1970: 1_700_000_000)+        task.lastStatusChangeDate = fixed+        task.completionDate = fixed+        owner.context.insert(task)+        try owner.context.save()+        #expect(task.status == .idea)+        let service = TaskService(modelContext: owner.context,+            displayIDAllocator: DisplayIDAllocator(store: InMemoryCounterStore(), isCloudSyncActive: false))+        let comment = try service.updateStatus(task: task, to: .idea, comment: nil, commentAuthor: nil,+            commentService: CommentService(modelContext: owner.context), save: false)+        #expect(comment == nil && task.statusRawValue == "unknown-saved-status")+        #expect(task.lastStatusChangeDate == fixed && task.completionDate == fixed)+        #expect(!owner.context.hasChanges)+        let status = try MCPTaskMutationValidation.status(currentStatus: "unknown-saved-status",+            targetStatus: "idea", comment: nil, authorName: nil)+        #expect(!status.statusChanged)+        #expect(status.lastStatusChange == .unchanged && status.completion == .unchanged)+    }++    @Test(arguments: ["task", "comment"])+    func typedRequiredReadFailuresRemainUnavailable(stage: String) throws {+        let fixture = try MCPBatchTaskPreviewFixture()+        var reads = fixture.reads()+        if stage == "task" {+            reads.tasks = { descriptor, context in+                fixture.observe(context, pending: descriptor.includePendingChanges)+                throw TaskService.Error.taskNotFound+            }+        } else {+            reads.comments = { descriptor, context in+                fixture.observe(context, pending: descriptor.includePendingChanges)+                throw MCPWriteFailure("INVALID_INPUT", "Injected required-read failure")+            }+        }+        let report = try MCPBatchTaskPreview.evaluate(fixture.request([fixture.item()]),+            container: fixture.owner.container, persistence: PersistenceAvailability(), reads: reads)+        #expect(report.entries[0].state == .unavailable)+        #expect(report.entries[0].current == nil && report.entries[0].proposedEffects == nil)+        #expect(report.isError == true)+        try fixture.assertUntouched()+    }+}+#endif
Transit/TransitTests/MCPTaskMutationValidationTests.swift Added +199 / -0
diff --git a/Transit/TransitTests/MCPTaskMutationValidationTests.swift b/Transit/TransitTests/MCPTaskMutationValidationTests.swiftnew file mode 100644index 00000000..de2b7647--- /dev/null+++ b/Transit/TransitTests/MCPTaskMutationValidationTests.swift@@ -0,0 +1,199 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPTaskMutationValidationTests {+    @Test(arguments: [" text ", "\ntext\t", "e\u{301}"])+    func pureCommentNormalization(content: String) throws {+        let normalized = try CommentInputValidation.normalize(content: content, authorName: " Agent \n")+        #expect(normalized.content.utf8.elementsEqual(content.trimmingCharacters(in: .whitespacesAndNewlines).utf8))+        #expect(normalized.authorName == "Agent")+    }++    @Test(arguments: ["content", "author", "both"])+    func pureCommentErrorsRemainDistinct(field: String) {+        do {+            _ = try CommentInputValidation.normalize(content: field == "author" ? "text" : " \n",+                                                       authorName: field == "content" ? "agent" : " \t")+            Issue.record("Blank comment inputs must reject")+        } catch let error as CommentInputValidation.Error {+            #expect(error == (field == "author" ? .emptyAuthorName : .emptyContent))+        } catch { Issue.record("Unexpected comment validation error: \(error)") }+    }++    @Test(arguments: ["same", "done", "abandoned", "leaveTerminal", "terminalToTerminal", "nonterminal"])+    func symbolicStatusTimestampEffects(scenario: String) throws {+        let current: String+        let target: String+        switch scenario {+        case "same": (current, target) = ("idea", "idea")+        case "done": (current, target) = ("idea", "done")+        case "abandoned": (current, target) = ("idea", "abandoned")+        case "leaveTerminal": (current, target) = ("done", "idea")+        case "terminalToTerminal": (current, target) = ("done", "abandoned")+        default: (current, target) = ("idea", "planning")+        }+        let value = try MCPTaskMutationValidation.status(currentStatus: current, targetStatus: target,+                                                        comment: nil, authorName: nil)+        #expect(value.targetStatus == target)+        #expect(value.statusChanged == (current != target))+        #expect(value.comment == nil)+        #expect(value.lastStatusChange == (current == target ? .unchanged : .update))+        let expected: MCPTaskMutationValidation.TimestampAction+        switch scenario {+        case "done", "abandoned", "terminalToTerminal": expected = .set+        case "leaveTerminal": expected = .clear+        default: expected = .unchanged+        }+        #expect(value.completion == expected)+    }++    @Test(arguments: ["absent", "blank", "content"])+    func sameStatusCommentSemantics(scenario: String) throws {+        let comment: String?+        switch scenario {+        case "absent": comment = nil+        case "blank": comment = " \n"+        default: comment = " Reason \n"+        }+        let value = try MCPTaskMutationValidation.status(currentStatus: "idea", targetStatus: "idea",+                                                        comment: comment, authorName: " Agent ")+        #expect(!value.statusChanged && value.lastStatusChange == .unchanged && value.completion == .unchanged)+        #expect(value.comment?.content == (scenario == "content" ? "Reason" : nil))+        #expect(value.comment?.authorName == (scenario == "content" ? "Agent" : nil))+    }++    @Test(arguments: ["invalidStatus", "blankCommentMissingAuthor", "blankCommentBlankAuthor", "contentMissingAuthor"])+    func protectedStatusValidationOrder(scenario: String) {+        let status = scenario == "invalidStatus" ? "unsupported" : "idea"+        let content = scenario == "contentMissingAuthor" ? "reason" : " \n"+        do {+            _ = try MCPTaskMutationValidation.status(currentStatus: "idea", targetStatus: status,+                comment: content, authorName: scenario == "blankCommentBlankAuthor" ? " \t" : nil)+            Issue.record("Protected status input must reject")+        } catch let error as MCPWriteFailure {+            #expect(error.code == (scenario == "invalidStatus" ? "INVALID_STATUS" : "INVALID_INPUT"))+        } catch { Issue.record("Unexpected protected validation error: \(error)") }+    }++    @Test+    func absentCommentIgnoresUnusedBlankAuthor() throws {+        let value = try MCPTaskMutationValidation.status(currentStatus: "idea", targetStatus: "idea",+                                                        comment: nil, authorName: " \n")+        #expect(value.comment == nil && !value.statusChanged)+    }+}++/// Existing-service controls run independently of the new RED placeholders.+@MainActor @Suite(.serialized)+struct MCPTaskMutationBaselineTests {+    @Test(arguments: ["invalidFirst", "blankMissingAuthor", "blankValidAuthor", "absentComment"])+    func existingProtectedStatusContract(scenario: String) throws {+        let fixture = try MCPBatchTaskPreviewFixture()+        let allocator = DisplayIDAllocator(store: InMemoryCounterStore(), isCloudSyncActive: false)+        var saves = 0+        let services = MCPWriteCommandServices(+            tasks: TaskService(modelContext: fixture.owner.context, displayIDAllocator: allocator,+                statusSave: { _ in saves += 1; throw MCPBatchTaskPreviewFixture.Fault.injected }),+            projects: ProjectService(modelContext: fixture.owner.context),+            comments: CommentService(modelContext: fixture.owner.context),+            milestones: MilestoneService(modelContext: fixture.owner.context, displayIDAllocator: allocator),+            context: fixture.owner.context)+        var arguments: [String: Any] = ["taskId": fixture.targets[0].id.uuidString,+            "idempotencyKey": "baseline", "expectedRevision": try fixture.revision(),+            "status": scenario == "invalidFirst" ? "unsupported" : "idea"]+        if scenario != "absentComment" { arguments["comment"] = " \n" }+        if scenario == "blankValidAuthor" { arguments["authorName"] = " Agent " }+        do {+            let command = try MCPWriteCommand.validate(tool: "update_task_status", arguments: arguments)+            let result = try command.apply(.task(fixture.targets[0].id), using: services)+            #expect(scenario == "blankValidAuthor" || scenario == "absentComment")+            #expect(result["comment"] is NSNull)+        } catch let error as MCPWriteFailure {+            #expect(error.code == (scenario == "invalidFirst" ? "INVALID_STATUS" : "INVALID_INPUT"))+            #expect(scenario == "invalidFirst" || scenario == "blankMissingAuthor")+        }+        #expect(saves == 0 && !fixture.owner.context.hasChanges)+        try fixture.assertUntouched()+    }++    @Test(arguments: ["trim", "blankContent", "blankAuthor"])+    func existingCommentServiceContract(scenario: String) throws {+        let fixture = try MCPBatchTaskPreviewFixture()+        let service = CommentService(modelContext: fixture.owner.context)+        do {+            let comment = try service.addComment(to: fixture.targets[0],+                content: scenario == "blankContent" ? " \n" : " Reason ",+                authorName: scenario == "blankAuthor" ? " \t" : " Agent ", isAgent: true, save: nil)+            #expect(scenario == "trim")+            #expect(comment.content == "Reason" && comment.authorName == "Agent" && comment.isAgent)+        } catch let error as CommentService.Error {+            #expect(error == (scenario == "blankContent" ? .emptyContent : .emptyAuthorName))+            #expect(scenario != "trim")+        }+    }++    @Test(arguments: ["same", "terminal", "leaveTerminal", "nonterminalPreservesMalformedCompletion"])+    func existingStatusServiceContract(scenario: String) throws {+        let fixture = try MCPBatchTaskPreviewFixture()+        let task = fixture.targets[0]+        let fixed = Date(timeIntervalSince1970: 1_700_000_000)+        task.lastStatusChangeDate = fixed+        task.completionDate = fixed+        if scenario == "leaveTerminal" { task.status = .done }+        let target: TaskStatus = scenario == "terminal" ? .done : (scenario == "same" ? .idea : .planning)+        let service = TaskService(modelContext: fixture.owner.context,+            displayIDAllocator: DisplayIDAllocator(store: InMemoryCounterStore(), isCloudSyncActive: false))+        let comment = try service.updateStatus(task: task, to: target, comment: " \n",+            commentAuthor: nil, commentService: CommentService(modelContext: fixture.owner.context), save: false)+        #expect(comment == nil)+        #expect(task.status == target)+        #expect((task.lastStatusChangeDate == fixed) == (scenario == "same"))+        if scenario == "leaveTerminal" { #expect(task.completionDate == nil) }+        if scenario == "terminal" { #expect(task.completionDate != nil && task.completionDate != fixed) }+        if scenario == "same" || scenario == "nonterminalPreservesMalformedCompletion" {+            #expect(task.completionDate == fixed)+        }+    }++    @Test(arguments: ["trim", "clear", "clearMilestone", "displayPrecedence"])+    // Each row checks a distinct existing validator result without applying it.+    // swiftlint:disable:next cyclomatic_complexity+    func existingUpdateValidatorIsReadOnly(scenario: String) throws {+        let fixture = try MCPBatchTaskPreviewFixture()+        let service = MilestoneService(modelContext: fixture.owner.context,+            displayIDAllocator: DisplayIDAllocator(store: InMemoryCounterStore(), isCloudSyncActive: false))+        let args: [String: Any]+        switch scenario {+        case "trim": args = ["name": " Name ", "description": " Description "]+        case "clear": args = ["description": " \n", "metadata": [:] as [String: String]]+        case "clearMilestone": args = ["clearMilestone": true, "milestoneDisplayId": 999, "milestone": "Missing"]+        default: args = ["milestoneDisplayId": 9, "milestone": "Missing"]+        }+        let update = try TaskUpdateValidator.validate(args, task: fixture.targets[0], milestoneService: service).get()+        if scenario == "trim" {+            #expect(update.name == "Name")+            if case .set(let text) = update.description {+                #expect(text == "Description")+            } else { Issue.record("Description must trim") }+        }+        if scenario == "clear" {+            if case .clear = update.description {} else { Issue.record("Description must clear") }+            if case .clear = update.metadata {} else { Issue.record("Metadata must clear") }+        }+        if scenario == "clearMilestone" {+            if case .clear? = update.milestoneAction {} else { Issue.record("Clear takes precedence") }+        }+        if scenario == "displayPrecedence" {+            if case .assign(let milestone)? = update.milestoneAction {+                #expect(milestone.id == fixture.milestone.id)+            } else { Issue.record("Display ID takes precedence") }+        }+        #expect(!fixture.owner.context.hasChanges)+        try fixture.assertUntouched()+    }+}+#endif
Transit/TransitTests/MCPTestHelpers.swift Modified +2 / -1
diff --git a/Transit/TransitTests/MCPTestHelpers.swift b/Transit/TransitTests/MCPTestHelpers.swiftindex 9a2155e4..37fcb0e2 100644--- a/Transit/TransitTests/MCPTestHelpers.swift+++ b/Transit/TransitTests/MCPTestHelpers.swift@@ -81,7 +81,8 @@ enum MCPTestHelpers {             maintenanceService: maintenanceService, settings: mcpSettings, persistence: persistence,             taskFetcher: taskFetcher, commentFetcher: commentFetcher,             milestoneFetcher: milestoneFetcher,-            milestoneDisplayIDFinder: milestoneDisplayIDFinder, writeCoordinator: writeCoordinator+            milestoneDisplayIDFinder: milestoneDisplayIDFinder, writeCoordinator: writeCoordinator,+            batchContainer: context.container         )         return MCPTestEnv(             handler: handler,
Transit/TransitTests/MCPToolHandlerTests.swift Modified +2 / -2
diff --git a/Transit/TransitTests/MCPToolHandlerTests.swift b/Transit/TransitTests/MCPToolHandlerTests.swiftindex a5968949..03125df8 100644--- a/Transit/TransitTests/MCPToolHandlerTests.swift+++ b/Transit/TransitTests/MCPToolHandlerTests.swift@@ -43,11 +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 == 12)+        #expect(tools.count == 13)         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"]))+            "delete_milestone", "query_project_summaries", "mutate_tasks"]))         #expect(names.contains("create_task"))         #expect(names.contains("update_task_status"))         #expect(names.contains("query_tasks"))
Transit/TransitUITests/TransitUITests.swift Modified +8 / -16
diff --git a/Transit/TransitUITests/TransitUITests.swift b/Transit/TransitUITests/TransitUITests.swiftindex 6cd3020c..ddaec4c0 100644--- a/Transit/TransitUITests/TransitUITests.swift+++ b/Transit/TransitUITests/TransitUITests.swift@@ -22,9 +22,7 @@ final class TransitUITests: XCTestCase {         let app = launchApp()          // Navigate to settings [req 12.1]-        let settingsButton = app.buttons["dashboard.settingsButton"]-        XCTAssertTrue(settingsButton.waitForExistence(timeout: 5))-        settingsButton.tap()+        app.tapTransitToolbarButton(identifier: "dashboard.settingsButton", overflowLabel: "Settings")          // [req 20.4] Settings with zero projects shows create prompt         let prompt = app.staticTexts["Create your first project to get started."]@@ -37,9 +35,7 @@ final class TransitUITests: XCTestCase {     func testTappingGearPushesSettingsView() throws {         let app = launchApp() -        let settingsButton = app.buttons["dashboard.settingsButton"]-        XCTAssertTrue(settingsButton.waitForExistence(timeout: 5))-        settingsButton.tap()+        app.tapTransitToolbarButton(identifier: "dashboard.settingsButton", overflowLabel: "Settings")          // [req 12.1] Settings view is pushed onto the navigation stack         let settingsTitle = app.navigationBars["Settings"]@@ -50,7 +46,7 @@ final class TransitUITests: XCTestCase {     func testSettingsHasBackChevron() throws {         let app = launchApp() -        app.buttons["dashboard.settingsButton"].tap()+        app.tapTransitToolbarButton(identifier: "dashboard.settingsButton", overflowLabel: "Settings")          // [req 12.2] Chevron-only back button (no label text)         let backButton = app.navigationBars["Settings"].buttons.element(boundBy: 0)@@ -177,18 +173,14 @@ final class TransitUITests: XCTestCase {         let app = launchApp()         let window = app.windows.firstMatch         XCTAssertTrue(window.waitForExistence(timeout: 5))-        let portraitExpectation = XCTNSPredicateExpectation(-            predicate: NSPredicate { object, _ in-                guard let element = object as? XCUIElement else { return false }-                return element.frame.height > element.frame.width-            },-            object: window-        )-        XCTAssertEqual(XCTWaiter.wait(for: [portraitExpectation], timeout: 5), .completed)+        // A remote frame query can exceed a predicate waiter's budget even when+        // the device has acknowledged portrait. Capture once and assert the layout.+        let windowFrame = window.frame+        XCTAssertGreaterThan(windowFrame.height, windowFrame.width)          let segmentedControl = app.segmentedControls.firstMatch         XCTAssertGreaterThanOrEqual(-            window.frame.width,+            windowFrame.width,             400,             "The standard iPhone 17 UI destination must exercise the wide portrait Kanban path"         )
specs/batch-task-mutations/api15-consumer-import.json Added +53 / -0
diff --git a/specs/batch-task-mutations/api15-consumer-import.json b/specs/batch-task-mutations/api15-consumer-import.jsonnew file mode 100644index 00000000..21f33124--- /dev/null+++ b/specs/batch-task-mutations/api15-consumer-import.json@@ -0,0 +1,53 @@+{+  "deliveryCommit": "b21e358c8a5ea1e287afe332c1fc50d83303ce19",+  "sourceCommit": "543c4a757e4cb7f9f73c973d7cb1be5725c8f342",+  "imported": [+    {+      "path": "Transit/Transit/MCP/Results/MCPJSONDocument.swift",+      "sha256": "7efd3387f8b262d2a253343ce976f562dab830fe7aa2954832c6a11e1fae725c"+    },+    {+      "path": "Transit/Transit/MCP/Results/MCPResultAdapter.swift",+      "sha256": "b27522345f88c6a28a2a5ccc5d339bb89859bcecf794ced5e7f20314d3802254"+    },+    {+      "path": "Transit/Transit/MCP/Results/MCPResultByteWriter.swift",+      "sha256": "2aae6f485a5648c38bb83df76a2f7f5320d387d1e0b9ad66867c16020d6760c0"+    },+    {+      "path": "Transit/Transit/MCP/Results/MCPResultClassification.swift",+      "sha256": "8d3664f62cce2e142174235e060a00bfb02d92cfc4b4f3b1b81c8b26968a7380"+    },+    {+      "path": "Transit/Transit/MCP/Results/MCPResultEncoder.swift",+      "sha256": "177abf4f9b5b6158047de2c0ff0ad179565d8a1d1c50027403a902d3aaa77127"+    },+    {+      "path": "Transit/Transit/MCP/Results/MCPResultInspection.swift",+      "sha256": "5202d57c29a946a6e64ebb26ce5512f19aa1d5460a766141d30789af5c7fc2f1"+    },+    {+      "path": "Transit/Transit/MCP/Results/MCPResultLinks.swift",+      "sha256": "c31ec2298e3d90d56f71ba79a430eec94184a71876350e4b4ed0a7d277cf0036"+    },+    {+      "path": "Transit/Transit/MCP/Results/MCPResultProviderSelection.swift",+      "sha256": "49d54b6e3591c5e8eb37bb7c9d2779aa4d6309de055447a42ffb161e16dbdc62"+    },+    {+      "path": "Transit/Transit/MCP/Results/MCPResultSchemas.swift",+      "sha256": "ebb3af861af669af946f0b94eb3b3c68fd276e4be9416b180545ba383cf20338"+    },+    {+      "path": "Transit/Transit/MCP/Results/MCPResultSource.swift",+      "sha256": "524fe680c37db3670d283bb1e02d8a48a15195dc9ffc8aaa8ff5712e62337068"+    }+  ],+  "protectedUnchanged": {+    "Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift": "a1c040d1f007b1f2a3db27e64c2336c6670bac2b2e340204220414f92874a7d4",+    "Transit/Transit/TransitApp.swift": "64382a046f849f41b0015ee779a3e5ca956f241e4fedc5f260a51ef4ecaf34b6",+    "Transit/Transit.xcodeproj/project.pbxproj": "322614fe5cf1f6d2ba88e04c5bf46b44600c41a9f448149aa9f81d547ba6daee",+    "Makefile": "ec6fd731fd3fca59881077368f3fb1d8b2c29d399518f3747be3ae0732891c86"+  },+  "scope": "Task3 exact immutable source/encoder dependencies; no server binding or isolation import; no runtime verification"+}
specs/batch-task-mutations/local-review.json Added +125 / -0
diff --git a/specs/batch-task-mutations/local-review.json b/specs/batch-task-mutations/local-review.jsonnew file mode 100644index 00000000..cd6d251f--- /dev/null+++ b/specs/batch-task-mutations/local-review.json@@ -0,0 +1,125 @@+{+  "ticket": "T-2384",+  "reviewMode": "Four internal specialists plus root source/evidence checks; configured Claude external PR review follows under explicit owner approval",+  "reviewBase": "adc98b55e69af6be22e095126c81986d0d8e48a8",+  "reviewedSource": "fde318d5f8eedbef62f825bd9ad69889187c5f09",+  "nativeAcceptance": [+    {+      "suite": "macOS full units",+      "pin": "b90e6f84255f01c3de39104ea59a9aa0c77c7acb",+      "declarations": 2409,+      "cases": 3049,+      "result": "Passed",+      "finalized": true,+      "failed": 0,+      "skipped": 0,+      "expectedFailures": 0,+      "nativeRuntimeWarnings": [],+      "runnerExit": 0,+      "ownedRemaining": [],+      "hostSignals": [],+      "nativeResult": "DerivedData/t2384-publication-macos/PublicationMacOSUnits.xcresult",+      "inventoryProof": ".codex-cache/publication-macos/actual-inventory-check.json",+      "nativeSummary": ".codex-cache/publication-macos/native-summary.json",+      "drainEvidence": ".codex-cache/publication-macos/drain.json",+      "logSHA256": "038b65c48eb807026b15f098834b02ce6ff08a96ab9dc8d71b697aa84ee06ead"+    },+    {+      "suite": "iOS full units",+      "pin": "b90e6f84255f01c3de39104ea59a9aa0c77c7acb",+      "declarations": 1289,+      "cases": 1334,+      "result": "Passed",+      "finalized": true,+      "failed": 0,+      "skipped": 0,+      "expectedFailures": 0,+      "nativeRuntimeWarnings": [],+      "runnerExit": 0,+      "ownedRemaining": [],+      "hostSignals": [],+      "nativeResult": "DerivedData/t2384-publication-ios/PublicationIOSUnits.xcresult",+      "inventoryProof": ".codex-cache/publication-ios/unit-native-inventory-check.json",+      "nativeSummary": ".codex-cache/publication-ios/unit-native-summary.json",+      "drainEvidence": ".codex-cache/publication-ios/unit-drain.json",+      "logSHA256": "17a832f4d5a5ba5b13b94b3b98d141b5bd735104bbc2c940f37a1205e6be3c0c"+    },+    {+      "suite": "iOS full UI",+      "pin": "b8f9fc7e2277c5f4a6ba1d37f1133c8796ffa940",+      "declarations": 21,+      "cases": 24,+      "result": "Passed",+      "finalized": true,+      "failed": 0,+      "skipped": 0,+      "expectedFailures": 0,+      "nativeRuntimeWarnings": [],+      "runnerExit": 0,+      "ownedRemaining": [],+      "hostSignals": [],+      "nativeResult": "DerivedData/t2384-publication-ios/PublicationIOSUIAttempt2.xcresult",+      "inventoryProof": ".codex-cache/publication-ios-ui-attempt2/ui-native-inventory-check.json",+      "nativeSummary": ".codex-cache/publication-ios-ui-attempt2/ui-native-summary.json",+      "drainEvidence": ".codex-cache/publication-ios-ui-attempt2/ui-drain.json",+      "logSHA256": "cf12cd6d088facab5307011fc9a7d31bda9a2a1ec07faa7f0d274bc776f4d440"+    }+  ],+  "firstUIAttempt": {+    "pin": "b90e6f84255f01c3de39104ea59a9aa0c77c7acb",+    "executedCases": 24,+    "passed": 20,+    "failed": 4,+    "finalized": false,+    "failureEvidence": ".codex-cache/publication-ios/ui-failed-body-evidence.json",+    "teardown": "Sampled owned runner then runner-only TERM after bounded stalled finalization; subprocess exit -15, wrapper exit 241, no host signals, all owned processes drained. No successful native result claimed.",+    "correction": "Three Settings tests now use existing overflow-aware toolbar helper. Portrait test captures one remote frame and asserts height>width and existing width>=400/Kanban checks, avoiding a remote-query predicate timeout. Same21 declarations/24 cases; behavior assertions retained.",+    "correctedFreshResult": "iOS full UI acceptance above"+  },+  "artifactHashesIndependentlyVerified": 15,+  "publicationAuthority": "Explicit owner approval for all pushes, configured Claude review and eligible overnight merges; prior denial resolved",+  "clientReadiness": "MacBook activation deferred by owner; not merge blocker",+  "archive": null,+  "historicalOriginalReview": {+    "ticket": "T-2384",+    "reviewMode": "Four internal reviewers plus independent root critical review; no external peer-review service",+    "archive": {+      "helper": "/Users/arjen/golang/bin/pulsar",+      "action": "publish (local archive only)",+      "exit": 0,+      "path": "/Users/arjen/CodeReviews/2026-10/2026-10-04-github-transit-branch-t-2384-batch-task-mutations.html",+      "sha256": "083506b181c1a9154372cfec850bb54a32c0668e908d0b4ea19fe7517c199eec",+      "bytes": 5850534,+      "networkRequestPerformed": false,+      "globalSettingsChanged": false+    },+    "reviewBase": "201205bd4e786c7f152d8f99006b37da7da888c7",+    "testedCode": "5c42c7e059e8c810e89d366f0889aef132adf5c5",+    "generatedSnapshot": "e8ae1b3 plus documentation-only working tree",+    "cumulativeFiles": 417,+    "commitsReviewed": 396,+    "nativeAcceptance": {+      "macOS": {+        "declarations": 2409,+        "cases": 3049+      },+      "iOSUnits": {+        "declarations": 1289,+        "cases": 1334+      },+      "iOSUI": {+        "declarations": 21,+        "cases": 24+      }+    },+    "allFinalized": true,+    "failures": 0,+    "skips": 0,+    "nativeRuntimeWarnings": 0,+    "structuredReporting": "No detected JUnit/coverage runner; native xcresult evidence retained and counts explicit in HTML. Renderer JUnit summary zero is not a native test total.",+    "releaseHold": "Parent-reported prior approval-review rejection for private Claude diff/context disclosure and GitHub push destination authority; no alternate publication route attempted",+    "clientReadiness": "Deferred owner MacBook validation; no activation",+    "inputDirectory": "/Users/arjen/Documents/Codex/2026-10-03/task-4/review-inputs"+  },+  "structuredReporting": "No detected JUnit/line-coverage runner; actual native counts/inventories retained"+}
specs/batch-task-mutations/publication-verification.json Added +165 / -0
diff --git a/specs/batch-task-mutations/publication-verification.json b/specs/batch-task-mutations/publication-verification.jsonnew file mode 100644index 00000000..ca1e1b55--- /dev/null+++ b/specs/batch-task-mutations/publication-verification.json@@ -0,0 +1,165 @@+{+  "status": "Fresh publication reconciliation verification passed",+  "publicationBase": "adc98b55e69af6be22e095126c81986d0d8e48a8",+  "featureDeltaBase": "a4a60de579e5a30bc2ad9ff88b6954233f7ff42f",+  "reviewedFeatureTip": "db775173ea5f6d4717939a60d0a24da73204e7fd",+  "reconciliationCommit": "fde318d5f8eedbef62f825bd9ad69889187c5f09",+  "initialVerifiedPin": "b90e6f84255f01c3de39104ea59a9aa0c77c7acb",+  "finalUIFixturePin": "b8f9fc7e2277c5f4a6ba1d37f1133c8796ffa940",+  "scope": {+    "application": "Only reviewed feature base-to-tip diff applied with git apply --3way; no cumulative commit replay",+    "productionConflicts": [],+    "documentConflictsResolvedPreservingMain": [+      "CHANGELOG.md",+      "README.md",+      "specs/OVERVIEW.md"+    ],+    "productionAndConfigurationPathsEqualReviewedTip": 271,+    "postBaselineNonoverlappingMainFilesPreserved": [+      "Transit/TransitTests/MCPPortfolioReconciliationTests.swift",+      "specs/bounded-read-freshness/decision_log.md",+      "specs/bounded-read-freshness/implementation.md",+      "specs/bounded-read-freshness/task15-green-acceptance.md",+      "specs/bounded-read-freshness/task15-source-handoff.md",+      "specs/bounded-read-freshness/task16-green-acceptance.md",+      "specs/portfolio-summaries/decision_log.md",+      "specs/portfolio-summaries/implementation.md",+      "specs/portfolio-summaries/integration-acceptance.md",+      "specs/portfolio-summaries/requirements.md"+    ],+    "originalWorktreeCleanAndUntouched": true,+    "finalUIChange": "Only Transit/TransitUITests/TransitUITests.swift changed after initial verified pin; production, configuration and all unit test sources are byte-identical. Thus fresh full macOS/iOS unit acceptance remains applicable; full UI was freshly rebuilt and rerun at final pin."+  },+  "freshBuilds": {+    "macOS": {+      "exit": 0,+      "result": "DerivedData/t2384-publication-macos/PublicationMacOSBuild.xcresult"+    },+    "iOS": {+      "exit": 0,+      "result": "DerivedData/t2384-publication-ios/PublicationIOSBuild.xcresult"+    },+    "correctedUIIncremental": {+      "exit": 0,+      "result": "DerivedData/t2384-publication-ios/PublicationIOSUIBuildAttempt2.xcresult"+    }+  },+  "isolation": {+    "bundleID": "me.nore.ig.Transit.development",+    "signedPrivateDebugHost": true,+    "CloudKitPushAndAppGroupsAbsent": true,+    "unitPersistenceMode": "unit-test",+    "UIPersistenceMode": "ui-test",+    "serialRuns": true,+    "fullTargetsNoOnlyOrSkipFilters": true,+    "ownedSimulator": "BC0BB706-5B71-4827-8384-37931176D9A7",+    "ownedSimulatorShutdownAndDeleted": true,+    "otherSimulatorInventoryUnchanged": true,+    "persistentFixtureStoresPreserved": true+  },+  "acceptance": [+    {+      "suite": "macOS full units",+      "pin": "b90e6f84255f01c3de39104ea59a9aa0c77c7acb",+      "declarations": 2409,+      "cases": 3049,+      "result": "Passed",+      "finalized": true,+      "failed": 0,+      "skipped": 0,+      "expectedFailures": 0,+      "nativeRuntimeWarnings": [],+      "runnerExit": 0,+      "ownedRemaining": [],+      "hostSignals": [],+      "nativeResult": "DerivedData/t2384-publication-macos/PublicationMacOSUnits.xcresult",+      "inventoryProof": ".codex-cache/publication-macos/actual-inventory-check.json",+      "nativeSummary": ".codex-cache/publication-macos/native-summary.json",+      "drainEvidence": ".codex-cache/publication-macos/drain.json",+      "logSHA256": "038b65c48eb807026b15f098834b02ce6ff08a96ab9dc8d71b697aa84ee06ead"+    },+    {+      "suite": "iOS full units",+      "pin": "b90e6f84255f01c3de39104ea59a9aa0c77c7acb",+      "declarations": 1289,+      "cases": 1334,+      "result": "Passed",+      "finalized": true,+      "failed": 0,+      "skipped": 0,+      "expectedFailures": 0,+      "nativeRuntimeWarnings": [],+      "runnerExit": 0,+      "ownedRemaining": [],+      "hostSignals": [],+      "nativeResult": "DerivedData/t2384-publication-ios/PublicationIOSUnits.xcresult",+      "inventoryProof": ".codex-cache/publication-ios/unit-native-inventory-check.json",+      "nativeSummary": ".codex-cache/publication-ios/unit-native-summary.json",+      "drainEvidence": ".codex-cache/publication-ios/unit-drain.json",+      "logSHA256": "17a832f4d5a5ba5b13b94b3b98d141b5bd735104bbc2c940f37a1205e6be3c0c"+    },+    {+      "suite": "iOS full UI",+      "pin": "b8f9fc7e2277c5f4a6ba1d37f1133c8796ffa940",+      "declarations": 21,+      "cases": 24,+      "result": "Passed",+      "finalized": true,+      "failed": 0,+      "skipped": 0,+      "expectedFailures": 0,+      "nativeRuntimeWarnings": [],+      "runnerExit": 0,+      "ownedRemaining": [],+      "hostSignals": [],+      "nativeResult": "DerivedData/t2384-publication-ios/PublicationIOSUIAttempt2.xcresult",+      "inventoryProof": ".codex-cache/publication-ios-ui-attempt2/ui-native-inventory-check.json",+      "nativeSummary": ".codex-cache/publication-ios-ui-attempt2/ui-native-summary.json",+      "drainEvidence": ".codex-cache/publication-ios-ui-attempt2/ui-drain.json",+      "logSHA256": "cf12cd6d088facab5307011fc9a7d31bda9a2a1ec07faa7f0d274bc776f4d440"+    }+  ],+  "retainedFailedUIAttempt": {+    "pin": "b90e6f84255f01c3de39104ea59a9aa0c77c7acb",+    "executedCases": 24,+    "passed": 20,+    "failed": 4,+    "finalized": false,+    "failureEvidence": ".codex-cache/publication-ios/ui-failed-body-evidence.json",+    "teardown": "Sampled owned runner then runner-only TERM after bounded stalled finalization; subprocess exit -15, wrapper exit 241, no host signals, all owned processes drained. No successful native result claimed.",+    "correction": "Three Settings tests now use existing overflow-aware toolbar helper. Portrait test captures one remote frame and asserts height>width and existing width>=400/Kanban checks, avoiding a remote-query predicate timeout. Same21 declarations/24 cases; behavior assertions retained.",+    "correctedFreshResult": "iOS full UI acceptance above"+  },+  "lint": {+    "command": "make lint",+    "exit": 0,+    "files": 596,+    "violations": 0,+    "ownershipSchemaAndDevelopmentConfigurationGuards": "Passed",+    "log": ".codex-cache/publication-reconcile/final-lint.log"+  },+  "qualifications": [+    "Historical original-worktree artifacts are not current acceptance; these are fresh full native runs, not a union of focused results.",+    "UI native method display omits empty parentheses for testLaunch only; inventory comparison normalizes only that display suffix.",+    "Native runtimeWarnings arrays are empty; ordinary XCTest debugger lookup and animation-idle console diagnostics are retained in logs.",+    "Existing approved Markdown hard-break whitespace in imported spec documents was preserved.",+    "MacBook client check is deferred and is not a publication blocker. Parent owns remaining final documentation, external review and publication; this worker performed no push or external disclosure."+  ],+  "artifactSHA256": {+    ".codex-cache/publication-reconcile/source-equivalence.json": "eb0cc9bc2d46570c5e523a9542b8141f58dca3b50841515fe05ac8dbeda22564",+    ".codex-cache/publication-reconcile/final-source-check.json": "3c7f68fc2f0f09f63e121039ed77cf0a1e824f852f2e4a0b3ad82ddf0ec09ba5",+    ".codex-cache/publication-reconcile/final-lint.log": "95773cc729eff86e0de16c4c17502f4001f07acb1ad4eb579c9bcd278f3475ad",+    ".codex-cache/publication-macos/source-guard.json": "c29bd244d8e00bddb0a35e879fece14fa04dfacbf865fc23876b706a975354a5",+    ".codex-cache/publication-macos/signed-preflight.json": "3e244005234adbf3422d353c60ca0c4c9d20fec0449032c5d2fc2d44439e53fe",+    ".codex-cache/publication-macos/actual-inventory-check.json": "531f663d65b9edfbc00dfb86d0b077508ed645d5cfbd2425e9b1d65e0349a0b6",+    ".codex-cache/publication-ios/signed-preflight.json": "86509e0af4412a0508c0b34b1e74f789994813ba95e02892181ecb9067d7c96c",+    ".codex-cache/publication-ios/unit-native-inventory-check.json": "1dd19ac3887aab10e88858c25b862f10024dc61db919b7f114757610b09d1ea8",+    ".codex-cache/publication-ios/ui-failed-body-evidence.json": "f2c720ec5d53bde1b4265abefc1e3ec4cd83d2f0f5edebb7655b51ef73504812",+    ".codex-cache/publication-ios/ui-drain.json": "81ef27f6c5049b6b82ec06497672330d3ec5c03f8838743913b26c05b0210167",+    ".codex-cache/publication-ios/ui-finalization-runner-sample.txt": "ba3c3e561f2664e5705702fcaea021da6e7d549e3d61ef12e3a260a0c1249006",+    ".codex-cache/publication-ios-ui-attempt2/scope-equivalence.json": "aa126c798a45d964599ae1e34e3831a03085eb5bd2ea9f8767df1f761f41d3a4",+    ".codex-cache/publication-ios-ui-attempt2/signed-preflight.json": "81f886cffcc722e8759c34c30276834928969f35c158cde7324986ae75eba516",+    ".codex-cache/publication-ios-ui-attempt2/ui-native-inventory-check.json": "eabacad5cf859c94df45431c29702e9bf0a68a6c77c2218f10269ec2be2adc37",+    ".codex-cache/publication-ios-ui-attempt2/owned-simulator-cleanup.json": "fcaaf7061b326b8c7cdf6651bc39e7dae06f9fd63e709debb14f2d3a517a1c04"+  }+}
specs/batch-task-mutations/task10-green-actual.json Added +15 / -0
diff --git a/specs/batch-task-mutations/task10-green-actual.json b/specs/batch-task-mutations/task10-green-actual.jsonnew file mode 100644index 00000000..0aadeb01--- /dev/null+++ b/specs/batch-task-mutations/task10-green-actual.json@@ -0,0 +1,15 @@+{+  "sourcePin": "8342b3126a6e4c68705d90b5ae59a439b8252ecc",+  "declarations": 33,+  "parameterBodies": 110,+  "standaloneBodies": 19,+  "bodies": 129,+  "failed": 0,+  "skipped": 0,+  "runtimeExit": 0,+  "finalizedNativeResult": true,+  "signals": [],+  "ownedWorkersDrained": true,+  "logSHA256": "9b542fd77e2a28e9fc46009a48a44816406ec994925d5035ee4c6fbb8766f58a",+  "artifacts": ".codex-cache/task10-green-readiness"+}
specs/batch-task-mutations/task11-red-actual.json Added +21 / -0
diff --git a/specs/batch-task-mutations/task11-red-actual.json b/specs/batch-task-mutations/task11-red-actual.jsonnew file mode 100644index 00000000..79090bac--- /dev/null+++ b/specs/batch-task-mutations/task11-red-actual.json@@ -0,0 +1,21 @@+{+  "sourcePin": "5da541615ff97ca9f77b15c032d274ce65c79acc",+  "declarations": 7,+  "bodies": 10,+  "notImplementedIssues": 9,+  "controlsPassed": 1,+  "otherIssues": 0,+  "runtimeExit": 143,+  "ownedRemaining": [],+  "runnerSignal": "SIGTERM",+  "hostSignals": [],+  "finalizedResultClaim": false,+  "cleanupExecuted": false,+  "time": 1791131706.176476,+  "attempt1BuildExit": 65,+  "attempt1Failure": "fixture missing SwiftData defining-module import; corrected without assertion changes",+  "attempt2BuildExit": 0,+  "logSHA256": "13b3cd80963f7838565128780453c68c4326d4e18e9bf7542c132649d416ca77",+  "rootBoundaryReview": "clear;9 intended missing-builder issues +1 existing fallback control",+  "artifacts": ".codex-cache/task11-red-attempt2-readiness"+}
specs/batch-task-mutations/task12-green-actual.json Added +15 / -0
diff --git a/specs/batch-task-mutations/task12-green-actual.json b/specs/batch-task-mutations/task12-green-actual.jsonnew file mode 100644index 00000000..bf5b1907--- /dev/null+++ b/specs/batch-task-mutations/task12-green-actual.json@@ -0,0 +1,15 @@+{+  "sourcePin": "515c2f41affdf7d9bf8caaa1e492747db44e2776",+  "declarations": 10,+  "bodies": 14,+  "passed": 14,+  "failed": 0,+  "skipped": 0,+  "runtimeExit": 0,+  "finalizedNativeResult": true,+  "ownedRemaining": [],+  "signals": [],+  "priorAttempt": "Task12Green:14 bodies,two spelling-fixture assertions, sampled teardown143; preserved",+  "logSHA256": "943551d2847658ce709a45f3041fa2fd6f3bc754aa09adcd0b569976430da1c7",+  "artifacts": ".codex-cache/task12-green-attempt2-readiness"+}
specs/batch-task-mutations/task13-red-actual.json Added +19 / -0
diff --git a/specs/batch-task-mutations/task13-red-actual.json b/specs/batch-task-mutations/task13-red-actual.jsonnew file mode 100644index 00000000..9c5cb0dc--- /dev/null+++ b/specs/batch-task-mutations/task13-red-actual.json@@ -0,0 +1,19 @@+{+  "sourcePin": "23bcfe5b1e33cd8305e0d85a3901cdbf3ef397a3",+  "declarations": 14,+  "bodies": 18,+  "missingRegistrationFailingBodies": 7,+  "missingRegistrationIssues": 13,+  "controlBodiesPassed": 11,+  "otherIssues": 0,+  "buildExit": 0,+  "runtimeExit": 143,+  "runnerSignal": "SIGTERM",+  "hostSignals": [],+  "ownedRemaining": [],+  "finalizedResultClaim": false,+  "cleanupExecuted": false,+  "logSHA256": "3e3bd5d44d4d01724473a69df6bdab0803bf89b6c07248ce16806eca9b3f3160",+  "time": 1791133470.028852,+  "artifacts": ".codex-cache/task13-red-readiness"+}
specs/batch-task-mutations/task14-green-actual.json Added +121 / -0
diff --git a/specs/batch-task-mutations/task14-green-actual.json b/specs/batch-task-mutations/task14-green-actual.jsonnew file mode 100644index 00000000..1c1f715c--- /dev/null+++ b/specs/batch-task-mutations/task14-green-actual.json@@ -0,0 +1,121 @@+{+  "ticket": "T-2384",+  "task": 14,+  "status": "GREEN verified; all14Rune tasks complete",+  "verifiedCodePin": "5c42c7e059e8c810e89d366f0889aef132adf5c5",+  "reviewMode": "Four internal pre-push peers and independent root source/runtime review; external disclosure not authorized",+  "integrationSourceCommits": [+    "226b59454de946e6b497d11d75ef1e41db0e9926",+    "5b66fe33dc96a8ffc6bc81a64b5d65257fc81549",+    "5c42c7e059e8c810e89d366f0889aef132adf5c5"+  ],+  "focusedAttempt1": {+    "sourcePin": "5b66fe33dc96a8ffc6bc81a64b5d65257fc81549",+    "buildExit": 65,+    "runtimeExecuted": false,+    "failure": "Throwing modern schema calls needed explicit try; reviewed narrow correction preserved schema semantics"+  },+  "focusedGREEN": {+    "declarations": 17,+    "actualCases": 22,+    "buildExit": 0,+    "runtimeExit": 0,+    "finalized": true,+    "failed": 0,+    "skipped": 0,+    "warnings": [],+    "ownedRemaining": []+  },+  "freshMacOSUnits": {+    "declarations": 2409,+    "actualCases": 3049,+    "compiledToExecutedIdentityMatch": true,+    "includesTwoRepetitionLeaves": true,+    "runtimeExit": 0,+    "finalized": true,+    "failed": 0,+    "skipped": 0,+    "expectedFailures": 0,+    "runtimeWarnings": [],+    "ownedRemaining": []+  },+  "freshIOSUnits": {+    "declarations": 1289,+    "actualCases": 1334,+    "compiledToExecutedIdentityMatch": true,+    "buildExit": 0,+    "runtimeExit": 0,+    "finalized": true,+    "failed": 0,+    "skipped": 0,+    "expectedFailures": 0,+    "runtimeWarnings": [],+    "ownedRemaining": []+  },+  "freshIOSUI": {+    "declarations": 21,+    "actualCases": 24,+    "compiledToExecutedMethodMatch": true,+    "nativeDisplayNormalization": "Only native testLaunch omits empty () suffix; exact suite/method identities and all24leaves verified",+    "runtimeExit": 0,+    "finalized": true,+    "failed": 0,+    "skipped": 0,+    "expectedFailures": 0,+    "runtimeWarnings": [],+    "ownedRemaining": []+  },+  "iosPreflight": {+    "firstAttempt": "Fail closed before app launch because inherited macOS get-task-allow predicate does not apply to simulator empty entitlements",+    "acceptedAttempt": "signed-preflight-attempt2.json; root reviewed exact iOS27 simulator platform/development identity/private Debug hostpaths/strict signatures/noCloud/push/groups; separate fullunit unit-test and fullUI ui-test launches"+  },+  "lightChecks": {+    "finalMakeLintExit": 0,+    "swiftFiles": 596,+    "ownershipSchemaDevelopmentGuards": true,+    "syntaxParseExit": 0,+    "whitespaceExit": 0+  },+  "coverage": "Native Xcode results retained; no invented JUnit or coverage data",+  "cleanup": {+    "ownedDisposableSimulator": "14C40035-BADD-46EF-BA94-52875A387F30",+    "deletedAfterNormalDrain": true,+    "otherSimulatorsUntouched": true,+    "persistentTestStores": "Retained; no unmatched cleanup guard or old unmarked directory deletion"+  },+  "publication": "No push, PR, deployment, client activation, live writes or external review disclosure",+  "remaining": "Root-owned final phase documentation, CHANGELOG/OVERVIEW and local review HTML; installed-client readiness deferred to post-merge MacBook validation",+  "artifacts": {+    ".codex-cache/task14-green-attempt2-readiness/native-summary.json": "5553d1955c25f12daf97193d68d8f36957c688a0daaee2d2d2b8ef1956806c81",+    ".codex-cache/task14-green-attempt2-readiness/native-tests.json": "2d0b229b38b5de267688540259e19a2df4afde0e8e740079f14208c656b72e57",+    ".codex-cache/task14-green-attempt2-readiness/drain.json": "986e34b4958a1d565ce169d33bbccff7efcfaf8ac8025bd8c3e7ff0bd9b3990a",+    ".codex-cache/task14-green-attempt2-readiness/host-preflight.json": "bc1a5a291cec99503b077bc8488d07247f617ac4cedab7baa07ba7588bc9fff1",+    ".codex-cache/task14-green-attempt2-readiness/compiled-inventory-verification.json": "05d98f046907dae063fc5ad9b30b3f84c36af1c0deeaf8b9d16b6d164d70e530",+    ".codex-cache/task14-green-attempt2-readiness/focused-green-build.log": "ac4120ba0b11527d3a071cde700d7a4db6a4a8834b385d0d1cdad0c886cf5432",+    ".codex-cache/task14-green-attempt2-readiness/focused-green-test.log": "a3334549c8b2e5cce8ea066e2022db782add7ae4bc653ec68c88fa14c3cd3db2",+    ".codex-cache/final-macos-units/native-summary.json": "401da4ffb1c0a7d9904579f70145b3aa6e36550246fb072fc2ad7719f7049c78",+    ".codex-cache/final-macos-units/native-tests.json": "147d376005c6bbd335ab1045a9780995702160ec3e505cfbc495301012fbf7de",+    ".codex-cache/final-macos-units/full-inventory-guard.json": "0349960af5156d928a4a176dfd429e160e552b339a80b2f92804c4722fe82d70",+    ".codex-cache/final-macos-units/actual-native-inventory-check.json": "806f59ac3db2e73df831f3eb17f6aae8e71af0922d2c6f0c84c9c38eabf6b06f",+    ".codex-cache/final-macos-units/drain.json": "0c4b1c980c32cd74683205b1150d9a9a36325acb07f715e8c31d5620a66dd07e",+    ".codex-cache/final-macos-units/full-unit-test.log": "72531bf0a90668cb852955bd5479efbb08fb1e09fe75f79278ff5fc98edf6484",+    ".codex-cache/final-ios/signed-preflight-attempt2.json": "bd53d06badd23b71f3a1b7fd1a7d663250cb250e1505c9dc94eb96132b396b0c",+    ".codex-cache/final-ios/preflight-attempt1.json": "d86fb04862e30036b1f681b09a112e6a8b0a0eab23cef3782e9caa750edc55c5",+    ".codex-cache/final-ios/unit-native-summary.json": "c5ba7241e107aa4792df8195b6df3247dd0e9462b35cc276d932b11ec69d1838",+    ".codex-cache/final-ios/unit-native-tests.json": "20fde05d6b841085c6306cdb69ddefb8b6dd0ef0a88f1d14ebe27213e08a5285",+    ".codex-cache/final-ios/unit-native-inventory-check.json": "9121991dafbe44af4157b8cab608e391e7404878487fc201c34d465911d6daa6",+    ".codex-cache/final-ios/unit-inventory-guard.json": "f2b07ce2f7e98ba6a31164ae31af18e1dbc23d30d5bb488de2d68ffca201d2f6",+    ".codex-cache/final-ios/unit-drain.json": "ac46bcfcb9debc7f58708cba12a37cd75f00712e13fe23e1222f0433c042521c",+    ".codex-cache/final-ios/ui-native-summary.json": "8d36ee6587fc95d9844bd3cc180b990184f21fd73e34cca590b1182f59b8ceb3",+    ".codex-cache/final-ios/ui-native-tests.json": "91571dad79f96815af481405879fc06dc2c66f92ed678314382909e93ba5c8fc",+    ".codex-cache/final-ios/ui-native-inventory-check.json": "8af0ef0a79707ccebc6a0138edd84ee1317dbcaef18f96242e6348b5a3ab8cf5",+    ".codex-cache/final-ios/ui-inventory-guard.json": "d280fc09ca5d38a625643238cfac04fa1dfedfcd95185c6904be4d9c467b9d4d",+    ".codex-cache/final-ios/ui-drain.json": "ac46bcfcb9debc7f58708cba12a37cd75f00712e13fe23e1222f0433c042521c",+    ".codex-cache/final-ios/owned-simulator-cleanup.json": "19e1112c696ff4ed7103216af95f55e61cd15315afb7dff867ecd858ed752bc6",+    ".codex-cache/final-ios/full-ios-build.log": "f88fdf25cccae8b16f4d0be1c0a875e9d23058d5d1b61db300bbbc0b1097cb86",+    ".codex-cache/final-ios/full-ios-unit-test.log": "d28f21ba03c1645302a0eb7565841fc25e2323a11dc10a800674c6e42872b034",+    ".codex-cache/final-ios/full-ios-ui-test.log": "9c1a9802974f9d825006927839a47320c041dd76e8eeb5cb436d7d3a958324f0",+    ".codex-cache/task14-source-checks/final-full-lint.log": "a39bb730aa922727caa8192bd5809582f7ad1e3849e0153ecf9a11044ba14100",+    ".codex-cache/task14-source-checks/parse.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+  }+}
specs/batch-task-mutations/task3-red-verification.json Added +46 / -0
diff --git a/specs/batch-task-mutations/task3-red-verification.json b/specs/batch-task-mutations/task3-red-verification.jsonnew file mode 100644index 00000000..a5b74c59--- /dev/null+++ b/specs/batch-task-mutations/task3-red-verification.json@@ -0,0 +1,46 @@+{+  "source": "0512d99866c5fea1a1ffd1896ad61701e2dee2a5",+  "ownerImport": "8be35ea",+  "offlineIsolationExit": 0,+  "smokeBuildExit": 0,+  "signedSmokeExit": 0,+  "smokePassedBodies": 1,+  "focusedBuildExit": 0,+  "signedHostPreflightExit": 0,+  "enumerationExit": 0,+  "inventoryExit": 0,+  "enabledDeclarations": 13,+  "executedDeclarations": 13,+  "parameterCasesStarted": 48,+  "standaloneBodiesStarted": 4,+  "executedBodies": 52,+  "issues": 16,+  "expectedIssueBoundaries": [+    "canAdvance false declaration shell",+    "MCPResultBoundaryError.notImplemented fallback shell"+  ],+  "testExit": 143,+  "finalizedResult": false,+  "ownedDrained": true,+  "cleanup": "Both runner66051 and host66059 sampled exit0 before signal; identity-checked TERM to runner66051 only; host drained without signal. Cleanup poll saw transient defunct runner and its identity assertion stopped; unified session reaped runner then final ps showed both absent.",+  "slotReleased": true,+  "noReplay": true,+  "issuesFromConsole": [+    "\u2718 Test compactFallbackStripsGiantItemRecordsDiagnosticsAndEntityLinks() recorded an issue at MCPBatchTaskEncodingTests.swift:41:6: Caught error: .notImplemented",+    "\u2718 Test preparationFailureDoesNotDispatchOrTryNormalEncoding() recorded an issue at MCPBatchTaskEncodingTests.swift:78:6: Caught error: .notImplemented",+    "\u2718 Test postEffectFailureSelectsCompletePreparedBytesWithoutSecondEncoding(stage:) recorded an issue with 1 argument stage \u2192 \"payload\" at MCPBatchTaskEncodingTests.swift:100:6: Caught error: .notImplemented",+    "\u2718 Test postEffectFailureSelectsCompletePreparedBytesWithoutSecondEncoding(stage:) recorded an issue with 1 argument stage \u2192 \"presentation\" at MCPBatchTaskEncodingTests.swift:100:6: Caught error: .notImplemented",+    "\u2718 Test postEffectFailureSelectsCompletePreparedBytesWithoutSecondEncoding(stage:) recorded an issue with 1 argument stage \u2192 \"envelope\" at MCPBatchTaskEncodingTests.swift:100:6: Caught error: .notImplemented",+    "\u2718 Test readableDepth32ReceiptOverflowsGeneratedAggregateAfterSyntheticCommit() recorded an issue at MCPBatchTaskEncodingTests.swift:144:6: Caught error: .notImplemented",+    "\u2718 Test equivalentNumericVersionAndOriginalOptionalFlagCanAdvance(version:isError:) recorded an issue with 2 arguments version \u2192 \"1\", isError \u2192 nil at MCPBatchTaskEvidenceTests.swift:18:9: Expectation failed: result.canAdvance",+    "\u2718 Test equivalentNumericVersionAndOriginalOptionalFlagCanAdvance(version:isError:) recorded an issue with 2 arguments version \u2192 \"1\", isError \u2192 false at MCPBatchTaskEvidenceTests.swift:18:9: Expectation failed: result.canAdvance",+    "\u2718 Test equivalentNumericVersionAndOriginalOptionalFlagCanAdvance(version:isError:) recorded an issue with 2 arguments version \u2192 \"1.0\", isError \u2192 nil at MCPBatchTaskEvidenceTests.swift:18:9: Expectation failed: result.canAdvance",+    "\u2718 Test equivalentNumericVersionAndOriginalOptionalFlagCanAdvance(version:isError:) recorded an issue with 2 arguments version \u2192 \"1.0\", isError \u2192 false at MCPBatchTaskEvidenceTests.swift:18:9: Expectation failed: result.canAdvance",+    "\u2718 Test equivalentNumericVersionAndOriginalOptionalFlagCanAdvance(version:isError:) recorded an issue with 2 arguments version \u2192 \"1e0\", isError \u2192 nil at MCPBatchTaskEvidenceTests.swift:18:9: Expectation failed: result.canAdvance",+    "\u2718 Test equivalentNumericVersionAndOriginalOptionalFlagCanAdvance(version:isError:) recorded an issue with 2 arguments version \u2192 \"1e0\", isError \u2192 false at MCPBatchTaskEvidenceTests.swift:18:9: Expectation failed: result.canAdvance",+    "\u2718 Test operationSpecificSavedIdentityCanAdvance(operation:) recorded an issue with 1 argument operation \u2192 \"update_task\" at MCPBatchTaskEvidenceTests.swift:76:9: Expectation failed: result.canAdvance",+    "\u2718 Test operationSpecificSavedIdentityCanAdvance(operation:) recorded an issue with 1 argument operation \u2192 \"update_task_status\" at MCPBatchTaskEvidenceTests.swift:76:9: Expectation failed: result.canAdvance",+    "\u2718 Test operationSpecificSavedIdentityCanAdvance(operation:) recorded an issue with 1 argument operation \u2192 \"add_comment\" at MCPBatchTaskEvidenceTests.swift:76:9: Expectation failed: result.canAdvance",+    "\u2718 Test requestedStatusReasonRequiresItsOwnSavedComment(kind:) recorded an issue with 1 argument kind \u2192 \"valid\" at MCPBatchTaskEvidenceTests.swift:91:9: Expectation failed: result.canAdvance == (kind == \"valid\")"+  ]+}
specs/batch-task-mutations/task4-green-verification.json Added +35 / -0
diff --git a/specs/batch-task-mutations/task4-green-verification.json b/specs/batch-task-mutations/task4-green-verification.jsonnew file mode 100644index 00000000..631931f5--- /dev/null+++ b/specs/batch-task-mutations/task4-green-verification.json@@ -0,0 +1,35 @@+{+  "sourcePin": "85bec71446a322f87a05af39360f2bab2fa9007d",+  "implementation": "28bee6ae0bf48a756da7220a5840ba24cb0e7aa3",+  "configurationGuardExit": 0,+  "buildExit": 0,+  "signedPreflightExit": 0,+  "enumerationExit": 0,+  "inventoryExit": 0,+  "testExit": 0,+  "finalizedResult": "Passed",+  "enabledAndExecutedDeclarations": 21,+  "parameterizedDeclarations": 14,+  "parameterCaseRuns": 77,+  "standaloneBodies": 7,+  "actualExecutedBodies": 84,+  "issues": 0,+  "failedTests": 0,+  "skippedTests": 0,+  "runtimeWarnings": [],+  "consoleWarning": "Xcode multiple matching destination selection; existing build scheme/test warnings retained in raw logs",+  "summaryExtractionAttempts": [+    {+      "sandboxExit": 64,+      "reason": "xcresulttool report-cache write denied"+    },+    {+      "perCommandEscalatedExit": 0+    }+  ],+  "ownedDrained": true,+  "cleanup": "None: normal finish, no samples/signals/replay",+  "slotReleasedBeforeExtraction": true,+  "originalFixturesUnchanged": "13 declarations /52 cases",+  "supplementalFixtures": "8 declarations /32 cases"+}
specs/batch-task-mutations/task5-red-verification.json Added +24 / -0
diff --git a/specs/batch-task-mutations/task5-red-verification.json b/specs/batch-task-mutations/task5-red-verification.jsonnew file mode 100644index 00000000..405e464c--- /dev/null+++ b/specs/batch-task-mutations/task5-red-verification.json@@ -0,0 +1,24 @@+{+  "sourcePin": "f428f941fd77af893593acf8db8ac01e9d4b9063",+  "buildExit": 0,+  "signedPreflightExit": 0,+  "enumerationExit": 0,+  "inventoryExit": 0,+  "declarations": 17,+  "parameterBodies": 105,+  "standaloneBodies": 4,+  "actualBodies": 109,+  "issues": 109,+  "allIssues": "Caught error: .notImplemented",+  "runtimeREDVerified": true,+  "unrelatedIssues": 0,+  "runnerExit": 143,+  "xcresultFinalized": false,+  "sampledBeforeRunnerOnlyTERM": true,+  "hostSignalled": false,+  "ownedWorkersDrained": true,+  "slotReleased": true,+  "noReplay": true,+  "priorAttempt": "attempt1 build65 fixture compiler issue; no bodies; drained; preserved",+  "rootReview": "root-runtime-review.json"+}
specs/batch-task-mutations/task6-green-verification.json Added +29 / -0
diff --git a/specs/batch-task-mutations/task6-green-verification.json b/specs/batch-task-mutations/task6-green-verification.jsonnew file mode 100644index 00000000..387d3fcf--- /dev/null+++ b/specs/batch-task-mutations/task6-green-verification.json@@ -0,0 +1,29 @@+{+  "reviewedPin": "5066a06d7c2065cb37858dddc81670268ac9ebb4",+  "sourcePin": "565c336afd4c02bbb4d52c34aa9904ee5d0eca41",+  "buildExit": 0,+  "signedPreflightExit": 0,+  "enumerationExit": 0,+  "inventoryExit": 0,+  "runExit": 0,+  "result": "Passed",+  "declarations": 21,+  "parameterizedDeclarations": 17,+  "parameterBodies": 128,+  "standaloneBodies": 4,+  "actualBodies": 132,+  "failed": 0,+  "skipped": 0,+  "expectedFailures": 0,+  "runtimeWarnings": [],+  "xcresultFinalized": true,+  "ownedWorkersDrained": true,+  "signals": false,+  "replays": false,+  "slotReleasedBeforeExtraction": true,+  "originalTask5Cases": 109,+  "supplementalCases": 23,+  "prior84FixturesUnchanged": true,+  "rawEvidence": ".codex-cache/task6-green-readiness/",+  "rootReview": "root-runtime-review.json"+}
specs/batch-task-mutations/task7-fixture-lifetime-diagnosis.json Added +163 / -0
diff --git a/specs/batch-task-mutations/task7-fixture-lifetime-diagnosis.json b/specs/batch-task-mutations/task7-fixture-lifetime-diagnosis.jsonnew file mode 100644index 00000000..3e581166--- /dev/null+++ b/specs/batch-task-mutations/task7-fixture-lifetime-diagnosis.json@@ -0,0 +1,163 @@+{+  "status": "source-only fixture lifetime correction; meaningful corrected RED pending",+  "cause": {+    "containerRetention": "TestModelContainer.swift16\u201319 and40 retains ModelContainers for process lifetime",+    "prematureDelete": "MCPBatchTaskPreviewFixture.swift77 at e206f8c removed SQLite backing directory in fixture deinit",+    "directEvidence": "Original run log34\u201342 reports SQLite vnode-unlinked while files remain open; subsequent CoreData missing-store faults and seven automatic host restarts",+    "sampleLimit": "Runner/host samples show framework runloop waits after bodies, not proof of a preview validation deadlock"+  },+  "originalEvidence": {+    "runtimeSourcePin": "e206f8c739ce1f7c2b88157f125ab025b27e9045",+    "log": ".codex-cache/task7-red-attempt5/focused-red-test.log",+    "logSHA256": "0d3c110ac3c0c0c0f0756b76f2493c2cc61368f21bf8fabb1338c1ae1d6b0b94",+    "originalRun": {+      "run": 1,+      "kind": "original",+      "declarationsStarted": 25,+      "parameterBodiesStarted": 61,+      "standaloneBodiesStarted": 7,+      "physicalBodiesStarted": 68,+      "reportedDeclarations": 25,+      "reportedIssues": 53,+      "baselineControlsPassed": true,+      "recordedIssueCount": 53,+      "allParsedIssueRecordsArePlaceholder": true,+      "unparsedReportedIssues": 0,+      "parserLimit": "All reported issue records classified."+    },+    "logicalBodies": 68,+    "intendedPlaceholderIssues": 53,+    "baselineControls": 15,+    "automaticPartialRestarts": [+      {+        "run": 2,+        "kind": "automaticPartialRestart",+        "declarationsStarted": 24,+        "parameterBodiesStarted": 59,+        "standaloneBodiesStarted": 7,+        "physicalBodiesStarted": 66,+        "reportedDeclarations": 24,+        "reportedIssues": 51,+        "baselineControlsPassed": true,+        "recordedIssueCount": 50,+        "allParsedIssueRecordsArePlaceholder": true,+        "unparsedReportedIssues": 1,+        "parserLimit": "Partial restart logs contain interleaved output; unparsed reported issues remain unclassified."+      },+      {+        "run": 3,+        "kind": "automaticPartialRestart",+        "declarationsStarted": 23,+        "parameterBodiesStarted": 59,+        "standaloneBodiesStarted": 6,+        "physicalBodiesStarted": 65,+        "reportedDeclarations": 23,+        "reportedIssues": 50,+        "baselineControlsPassed": true,+        "recordedIssueCount": 50,+        "allParsedIssueRecordsArePlaceholder": true,+        "unparsedReportedIssues": 0,+        "parserLimit": "All reported issue records classified."+      },+      {+        "run": 4,+        "kind": "automaticPartialRestart",+        "declarationsStarted": 22,+        "parameterBodiesStarted": 54,+        "standaloneBodiesStarted": 6,+        "physicalBodiesStarted": 60,+        "reportedDeclarations": 22,+        "reportedIssues": 45,+        "baselineControlsPassed": true,+        "recordedIssueCount": 45,+        "allParsedIssueRecordsArePlaceholder": true,+        "unparsedReportedIssues": 0,+        "parserLimit": "All reported issue records classified."+      },+      {+        "run": 5,+        "kind": "automaticPartialRestart",+        "declarationsStarted": 21,+        "parameterBodiesStarted": 52,+        "standaloneBodiesStarted": 6,+        "physicalBodiesStarted": 58,+        "reportedDeclarations": 21,+        "reportedIssues": 43,+        "baselineControlsPassed": true,+        "recordedIssueCount": 43,+        "allParsedIssueRecordsArePlaceholder": true,+        "unparsedReportedIssues": 0,+        "parserLimit": "All reported issue records classified."+      },+      {+        "run": 6,+        "kind": "automaticPartialRestart",+        "declarationsStarted": 20,+        "parameterBodiesStarted": 52,+        "standaloneBodiesStarted": 5,+        "physicalBodiesStarted": 57,+        "reportedDeclarations": 20,+        "reportedIssues": 42,+        "baselineControlsPassed": true,+        "recordedIssueCount": 42,+        "allParsedIssueRecordsArePlaceholder": true,+        "unparsedReportedIssues": 0,+        "parserLimit": "All reported issue records classified."+      },+      {+        "run": 7,+        "kind": "automaticPartialRestart",+        "declarationsStarted": 19,+        "parameterBodiesStarted": 50,+        "standaloneBodiesStarted": 5,+        "physicalBodiesStarted": 55,+        "reportedDeclarations": 19,+        "reportedIssues": 40,+        "baselineControlsPassed": true,+        "recordedIssueCount": 37,+        "allParsedIssueRecordsArePlaceholder": true,+        "unparsedReportedIssues": 3,+        "parserLimit": "Partial restart logs contain interleaved output; unparsed reported issues remain unclassified."+      },+      {+        "run": 8,+        "kind": "automaticPartialRestart",+        "declarationsStarted": 18,+        "parameterBodiesStarted": 48,+        "standaloneBodiesStarted": 5,+        "physicalBodiesStarted": 53,+        "reportedDeclarations": 18,+        "reportedIssues": 38,+        "baselineControlsPassed": true,+        "recordedIssueCount": 38,+        "allParsedIssueRecordsArePlaceholder": true,+        "unparsedReportedIssues": 0,+        "parserLimit": "All reported issue records classified."+      }+    ],+    "automaticRestartMarkers": 7,+    "workerLaunchedReplays": 0,+    "fixtureFaultsSeparate": {+      "vnodeUnlinkedOccurrences": 1170,+      "coreDataMissingStoreOccurrences": 28+    },+    "runnerCleanupSeparate": {+      "runnerPID": 18601,+      "runnerSampleExit": 0,+      "hostSamplePID": 19137,+      "hostSampleExit": 0,+      "runnerOnlySignal": "SIGTERM",+      "runtimeExit": 143,+      "hostSignals": [],+      "allOwnedWorkersDrained": true+    },+    "task7Complete": false+  },+  "fix": "Preserve backing directory for process lifetime; exact T2384Task7Preview-UUID ownership marker; marker-only bounded off-process cleanup after pinned source/run/drain evidence and current owned PID absence",+  "assertions": "All six-entity/canonical-field/pending-object/descriptor/advisory/revision/effect assertions and25/68 unchanged",+  "cleanupLimits": "48 directories; excess markers, automatic replay markers, interleaving, traversal, symlinks, wrong ownership or live PIDs preserve every store. Cleanup must precede bookkeeping HEAD changes. No glob/old unmarked-store cleanup.",+  "unchanged": "TestModelContainer, SafetyFixture and all production helper/service/command/coordinator files",+  "separateSafetyAssessment": "MCPBatchTaskSafetyFixture.swift50 has same historical deinit cleanup pattern with process-retained containers; not edited under Task7 scope, requires coordinated later assessment",+  "newRuntimeExecuted": false,+  "task7Complete": false+}
specs/batch-task-mutations/task7-red-actual.json Added +30 / -0
diff --git a/specs/batch-task-mutations/task7-red-actual.json b/specs/batch-task-mutations/task7-red-actual.jsonnew file mode 100644index 00000000..0390204e--- /dev/null+++ b/specs/batch-task-mutations/task7-red-actual.json@@ -0,0 +1,30 @@+{+  "sourcePin": "e008ad1b46dfab2fc39a128e16546a95220bee39",+  "logSHA256": "e5c77788ce6ad0bcc1d5dc448060464b0d6ca94a7d717528bbc03fca7fc3b84d",+  "declarations": 25,+  "parameterDeclarations": 18,+  "parameterBodies": 61,+  "standaloneBodies": 7,+  "bodies": 68,+  "issues": 53,+  "issueClassification": {+    "notImplemented": 53,+    "unclassified": 0,+    "caughtPlaceholder": 46,+    "explicitUnexpectedPlaceholderControls": 7+  },+  "baselineControlBodies": 15,+  "runStarts": 1,+  "automaticRestarts": 0,+  "vnodeFaults": 0,+  "ownedMarkers": 48,+  "sourceUnchanged": true,+  "runtimeExit": 143,+  "sampledRunnerOnlyTERM": true,+  "finalizedXCResultClaim": false,+  "cleanupExecuted": true,+  "task7Complete": true,+  "cleanupDirectories": 48,+  "review": "Parent independent console classification clear; meaningful RED accepted with sampled teardown143/unfinalized result limit.",+  "evidenceDirectory": ".codex-cache/task7-red-attempt6"+}
specs/batch-task-mutations/task7-red-readiness.json Added +32 / -0
diff --git a/specs/batch-task-mutations/task7-red-readiness.json b/specs/batch-task-mutations/task7-red-readiness.jsonnew file mode 100644index 00000000..9f27c9ab--- /dev/null+++ b/specs/batch-task-mutations/task7-red-readiness.json@@ -0,0 +1,32 @@+{+  "status": "SOURCE ONLY; Task7 in progress; no meaningful RED yet",+  "base": "6eae0f3",+  "declarations": 25,+  "bodies": 68,+  "intendedPlaceholderBodies": 53,+  "existingControlBodies": 15,+  "noAppJobExecuted": true,+  "ownedFiles": {+    "Transit/Transit/Services/CommentInputValidation.swift": "6559ed200988b9d4d72f7d284f2ab98b12907da87ae8fb9b1ec2b50501e71350",+    "Transit/Transit/MCP/BatchWrites/MCPTaskMutationValidation.swift": "09c186ae0ab5cf6a1e74baecaa1944ec3bf3abf04f3490bc1fe30d057ca13f9c",+    "Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreview.swift": "4e1b05a0282e229e35f083c4d3821981aa54e2e5e7863a260d68bec8327fe395",+    "Transit/TransitTests/MCPBatchTaskPreviewFixture.swift": "905f13fd09369a914763b7b5be6cece149e5894cddc7e46193335d38dc5ba235",+    "Transit/TransitTests/MCPBatchTaskPreviewTests.swift": "e0115616d04d6659f0851b2a82bea0bf67baf93e5d20e143647b3810db84465d",+    "Transit/TransitTests/MCPTaskMutationValidationTests.swift": "bd413773b58209d2ad0ca909216d8f2a0d7d7f68a72d7c8af5636b63c97b4026"+  },+  "protectedFilesUnchanged": [+    "Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift",+    "Transit/Transit/Services/CommentService.swift",+    "Transit/Transit/Services/TaskService.swift",+    "Transit/Transit/MCP/Writes/MCPWriteCommand.swift",+    "Transit/Transit/TransitApp.swift",+    "Transit/Transit.xcodeproj/project.pbxproj",+    "Makefile"+  ],+  "oldFixtureFilesUnchanged": 9,+  "readinessDirectory": ".codex-cache/task7-red-readiness",+  "sourceReview": "Independent root source review clear for 46363eecd2a929d452297c1abd851cf188efa278; see task7-red-review.md. No runtime RED result or Task8 authority.",+  "runtimeLimits": "Syntax parse is not typecheck. Static effect guard supplements descriptor spies, noChanges, pending preservation and canonical durable readback; discarded constructor/clock calls are prohibited by source guard, not global runtime interception. No coordinator/sidecar constructor or write services supplied to preview.",+  "expectedFailures": "Preview and pure helper shells throw explicit notImplemented. Existing CommentService/TaskService/TaskUpdateValidator/protected-command controls must independently pass.",+  "requiredStart": "Parent exclusive heavy START after reviewed sourcepin/signature/hash/inventory guards. No Task8 source until meaningful RED reviewed."+}
specs/batch-task-mutations/task8-green-actual.json Added +22 / -0
diff --git a/specs/batch-task-mutations/task8-green-actual.json b/specs/batch-task-mutations/task8-green-actual.jsonnew file mode 100644index 00000000..1286e3f0--- /dev/null+++ b/specs/batch-task-mutations/task8-green-actual.json@@ -0,0 +1,22 @@+{+  "sourcePin": "403844121916ab2f19f6d2ead5d63fd42d0fbdfa",+  "declarations": 27,+  "parameterDeclarations": 19,+  "parameterBodies": 63,+  "standaloneBodies": 8,+  "bodies": 71,+  "issues": 0,+  "runtimeExit": 0,+  "runStarts": 1,+  "automaticRestarts": 0,+  "vnodeFaults": 0,+  "ownedMarkers": 50,+  "signals": [],+  "cleanupExecuted": true,+  "task8Complete": true,+  "logSHA256": "559954ae981aba28ae81e1ae8ffdc7133b36c899b2d5a5fac62a545cf9c9a6a7",+  "cleanupDirectories": 50,+  "finalizedXCResult": true,+  "review": "Parent independent actual console and finalized xcresult review clear.",+  "evidenceDirectory": ".codex-cache/task8-green-readiness"+}
specs/batch-task-mutations/task9-red-actual.json Added +25 / -0
diff --git a/specs/batch-task-mutations/task9-red-actual.json b/specs/batch-task-mutations/task9-red-actual.jsonnew file mode 100644index 00000000..2ff7e52e--- /dev/null+++ b/specs/batch-task-mutations/task9-red-actual.json@@ -0,0 +1,25 @@+{+  "sourcePin": "fc1b7d9d034cdcee1af7b822d3423c8830e01722",+  "boundaryReview": "ff1d21f",+  "logSHA256": "93713121f1b2abb7d2df6c835c689c0af22ccb879b1013e9f7d02fb41568b23b",+  "declarations": 30,+  "parameterBodies": 110,+  "standaloneBodies": 16,+  "bodies": 126,+  "caughtNotImplemented": 113,+  "customNotImplemented": 5,+  "otherIssues": 0,+  "baselineControlsPassed": 8,+  "runStarts": 1,+  "automaticRestarts": 0,+  "fixtureMarkers": 29,+  "storeFaults": 0,+  "buildExit": 0,+  "runtimeExit": 143,+  "runnerSignal": "SIGTERM",+  "hostSignals": [],+  "finalizedResultClaim": false,+  "ownedWorkersDrained": true,+  "cleanupExecuted": false,+  "evidenceDirectory": ".codex-cache/task9-red-readiness"+}
specs/batch-task-mutations/task9-red-blocked.json Added +31 / -0
diff --git a/specs/batch-task-mutations/task9-red-blocked.json b/specs/batch-task-mutations/task9-red-blocked.jsonnew file mode 100644index 00000000..b572ee6d--- /dev/null+++ b/specs/batch-task-mutations/task9-red-blocked.json@@ -0,0 +1,31 @@+{+  "reviewedSourcePin": "ae54ea1f347641cb936388d80a4cda8dc501bf68",+  "guards": {+    "cleanSourceAndReadinessHashes": "PASS",+    "configuration": 0+  },+  "buildLaunchAttempts": 2,+  "heavyProcessesCreated": 0,+  "testBodiesExecuted": 0,+  "compiledInventoryVerified": false,+  "actualREDVerified": false,+  "task9Complete": false,+  "task10Allowed": false,+  "slotHeld": false,+  "evidence": {+    "auto-review-rejection.json": {+      "sha256": "738f7745066171fc0b18dc69703d3c3933a7d959f00052d7d8102f5e1cf49f3a",+      "path": ".codex-cache/task9-red-readiness/auto-review-rejection.json"+    },+    "auto-review-rejection-retry.json": {+      "sha256": "3073e369316ea83fa96b8754ad3ceca247f1d866c56a48838f8a9261de5c7518",+      "path": ".codex-cache/task9-red-readiness/auto-review-rejection-retry.json"+    },+    "configuration-guard.log": {+      "sha256": "1da8eb8193fed6bf110ee5694cea717fadb86262f3676f874a5c7cc01ae72996",+      "path": ".codex-cache/task9-red-readiness/configuration-guard.log"+    }+  },+  "secondRejectionExactReason": "The action launches a focused implementation build, while the trusted user instruction explicitly prohibited heavy builds/tests; the later approval is only quoted in untrusted assistant content and does not override that restriction.",+  "nextStep": "Await trusted direct approval and a new exclusive parent START; do not retry or switch agents/routes based on current delegated message."+}
specs/development-isolation/t2384-source-checkpoint.json Added +59 / -0
diff --git a/specs/development-isolation/t2384-source-checkpoint.json b/specs/development-isolation/t2384-source-checkpoint.jsonnew file mode 100644index 00000000..72d4d4e2--- /dev/null+++ b/specs/development-isolation/t2384-source-checkpoint.json@@ -0,0 +1,59 @@+{+  "parent": "5e135d3dfc3cada13208c86fb5647b15352367ae",+  "API15Import": "fe1c57f",+  "verifiedIsolationSource": "9ba4297b9747673f3a39486e7ff66ced16f8b741",+  "pathGuardCorrection": "33b006a12a2d534d420a8b2cbb10ecd3a458096f",+  "sourceLint": {+    "files": 424,+    "violations": 0+  },+  "MCPModelsAndOwnerFixturesUnchanged": true,+  "branchRuntimeVerified": false,+  "sourceConflicts": [],+  "fileSHA256": {+    "Transit/Transit/TransitApp.swift": "d6cf9dcb0ae63527b1c87554ce4b57b25c5cbeed26609e148b63ed9379a7514d",+    "Transit/Transit.xcodeproj/project.pbxproj": "207934daaf68fae13c31519b428b8100e552a0a99353b0a8525ae6a4e2bd79cd",+    "Makefile": "43b2d9dafff57d65d7111f631b8688ba46d93bf86d087b0b3718bd23dd123e0d",+    "Transit/TransitTests/TestModelContainer.swift": "e8ace9bf519754289926bfc517c0fe4c9071f8e8dc3d05ccafa3df72a08387f5",+    "Transit/TransitTests/MCPBatchTaskEvidenceTests.swift": "2338dde5c77e8112ec82f2a451febb6fe86076b133f6a6c5f451a4616472dbc0",+    "Transit/TransitTests/MCPBatchTaskEncodingTests.swift": "f4ce1e66e09a47644f14b6a8f250c42c951a89e87710568cd51c76a5a0ea66a0",+    "Transit/Transit/MCP/MCPServer.swift": "06203ada49b19f12ce7f8451a17c89b59510841b78cb2e8bb3a2e716ee60ec51",+    "Transit/Transit/MCP/MCPOriginValidator.swift": "8d51448b7770741ef2ecbfb9844cee7040d5d4649cb4588c994869da1663c0ef",+    "Transit/Transit/MCP/MCPPortChangeCoordinator.swift": "32332acfa46792013b17b83e549071c89d2b49b62f1b50879a75defcaa682efa",+    "Transit/Transit/MCP/MCPTaskQuerySnapshotStore.swift": "dbf0e9e958db9649a5e7d54cade6114d1dad01cc004add946ae37cd35d935924",+    "Transit/Transit/MCP/MCPRequestContext.swift": "c2d158af8c5a8714f49b6df2586045eb2a048abc0074f1abd83d287ad5b88a20",+    "Transit/Transit/MCP/MCPSettings.swift": "3a523397dcce1bf2770f62414bac9cbd39c20f409663f1c9d54b5ae6bf8d8023",+    "Transit/Transit/MCP/MCPServerDecodeTypes.swift": "7d8243ee4e14ec1d4e8c4b7af5c29691ac3af9c592950fb43e696ba323d0edab",+    "Transit/Transit/MCP/MCPToolListChangeBroadcaster.swift": "8afa54367af4ded22a43acaca5f4692882d37511030a5d1430c4fe0c39dd4f66",+    "Transit/Transit/MCP/MCPServerLifecycleConfiguration.swift": "6cc4fddb83d78e9c6e86eb54ee074a7ba35f2473337212b7e017c50bb5057d86",+    "Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift": "f46e9ca6386c3d7740654ac7d38ddb82a33c8dcde4a17ec569727ad3413ceb16",+    "Transit/Transit/MCP/MCPToolDefinitions.swift": "9e9a57ede3b5b070c0098095bee23602cc079a75ba55b666df1780e3e12b583a",+    "Transit/Transit/MCP/MCPToolHandler.swift": "7f22d19518bd414c45ac21c11d2a706a73121fb87611313b487952fbab11862a",+    "Transit/Transit/MCP/MCPHelperTypes.swift": "df86f0ed2b5d1540878d55769a726e5421fa18b850ec6f040d41432491613709",+    "Transit/Transit/MCP/MCPTaskQueryRequest.swift": "6d413b6fcf2d816764ab98f6509c692ae7ff0d8aed8bbda833e61eb1c0bc550c",+    "Transit/Transit/MCP/MCPServer+Responses.swift": "c1da3a62420439cb6b7007a8871ff9ad2f45f4c06cabf4e7c7933a981b0e8bfb",+    "Transit/Transit/MCP/MCPTypes.swift": "6f792b5556c09927896755c8ffa95d3819f149015a14dd157fd6ec58a79c9aeb",+    "Transit/Transit/MCP/MCPServer+ToolListNotifications.swift": "0a6ea616cb23d54f325f1ab82c7338ea46e8c6ae303dd5f7b65f1120ae25e3cc",+    "Transit/Transit/MCP/BatchWrites/MCPBatchSavedReadContext.swift": "77e9cdaf66540095f5694b2845697a03f5272074392d3444e853cb051009286a",+    "Transit/Transit/MCP/BatchWrites/MCPBatchWritePolicy.swift": "bd487e8d387178b3c11f6cd48622176a82e6e383c4e155e649a03b0b6e22ce6b",+    "Transit/Transit/MCP/Writes/MCPWriteReceiptStore.swift": "1956f3368c974edab3a5c46a206c58544b8e125dd3a18917e2c7fee5f4041c9b",+    "Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift": "a1c040d1f007b1f2a3db27e64c2336c6670bac2b2e340204220414f92874a7d4",+    "Transit/Transit/MCP/Writes/MCPWriteOutcome.swift": "e124654549a55eb2299ca9b6a5f392b8160afba3b44e30d2b0c1cdcca579d628",+    "Transit/Transit/MCP/Writes/MCPWriteCoordinator+Outcomes.swift": "0c0be9257a69f38d953f442bf6eb01c21b473455c402c0ec56285415b4e36ccd",+    "Transit/Transit/MCP/Writes/MCPWriteCommand.swift": "9194fd0996b8874995f59681745d5dcbdcf468b56c5f621c47e96066b704132a",+    "Transit/Transit/MCP/Writes/MCPLocalReservationStore.swift": "b439b1a32f2d21fad7bdf42ddc593c6a06400335bf50ef71de1da690eea7dec2",+    "Transit/Transit/MCP/Writes/MCPCanonicalJSON.swift": "5ff40d70708ddaa510861e93e21b49489e197a956d02646690187c0e2cf34c96",+    "Transit/Transit/MCP/Writes/MCPRecordRevision.swift": "63a9401cfc2861b38f5b167cbd2e3f005b0bc8279c827bb3fb86f70feb91c0de",+    "Transit/Transit/MCP/Writes/MCPRecordSnapshot.swift": "777dcc06a4cec1855fa29d50e516472a40cb4528a4ad03bffb5f0bd04b4cc421",+    "Transit/Transit/MCP/Results/MCPResultSource.swift": "524fe680c37db3670d283bb1e02d8a48a15195dc9ffc8aaa8ff5712e62337068",+    "Transit/Transit/MCP/Results/MCPResultAdapter.swift": "b27522345f88c6a28a2a5ccc5d339bb89859bcecf794ced5e7f20314d3802254",+    "Transit/Transit/MCP/Results/MCPResultProviderSelection.swift": "49d54b6e3591c5e8eb37bb7c9d2779aa4d6309de055447a42ffb161e16dbdc62",+    "Transit/Transit/MCP/Results/MCPResultLinks.swift": "c31ec2298e3d90d56f71ba79a430eec94184a71876350e4b4ed0a7d277cf0036",+    "Transit/Transit/MCP/Results/MCPResultClassification.swift": "8d3664f62cce2e142174235e060a00bfb02d92cfc4b4f3b1b81c8b26968a7380",+    "Transit/Transit/MCP/Results/MCPResultInspection.swift": "5202d57c29a946a6e64ebb26ce5512f19aa1d5460a766141d30789af5c7fc2f1",+    "Transit/Transit/MCP/Results/MCPJSONDocument.swift": "7efd3387f8b262d2a253343ce976f562dab830fe7aa2954832c6a11e1fae725c",+    "Transit/Transit/MCP/Results/MCPResultSchemas.swift": "ebb3af861af669af946f0b94eb3b3c68fd276e4be9416b180545ba383cf20338",+    "Transit/Transit/MCP/Results/MCPResultEncoder.swift": "177abf4f9b5b6158047de2c0ff0ad179565d8a1d1c50027403a902d3aaa77127",+    "Transit/Transit/MCP/Results/MCPResultByteWriter.swift": "2aae6f485a5648c38bb83df76a2f7f5320d387d1e0b9ad66867c16020d6760c0"+  }+}
tests/batch-task-mutations/cleanup_preview_fixtures.py Added +148 / -0
diff --git a/tests/batch-task-mutations/cleanup_preview_fixtures.py b/tests/batch-task-mutations/cleanup_preview_fixtures.pynew file mode 100644index 00000000..700ce027--- /dev/null+++ b/tests/batch-task-mutations/cleanup_preview_fixtures.py@@ -0,0 +1,148 @@+"""Delete only marked Task7 fixture stores after their pinned run fully drains.++Default is validation/dry-run. Never call this in the test host: its centrally+retained ModelContainers may still hold SQLite files open.+"""+import argparse+import hashlib+import json+import math+import os+from pathlib import Path+import re+import shutil+import stat+import subprocess+import uuid+++MARKER = "T2384_TASK7_PREVIEW_DIRECTORY="+PREFIX = "T2384Task7Preview-"+GUARD = b"preview must not touch reservation evidence"+MAX_DIRECTORIES = 48  # 33 preview bodies plus 15 existing-service controls.+MAX_ENTRIES = 512+++def require(condition, message):+    if not condition:+        raise ValueError(message)+++def fixture_path(raw, temp_root):+    """Pure validation; exact direct-child path, canonical UUID, no links."""+    path = Path(raw)+    require(path.is_absolute() and str(path) == raw, "Noncanonical marker path")+    require(path.parent == temp_root, "Marker outside exact development temp root")+    suffix = path.name.removeprefix(PREFIX)+    require(path.name.startswith(PREFIX), "Not a Task7 fixture basename")+    require(re.fullmatch(r"[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}", suffix), "Invalid UUID")+    require(str(uuid.UUID(suffix)).upper() == suffix, "Noncanonical fixture UUID")+    require(temp_root.resolve() == temp_root, "Symlinked development temp root")+    require(path.resolve() == path and not path.is_symlink(), "Symlinked fixture path")+    require(path.is_dir(), "Missing fixture directory")+    count = 0+    directories = [path]+    while directories:+        with os.scandir(directories.pop()) as entries:+            for entry in entries:+                mode = entry.stat(follow_symlinks=False).st_mode+                require(stat.S_ISDIR(mode) or stat.S_ISREG(mode), "Nonregular or symlinked fixture entry")+                count += 1+                require(count <= MAX_ENTRIES, "Fixture entry count exceeds bound")+                if stat.S_ISDIR(mode):+                    directories.append(Path(entry.path))+    require((path / "untouched.guard").read_bytes() == GUARD, "Fixture ownership guard mismatch")+    require((path / "preview.store").is_file(), "Missing owned preview store")+    return path+++def exact_pid_absence(lines, pids, host, launch, result):+    """No signal is sent. Reject an active recorded PID or exact owned job."""+    for line in lines:+        values = line.strip().split(None, 1)+        if len(values) != 2 or not values[0].isdigit():+            continue+        pid, command = int(values[0]), values[1]+        require(pid not in pids, "Recorded owned PID still exists")+        require(not command.startswith(str(host)), "Owned isolated host is still live")+        owned_runner = "xcodebuild" in command and (str(launch) in command or str(result) in command)+        require(not owned_runner, "Owned test runner is still live")+++def marked_directories(text):+    require(text.count("◇ Test run started.") == 1 and "Restarting after unexpected exit" not in text,+            "Automatic replays or incomplete run markers require store preservation")+    markers = []+    for line in text.splitlines():+        if MARKER in line:+            require(line.startswith(MARKER), "Interleaved/noncanonical ownership marker")+            markers.append(line[len(MARKER):])+    require(0 < len(markers) <= MAX_DIRECTORIES, "Missing or excessive fixture markers")+    require(len(markers) == len(set(markers)), "Duplicate fixture ownership marker")+    return markers+++def validated_cleanup(repo, evidence_path, drain_path, readiness_path):+    evidence = json.loads(evidence_path.read_text())+    drain = json.loads(drain_path.read_text())+    readiness = json.loads(readiness_path.read_text())+    pin = evidence["sourcePin"]+    require(isinstance(pin, str) and re.fullmatch(r"[0-9a-f]{40}", pin), "Invalid source pin")+    require(pin == readiness["sourcePin"] == drain["sourcePin"], "Source/run/drain pins disagree")+    head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip()+    require(head == pin, "Current source pin differs from run")+    require(not subprocess.check_output(["git", "status", "--porcelain"], cwd=repo, text=True), "Dirty source")+    for section in ("ownedSource", "protectedSource"):+        for relative, digest in readiness[section].items():+            path = repo / relative+            require(path.resolve().is_relative_to(repo), "Source path escapes repository")+            require(hashlib.sha256(path.read_bytes()).hexdigest() == digest, "Source hash mismatch")+    require(evidence["declarations"] == 25 and evidence["bodies"] == 68, "Unexpected focused run inventory")+    log = Path(evidence["logPath"])+    require(log.resolve().is_relative_to(repo / ".codex-cache"), "Run log outside private artifacts")+    require(log.is_file() and not log.is_symlink() and log.stat().st_size <= 16 * 1024 * 1024,+            "Invalid or oversized run log")+    require(hashlib.sha256(log.read_bytes()).hexdigest() == evidence["logSHA256"], "Run log hash mismatch")+    text = log.read_text()+    require(drain["workerHostDrained"] is True and drain["ownedRemaining"] == [], "Drain proof is not clear")+    finished, drained = evidence["finishedAt"], drain["time"]+    require(all(isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)+                for v in (finished, drained)), "Invalid run/drain times")+    require(drained >= finished, "Drain proof predates run completion")+    pids = [evidence["runnerPID"]] + evidence["hostPIDs"]+    require(pids and len(pids) == len(set(pids)), "Invalid owned PID inventory")+    require(all(type(pid) is int and pid > 1 for pid in pids), "Invalid owned PID")+    derived = repo / "DerivedData/t2384-task3-red-run1"+    host = derived / "Build/Products/Debug/Transit.app/Contents/MacOS/Transit"+    name = evidence["runName"]+    require(isinstance(name, str) and re.fullmatch(r"Task7Red(?:Attempt[1-9][0-9]*)?", name), "Invalid run name")+    launch, result = Path(evidence["launchPath"]), Path(evidence["resultPath"])+    require(launch == derived / "Build/Products" / ("T2384" + name + ".xctestrun"), "Unowned launch path")+    require(result == derived / (name + ".xcresult"), "Unowned result path")+    lines = subprocess.check_output(["ps", "-axo", "pid,command"], text=True).splitlines()+    exact_pid_absence(lines, set(pids), host, launch, result)+    temp_root = Path.home() / "Library/Containers/me.nore.ig.Transit.development/Data/tmp"+    markers = marked_directories(text)+    paths = [fixture_path(marker, temp_root) for marker in markers]+    return paths+++def main():+    parser = argparse.ArgumentParser(description=__doc__)+    parser.add_argument("--run-evidence", required=True, type=Path)+    parser.add_argument("--drain-proof", required=True, type=Path)+    parser.add_argument("--readiness-hashes", required=True, type=Path)+    parser.add_argument("--delete", action="store_true", help="Otherwise validate without deleting")+    args = parser.parse_args()+    repo = Path(__file__).resolve().parents[2]+    paths = validated_cleanup(repo, args.run_evidence, args.drain_proof, args.readiness_hashes)+    if args.delete:+        require(shutil.rmtree.avoids_symlink_attacks, "Safe fd-based removal is unavailable")+        for path in paths:+            shutil.rmtree(path)+    print(json.dumps({"validatedDirectories": [str(path) for path in paths],+                      "count": len(paths), "deleted": args.delete, "signals": []}, indent=2))+++if __name__ == "__main__":+    main()
tests/development-isolation/DisposableStorePath.swift Added +31 / -0
diff --git a/tests/development-isolation/DisposableStorePath.swift b/tests/development-isolation/DisposableStorePath.swiftnew file mode 100644index 00000000..1813de9c--- /dev/null+++ b/tests/development-isolation/DisposableStorePath.swift@@ -0,0 +1,31 @@+import Foundation++/// Canonicalize existing directories symmetrically; a new leaf may resolve differently on macOS.+nonisolated enum DisposableStorePath {+    enum Failure: Error, Equatable { case invalidName, missingDirectory, outsideRoot, symbolicLink }++    static func resolve(path: String, rootPath: String) throws -> URL {+        let requested = URL(fileURLWithPath: path).standardizedFileURL+        guard requested.lastPathComponent == "synthetic.store" else { throw Failure.invalidName }+        let root = URL(fileURLWithPath: rootPath).standardizedFileURL+        let parent = requested.deletingLastPathComponent()+        let files = FileManager.default+        var rootIsDirectory = ObjCBool(false)+        var parentIsDirectory = ObjCBool(false)+        guard files.fileExists(atPath: root.path, isDirectory: &rootIsDirectory), rootIsDirectory.boolValue,+              files.fileExists(atPath: parent.path, isDirectory: &parentIsDirectory), parentIsDirectory.boolValue else {+            throw Failure.missingDirectory+        }+        let canonicalRoot = root.resolvingSymlinksInPath()+        let canonicalParent = parent.resolvingSymlinksInPath()+        guard canonicalParent.pathComponents.starts(with: canonicalRoot.pathComponents) else {+            throw Failure.outsideRoot+        }+        let candidate = canonicalParent.appendingPathComponent("synthetic.store")+        // Reject existing and dangling leaf symlinks before a store can be created or opened.+        guard (try? files.destinationOfSymbolicLink(atPath: candidate.path)) == nil else {+            throw Failure.symbolicLink+        }+        return candidate+    }+}
tests/development-isolation/MigrationProbe.swift Modified +42 / -3
diff --git a/tests/development-isolation/MigrationProbe.swift b/tests/development-isolation/MigrationProbe.swiftindex 398cecce..9cd15c2e 100644--- a/tests/development-isolation/MigrationProbe.swift+++ b/tests/development-isolation/MigrationProbe.swift@@ -9,9 +9,12 @@ struct MigrationProbe {         precondition(arguments.count == 3)         let mode = arguments[1]         let root = ProcessInfo.processInfo.environment["TRANSIT_DISPOSABLE_ROOT"]!-        let url = URL(fileURLWithPath: arguments[2]).standardizedFileURL.resolvingSymlinksInPath()-        let allowed = URL(fileURLWithPath: root).standardizedFileURL.resolvingSymlinksInPath().path + "/"-        precondition(url.path.hasPrefix(allowed) && url.lastPathComponent == "synthetic.store")+        let url = try DisposableStorePath.resolve(path: arguments[2], rootPath: root)+        if mode == "path-guard" {+            try verifyPathGuard(root: URL(fileURLWithPath: root))+            print("Path guard checks passed: aliases, new/existing leaves, escape and symlink rejection")+            return+        }         var models: [any PersistentModel.Type] = [             Project.self, TransitTask.self, Comment.self, Milestone.self, SyncHeartbeat.self         ]@@ -54,6 +57,42 @@ struct MigrationProbe {         }     } +    static func verifyPathGuard(root: URL) throws {+        let files = FileManager.default+        let allowed = root.appendingPathComponent("guard-allowed", isDirectory: true)+        let sibling = root.appendingPathComponent("guard-allowed-sibling", isDirectory: true)+        try files.createDirectory(at: allowed, withIntermediateDirectories: true)+        try files.createDirectory(at: sibling, withIntermediateDirectories: true)+        let leaf = allowed.appendingPathComponent("synthetic.store")+        let new = try DisposableStorePath.resolve(path: leaf.path, rootPath: allowed.path)+        let alias = allowed.resolvingSymlinksInPath()+        let aliased = try DisposableStorePath.resolve(path: leaf.path, rootPath: alias.path)+        precondition(aliased == new)+        try Data().write(to: new)+        let existing = try DisposableStorePath.resolve(path: leaf.path, rootPath: allowed.path)+        precondition(existing == new)+        func rejects(_ path: URL, expected: DisposableStorePath.Failure) throws {+            do {+                _ = try DisposableStorePath.resolve(path: path.path, rootPath: allowed.path)+                fatalError("Unsafe path accepted")+            } catch let error as DisposableStorePath.Failure {+                precondition(error == expected)+            }+        }+        try rejects(sibling.appendingPathComponent("synthetic.store"), expected: .outsideRoot)+        try rejects(allowed.appendingPathComponent("wrong.store"), expected: .invalidName)+        try rejects(allowed.appendingPathComponent("missing/synthetic.store"), expected: .missingDirectory)+        try files.removeItem(at: new)+        try files.createSymbolicLink(at: leaf, withDestinationURL: sibling.appendingPathComponent("missing.store"))+        try rejects(leaf, expected: .symbolicLink)+        try files.removeItem(at: leaf)+        try files.createSymbolicLink(at: leaf, withDestinationURL: sibling)+        try rejects(leaf, expected: .symbolicLink)+        let escape = allowed.appendingPathComponent("escape", isDirectory: true)+        try files.createSymbolicLink(at: escape, withDestinationURL: sibling)+        try rejects(escape.appendingPathComponent("synthetic.store"), expected: .outsideRoot)+    }+     @MainActor static func verifyConfiguration(         schema: Schema, configuration: ModelConfiguration, url: URL     ) throws {
tests/development-isolation/run.py Modified +3 / -0
diff --git a/tests/development-isolation/run.py b/tests/development-isolation/run.pyindex 8d2650e5..afd94ea7 100644--- a/tests/development-isolation/run.py+++ b/tests/development-isolation/run.py@@ -38,6 +38,9 @@ def main():          configuration_root = root / "configuration"         configuration_root.mkdir()+        results["pathGuard"] = execute("path-guard", configuration_root / "synthetic.store")+        if results["pathGuard"]["exit"]:+            raise RuntimeError(results["pathGuard"])         results["configuration"] = execute("configuration", configuration_root / "synthetic.store")          def metadata(store):

Docs (29)

CHANGELOG.md Modified +2 / -0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9399bb18..870b540d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).  ### Added +- T-2384: Add `mutate_tasks` for saved-only advisory preview and 1–50 ordered task updates, status-plus-comment changes or comments. Items retain independent revision/receipt/retry boundaries, stop after the first unsuccessful result, preserve complete original evidence and select a preencoded correlated recovery fallback after encoding failure. Fresh macOS, isolated iOS unit and UI suites pass; reviewed UI fixture corrections retain navigation/layout assertions. Installed-client activation remains deferred.+ - T-2382: Complete portfolio regression coverage and caller guidance for saved summary counts, half-open completion windows and activity, with reusable frozen task queries. Remove the obsolete unused scaffold error.  - T-63: MCP reads capture saved local data with explicit capture/import metadata, cached or bounded-refresh policies, a five-second response budget and physical admission retained through late cleanup. Frozen pages preserve their original evidence. Bounded phase diagnostics and caller guidance cover failures, backoff and unsupported force-pull limits.
CLAUDE.md Modified +3 / -2
diff --git a/CLAUDE.md b/CLAUDE.mdindex 13fa2cf9..8a8765a7 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -138,15 +138,16 @@ Shared intent infrastructure lives in `Intents/Shared/`: entities (`ProjectEntit  ### MCP Server (macOS only) -HTTP-based JSON-RPC 2.0 server using **Hummingbird**, gated behind `#if os(macOS)`. Configured via `MCPSettings` (UserDefaults-backed toggle and port). Exposes 12 normal tools:+HTTP-based JSON-RPC 2.0 server using **Hummingbird**, gated behind `#if os(macOS)`. Configured via `MCPSettings` (UserDefaults-backed toggle and port). Exposes 13 normal tools: -`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`+`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`, `mutate_tasks`  Key implementation files: - `MCP/MCPServer.swift` — Hummingbird router, lifecycle management - `MCP/MCPToolHandler.swift` — dispatches `tools/call` to service layer - `MCP/MCPToolDefinitions.swift` — tool schemas with input validation - `MCP/MCPTypes.swift` — shared JSON-RPC types; exposed transport is latest-only `2026-07-28` via `MCP/Protocol` and `MCPServer+Routing.swift`+- `MCP/BatchWrites/` — saved-only mutation previews and ordered per-item protected writes; no whole-batch receipt or transaction - `MCP/Results/` — immutable source/presentation, output schemas and complete response/fallback encoding - `MCP/Reads/` — bounded capture/admission/deadline/publication services - `MCP/MCPHelperTypes.swift` — query filter logic (`MCPQueryFilters`)
README.md Modified +6 / -4
diff --git a/README.md b/README.mdindex 242e57a2..6f3d2ce9 100644--- a/README.md+++ b/README.md@@ -16,7 +16,7 @@ Transit sits alongside the existing tool ecosystem: [Orbit](https://github.com/A - **Reports** — generate summary reports of completed/abandoned tasks by date range - **Cross-device sync** via CloudKit private database - **CLI automation** through App Intents — create tasks, update statuses, manage milestones, add comments, generate reports-- **MCP server** (macOS) — HTTP JSON-RPC server for AI agent integration with 12 normal tools+- **MCP server** (macOS) — HTTP JSON-RPC server for AI agent integration with 13 normal tools - **Agent handoff statuses** (Ready for Implementation, Ready for Review) for AI/human workflow integration - **Adaptive layout**: width-based multi-column Kanban on iPhone/iPad/Mac, with a segmented single-column fallback only when one column fits - **Drag and drop** between columns to change task status@@ -64,13 +64,15 @@ All intents accept a JSON string input and return a JSON string response, includ  ## MCP Server (macOS) -Transit includes a built-in MCP server on macOS for AI agent integration. Enable it in Settings and configure the port (default: 3141). The server exposes 12 normal tools over latest-only MCP `2026-07-28` HTTP JSON-RPC 2.0:+Transit includes a built-in MCP server on macOS for AI agent integration. Enable it in Settings and configure the port (default: 3141). The server exposes 13 normal tools over latest-only MCP `2026-07-28` HTTP JSON-RPC 2.0: -`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`+`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`, `mutate_tasks`  **Breaking transport change:** Older MCP clients using `initialize`, session negotiation, GET streams or JSON-RPC wire arrays are unsupported. Requests require the modern headers and `_meta` fields described in the [MCP result contract](docs/mcp-result-contract.md). Missing required metadata returns an explanatory HTTP 400 protocol error; an otherwise valid modern `initialize` request returns HTTP 404 / JSON-RPC method-not-found. Actual installed-client compatibility remains unverified. -The eight write tools require an `idempotencyKey`. Task/milestone updates and milestone deletion also require the target's current `expectedRevision`. Read a revision before updating, and retry an interrupted request with the same key and arguments. Responses use structured saved-record outcomes; see the [MCP write contract](docs/mcp-write-contract.md) for examples, seven-day replay retention, conflicts, and local-store limits. See the [MCP result contract](docs/mcp-result-contract.md) for structuredContent, modern request headers and recovery. See the [bounded read contract](docs/mcp-read-contract.md) for saved capture freshness, policy, deadlines and retry guidance. See the [portfolio contract](docs/mcp-portfolio-contract.md) for project summaries and task queries over the same frozen snapshot. Actual installed-client compatibility is deferred to post-merge MacBook validation and remains unverified. App Intent inputs are unchanged.+`mutate_tasks` accepts one application batch of 1–50 task updates, status updates or comments, with saved-only advisory previews and ordered per-item outcomes. See the [batch mutation contract](docs/mcp-write-contract.md#application-batch-task-mutations) for stopping, replay and recovery rules.++The eight standalone write tools require an `idempotencyKey`. Task/milestone updates and milestone deletion also require the target's current `expectedRevision`. Read a revision before updating, and retry an interrupted request with the same key and arguments. Responses use structured saved-record outcomes; see the [MCP write contract](docs/mcp-write-contract.md) for examples, seven-day replay retention, conflicts, and local-store limits. See the [MCP result contract](docs/mcp-result-contract.md) for structuredContent, modern request headers and recovery. See the [bounded read contract](docs/mcp-read-contract.md) for saved capture freshness, policy, deadlines and retry guidance. See the [portfolio contract](docs/mcp-portfolio-contract.md) for project summaries and task queries over the same frozen snapshot. Actual installed-client compatibility is deferred to post-merge MacBook validation and remains unverified. App Intent inputs are unchanged.  ## Documentation 
docs/mcp-write-contract.md Modified +40 / -3
diff --git a/docs/mcp-write-contract.md b/docs/mcp-write-contract.mdindex 3b932484..4477008b 100644--- a/docs/mcp-write-contract.md+++ b/docs/mcp-write-contract.md@@ -61,9 +61,46 @@ exclude child collections. No-ops keep their revision; restoring identical cover the same token. Tokens are neither timestamps nor monotonic counters. Edits not yet imported from CloudKit cannot be detected, and later sync merges can still conflict. -These outcome and revision semantics are shared vocabulary for T-2384. They introduce no batch-mutation application or dry-run behavior. Wire-level JSON-RPC arrays are rejected. A T-2384 application batch, when delivered by its owner, is one tools/call with its separate per-item effect policy.-+## Application batch task mutations++`mutate_tasks` is one `tools/call`, not transport batching. Wire-level JSON-RPC arrays remain rejected.+Supply explicit `mode:"dry_run"` or `mode:"execute"` and 1–50 ordered `items`. Each item has a nonempty+opaque `itemId`, an `operation` (`update_task`, `update_task_status` or `add_comment`) and the original+protected tool's `arguments`. Task UUIDs must be unique after UUID normalization, item IDs must be+unique by exact spelling, and tool/key pairs must be unique. Updates require `expectedRevision`;+comments reject that field. Unknown fields, malformed safety values and wrong JSON types reject the+whole input before effects. Domain strings such as status, priority and type are validated per item.++Dry runs read saved local records, ignoring pending UI inserts, edits and deletions. They return+advisory proposals with `observation:"saved_local_store"` and `keyState:"unchecked"`; they neither+reserve keys nor establish replay availability. Full comment state determines the canonical `r1`+even when comment payloads are omitted. A later save can invalidate that revision.++Execution applies items in order and advances only after established committed evidence. The first+rejection, active or uncertain outcome, pending-edit stop, unavailable evidence or cancellation stops+later items. Each successful item commits independently; the batch is not a transaction. There are+no automatic retries or rollbacks of earlier commits. `not_attempted` describes this invocation,+not the history of that key. Original per-item JSON, text, optional `isError`, revisions and retry+instructions remain authoritative; aggregate `isError` does not replace them.++There is no whole-batch receipt or replay key. Recover each attempted item with its original tool,+arguments, key and originating local store. Regrouping items does not change protected request+identity. An identical batch retry may replay earlier committed items and execute previously+`not_attempted` items, stopping again at the first unsuccessful item. Exclude a retained no-effect+rejection, or correct its arguments with a fresh key, before expecting later items to proceed. A historical canonical replay certifies its saved outcome, not current task contents.+A removed or absent receipt does not prove that the original operation had no effect. If new duplicate closures require the canonical task to still match the plan, reconcile current+canonical records and original evidence before submitting those closures. Historical replay does not+establish that current-state condition.+Respect each known seven-day expiry and retain the original first-submission time. When that time+or acceptance evidence is lost, reconcile rather than assuming a fresh execution is safe. Retrying+a removed key after expiry can repeat effects, including comments. Never rotate keys automatically+for unknown outcomes.++Lost responses and cancellation do not undo effects. If aggregate encoding fails after dispatch,+the already prepared `summary:"serialization_failed"` fallback contains the correlated original+indexes, operations, tools, keys and UUIDs, with unestablished effect evidence. Reconcile those keys;+do not infer no effect from a failed response. Installed-client validation and activation remain+deferred to post-merge MacBook checks.  ## Recovery when local retry storage is unreadable 
specs/OVERVIEW.md Modified +18 / -0
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex a3b96685..13afb2c1 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -39,6 +39,7 @@ | [Structured MCP Results](#structured-mcp-results) | 2026-10-03 | Ready for Review | Structured/text results and latest-only transport locally verified; client compatibility explicitly deferred post-merge | | [Bounded Read Freshness](#bounded-read-freshness) | 2026-10-03 | Done | Bound MCP read completion and report immutable saved capture/import evidence | | [Portfolio Summaries](#portfolio-summaries) | 2026-10-04 | Done | Saved portfolio counts and reusable frozen task views; qualified native verification complete |+| [Batch Task Mutations](#batch-task-mutations) | 2026-10-04 | Done | Saved-only previews and ordered per-item MCP task writes; fresh native verification complete, publication pending |  --- @@ -423,3 +424,20 @@ T-2382 completes regression coverage and caller guidance for the portfolio imple - [Tasks](portfolio-summaries/tasks.md) - [Implementation](portfolio-summaries/implementation.md) - [Acceptance qualifications](portfolio-summaries/integration-acceptance.md)++## Batch Task Mutations++T-2384 provides `mutate_tasks` as one modern application tool call with advisory saved-only previews and ordered per-item protected writes. Original receipts, revision checks and retry evidence remain authoritative; complete preencoded fallback protects post-effect serialization failure. All 14 tasks and fresh macOS/iOS/UI acceptance are complete locally. Client readiness and specific publication/disclosure approvals remain separate release boundaries.++- [Scope](batch-task-mutations/scope.md)+- [Requirements](batch-task-mutations/requirements.md)+- [Design](batch-task-mutations/design.md)+- [Tasks](batch-task-mutations/tasks.md)+- [Decision log](batch-task-mutations/decision_log.md)+- [Implementation explanation and evidence](batch-task-mutations/implementation.md)+- [Three-level explanation](batch-task-mutations/explanation.md)+- [Final critical review](batch-task-mutations/final-critical-review.md)+- [Original native acceptance](batch-task-mutations/task14-green-actual.json)+- [Fresh reconciled publication verification](batch-task-mutations/publication-verification.json)+- [Final handoff](batch-task-mutations/final-handoff.md)+- [Local pre-push review archive](batch-task-mutations/local-review.json)
specs/batch-task-mutations/decision_log.md Added +172 / -0
diff --git a/specs/batch-task-mutations/decision_log.md b/specs/batch-task-mutations/decision_log.mdnew file mode 100644index 00000000..4419851e--- /dev/null+++ b/specs/batch-task-mutations/decision_log.md@@ -0,0 +1,172 @@+# Decisions: Batch Task Mutations++## Quick Decisions++| ID | Date | Decision | Rationale / evidence | Status |+| --- | --- | --- | --- | --- |+| Q1 | 2026-10-03 | Use full Starwave specs; feature name `batch-task-mutations`. | User: “2384 fully approved” in parent, `Sentinel_4fd40b3fecf48191a57ce03897d3e7ec`, approving the scope/name gate. | Approved scope. |+| Q2 | 2026-10-03 | Create isolated branch/worktree before later gates. | Explicit initial delegation; base `201205bd4e786c7f152d8f99006b37da7da888c7` verified against main/origin/main. | Authorised setup; no implementation approval. |+| Q3 | 2026-10-03 | Use design critic then internal peers for formal reviews. | External disclosure remains unauthorised; local peer-review-validator documents internal subagent fallback. PERSONAL_PROJECTS=1 does not override user disclosure restrictions. | Required review mode. |+| Q4 | 2026-10-03 | T63 owns existing MCPServer/MCPTypes/common dispatch/schema wiring until handoff. | Delegation and approved T63/T2382 read-only designs. | Coordination constraint. |+| Q5 | 2026-10-03 | T2383 adapter preserves historical T2380 terminal JSON and outcome meaning. | T2383 coordination message: preserve text, unknown/missing fields, accepted/outcome/retryAction; no live reread or terminal receipt rewrite. Latest-only T2383 scope and requirements are approved; its serializer design remains unapproved. | Shared constraint; concrete envelope still proposed. |++## ADR 1: Per-item commits and stop-on-first-unsuccessful execution++Status: approved requirements decision at `Sentinel_35dae4e67398819184369b41649ec75b`.++Context: canonical task updates must precede duplicate closure. Existing T2380 guarantees attach to a protected tool/item key with acceptance and terminal result persisted in the originating store. Whole-batch atomicity would require a different persistence/recovery boundary and cannot promise global CloudKit ordering.++Decision: propose ordered independent item commits and stop after the first rejected/in_progress/uncertain item; return unstarted items explicitly. Batch retries use item keys and can continue past earlier committed replays. A retained rejection must be excluded or corrected with a fresh key after review before later items can proceed; transient rejection may instead direct same-request retry. Only understood authoritative commitment permits progression. Unknown/unreadable outcomes stop the batch without assigning a fabricated receipt state.++Alternatives: whole-batch local transaction (different receipt design, larger recovery scope); continue after rejection (allows closure after failed canonical update); compensating rollback (creates new effects and conflicts).++Consequences: earlier effects survive later failure; one submission is not globally atomic. A lost aggregate response needs item reconciliation. The user must approve the exact behavior in requirements before design.++## ADR 2: Stable item targets and no within-batch revision chaining++Status: approved requirements decision at `Sentinel_35dae4e67398819184369b41649ec75b`.++Context: repeated updates to a task change its revision, and display-ID/UUID aliases complicate duplicate detection and replay identity. The motivating status-plus-reason effect already exists as an atomic T2380 item.++Decision: propose task UUID selectors only, one operation per normalized target UUID per batch, and caller-supplied operation key/revision. Multiple changes to the same task use existing combined status/comment or a later call.++Alternatives: allow repeated targets with literal revisions (later revisions generally stale); predicted revision chaining (new contract and coupling); combined update/status/comment item (new atomic operation beyond existing protected tools).++Consequences: simple stable payload identity and shape checks before execution, at the cost of another call for separate same-task property/comment edits. Limit 50 is proposed as a bounded initial API choice, not a performance claim.++## ADR 3: Advisory preview without receipt inspection++Status: approved requirements decision at `Sentinel_35dae4e67398819184369b41649ec75b`.++Context: dry run must not mutate guard/receipt state or trigger recovery. T2380 matching-key replay can legitimately return a historic commit when the current target has changed or disappeared.++Decision: propose validation of current local domain state only, all-item diagnostics, proposed normalized changed fields, and explicit unchecked key state. Do not simulate saved timestamps/UUIDs/revisions or promise durable availability. Execute replays first under the authoritative write contract, or validates a new write independently.++Alternatives: reserve keys/revisions during preview (violates no-write preview); inspect/recover receipts (adds recovery side effects and unavailable-store complexity); label preview as future commitment guarantee (false under concurrent local changes/sync).++Consequences: a stale or missing current target can yield an invalid preview while a retained submission replay remains committed. Current state success does not certify key availability or future write durability.++## Requirements review resolutions++| Finding | Resolution | Basis |+| --- | --- | --- |+| Critic: unknown/unreadable item result could continue execution | Stop unless authoritative commitment is understood; preserve available original text/flag and correlate not_attempted items. | Prevent further effects after an unverified result; classification remains receipt-owned. |+| Critic: historical nested isError omitted | Preserve item result flag separately from aggregate error flag. | T2380 resultJSON/resultIsError are authoritative. |+| Critic: transient responses described as durable outcomes | Advance only on confirmed commitment; no terminal-retention claim for transient responses. | Existing accepted:false retry_same_request responses do not imply a terminal receipt. |+| Critic: shape/domain boundary and failed-item correlation ambiguous | Type/safety formats fail whole shape; invalid enum domain values or missing status-comment author fail individual items; diagnostics include index. | Matches existing protected write stage distinctions. |+| Critic: UUID normalization could alter request binding | Normalize only collision detection/mapping, preserve original arguments. | T2380 canonical JSON binds the original UUID string; case changes are not silently rewritten. |+| Self-review: caller timeout versus server interruption | Define interruption by observed cancellation/execution failure. | Lost delivery alone cannot prove whether server continued. |++| Peer API: preserve unknown historic JSON and raw text bytes | Require complete lossless nested outcome/raw-text preservation without fixing serializer schema. | T2383 adapter must not drop historic fields or reconstruct authoritative original text. |+| Peer recovery: missing first-response expiry | Explain submission-time context, unknown protection duration and absent-receipt non-proof; cover response loss then receipt removal in tests. | T2380 allows expired removed keys to execute anew; client must reconcile rather than assume indefinite protection. |+| Peer recovery: old canonical replay before new closures | Explain replay is commit-time evidence, not certification of current canonical contents; caller reconciles stronger workflow conditions. | Preserve replay-first guarantee and avoid adding implicit revalidation or whole-batch atomicity. |++## T2383 latest-only scope coordination++T2383 reported explicit user approval of latest 2026-07-28 only, with no legacy transport, for its scope/name gate. Its requirements are approved; its serializer interface remains under design review. T2384 remains one application-level tools/call and does not require JSON-RPC transport arrays; requirement 6.4 refers to the transport ordering supported by that approved protocol contract. Supplemental classifications and links must stay separate from historical data even if unknown keys collide. Exact envelope/interface remains a design coordination item; T63 still owns the shared transport handoff. T2383 reported installed-client readiness as a blocker; T2384 has changed no client configuration. This coordination does not approve T2384 requirements or T2383's unseen design.++## Design gate context++Requirements at `9b5122c` were explicitly approved by user: “2384 requirements approved”, `Sentinel_35dae4e67398819184369b41649ec75b`. T2383 requirements approval was verified separately at `Sentinel_39b0ca45b1b8819180ac6d9600578f0b`; its design remains under review. Both facts are approvals of requirements, not implementation.++## ADR 4: Reuse receipt execution with a batch-only commit validation policy++Status: proposed design decision.++Context: `TaskService.findByID` selects the first UUID match. A preflight lookup before calling the coordinator could reject a valid historical replay, and a lookup before an await could miss a new ambiguity.++Decision: add an optional internal batch-only validation callback to coordinator execution, evaluated synchronously in the existing fresh commit phase immediately before domain apply. The callback validates one live task for the UUID. Replay and active-key outcomes bypass it. Default nil preserves existing callers; no key arguments, reservation/receipt stores, recovery or schema versions change.++Alternatives: global service lookup change (changes standalone behavior); separate batch receipt engine (duplicates safety); pre-call identity check (breaks replay-before-live-state and leaves a race).++Consequences: small coordinator integration edit with targeted replay/commit tests, without a new transaction boundary or guard subsystem.++## ADR 5: Saved-only non-saving preview context++Status: proposed design decision aligned with explicit owner constraint.++Context: owner said “If something isn't saved, it shouldn't be returned” at Sentinel_bb00a4d9d8688191a33a0e6a34ea38db. Approved AC2.1 does not require pending values; AC2.2 requires pending state remain unchanged. Existing shared service context is container.mainContext and T2380 can save its baseline changes.++Decision: preview owns a fresh ModelContext over the persistent container, autosave disabled and pending changes excluded. Validator services use that context. Unsaved UI values are never copied/output or flushed. Label saved_local_store observation and advisory difference from later saves/imports. Temporary fallback records are not returned as saved evidence.++Alternatives: shared context pending-value preview (contradicts owner); saving pending UI state before preview (violates AC2.2); mutate-and-rollback preview (risks unrelated edits).++Consequences: preview can describe saved data that differs from pending UI forms; execution cannot flush those forms and stops while shared context is dirty. Changes saved independently after preview can invalidate revisions.++## ADR 6: Stop batch writes rather than flush unrelated UI edits++Status: proposed design decision implementing owner no-flush constraint.++Context: TransitApp injects container.mainContext into existing services/coordinator; its fresh acceptance/commit/recovery phases can save baseline pending changes. Checking only the outer loop misses UI edits arising during awaited preparation.++Decision: batch-only execution policy requires a clean shared context at fresh synchronous phase boundaries, before baseline/recovery/rejection saves. Default nil retains standalone behavior. Dirty context first uses the existing store APIs for read-only retained terminal replay/key-reuse detection, with no repair/recovery/task reads. New acceptance or unresolved recovery is blocked; postaccept dirty detection returns uncertainty without flushing/rollback/terminal save. Accepted bindings remain retained, using existing recovery when context is independently clean.++Alternatives: globally replace all MCP services with an isolated context (larger existing-write behavior change); separate batch reservation/receipt engine (duplicates safety); save/rollback dirty context (violates owner instruction).++Consequences: dirty UI state temporarily prevents new batch writes or unresolved recovery through this shared context, while valid saved replay/key conflicts remain available; conservative uncertainty never implies no effects or fresh-key permission. Policy must cover every post-await cancellation/error path, not merely pre-apply identity check. TDD fixtures are required before integration; no guard storage format/files or new recovery implementation is changed.++## Quick Design Decisions++| ID | Decision | Rationale / status |+| --- | --- | --- |+| Q6 | Proposed public tool `mutate_tasks`, mode plus nested explicit operations. | Parent asked for naming preference; concrete design gate owns approval. No outer durable key. |+| Q7 | Batch-local immutable result evidence and logical aggregate adapt once via T2383. | T2383 proposed MCPResultSource + collision-free source/presentation wrapper; exact common API remains its design gate. Avoid inventing common production signatures. |+| Q8 | Pre-encode a compact recovery fallback before executing any item. | Full aggregate encoding can fail after durable effects. Fallback uses input indexes/tool/key/UUID and reconciliation direction, not fabricated receipt classification. |+| Q9 | Generated property tests with seeded cases in Swift Testing. | Existing toolchain; no dependency or build introduced during design. |++## Design critic resolutions++| Finding | Resolution |+| --- | --- |+| Fallback could invoke failed common encoder again | Prepare complete deliverable modern HTTP body bytes via the agreed T2383/T63 adapter before effects; selection is encoding-free. No shared adapter contract means no batch execution. |+| Commitment predicate underspecified | Enumerate strict v1 types/tool/key/identities/revisions/error-flag/terminal-date checks. Current expiry affects replay protection, never established commitment. |+| Cancellation lacks blocker before first/between items | Explicit stop reason/next-unstarted index/optional blocker. Noncommitted returned result retains precedence; all committed wins after-last cancellation while delivery may be suppressed. |++## Owner saved-only amendment and peer clarifications++The initial design's pending-observation preview was replaced after explicit owner evidence arrived, not approved by the prior peer reviews. Amended design requires fresh saved-only preview and clean shared-write phases to avoid flushing unrelated UI edits. No approved requirement mandates unsaved observation, so the requirements gate is not reopened. Repeat critic and both peer reviews cover the amendment before design gate.++Batch domain status/type/priority schemas use descriptive allowed-value lists without enum/const constraints; invalid string values remain item-domain errors. Fallback logical summary is serialization_failed with batch effect evidence unestablished; T2383's phrase outcome_unknown denotes this recovery meaning, not a second T2384 field/outcome namespace.++Amended critic identified AC4.2 conflict in a receipt-blind outer dirty block. Resolved with a non-mutating terminal-inspection branch of the existing coordinator using existing binding/durable-receipt lookup/validation. Valid terminal replay and key mismatch remain available while dirty; unresolved evidence/new acceptance is unavailable. Added an explicit table for every baseline/save/rollback/recovery route and direct-return-before-phase rule so unrelated UI edits cannot enter rollback handlers. No availability exception to approved replay is proposed.++## Final design review synthesis++Critic and two independent internal peers re-reviewed the saved-only/dirty-context amendment and cleared the design gate. They agree AC4.2 terminal replay/key conflicts remain available read-only while dirty; every fresh phase has direct-return guards before save/rollback/recovery handlers. Required early fixtures cover dirty committed/rejected replay, mismatched payload, missing/inconsistent sidecar, expired/unresolved evidence, and both post-await preparation continuations. Complete fallback, exact evidence predicate, schema/domain boundary and cancellation precedence are settled design instructions. No external services or implementation tests were used. Numeric version predicate follows T2380 canonical value equality (1 and 1.0 equivalent), not Boolean/string coercion.++## Design approval and task planning++Owner approved T2384 design `a5950e9` and T2383 design `7970a9c` in parent: “2383 and 2384 are approved” (`Sentinel_717be95229c48191a7c41b6e5e467e4c`). ADR4–6 and Q6–9 are approved design decisions. Proceed to Rune task planning only; task and implementation approvals remain outstanding. T63 owns shared wiring and heavy-test slot. Noncircular seam order is T63 handoff → T2383 common source/encoder/schema/fallback delivery tested with synthetic aggregate → T2384 consumer/registration tests. T2383 common delivery never depends on production batch integration. Single stream avoids conflicting coordinator/integration edits.++## Task plan review resolutions++Actual Rune authored 14 pending tasks, seven adjacent RED/GREEN pairs, one stream and stable-ID blocked_by relationships. All 32 AC anchors are covered; graph has no cycles. Critic first then recovery and integration peers cleared after clarifying new effect allocation versus parsing saved values, post-await versus impossible synchronous UI interleaving, named external API gates and actual MCP/Writes source paths. No scope/design change or source implementation is included. Task approval remains pending; only separate implementation authorisation may start coding, with T63 ownership/slot and T2383 delivery conditions preserved.++T2383 current Rune draft IDs verified read-only: source3/gpzncvn, presentation5/gpzncvp, bytes7/gpzncvr, schema9/gpzncvt, shared delivery15/gpzncvz. Batch consumer gate requires delivered15 commit/interface and these components, not design or task approval alone. T2383 final22/gpzncw6 does not wait on production batch. No dependency direction or scope changes.++## Task and conditional implementation approval++Parent verified owner “Approved” (`Sentinel_edf7fd12288c819192ad45a04154372a`) to “Do the tasks look good, and may it proceed with implementation once its shared dependencies are ready?” for plan d592907. Tasks are approved and implementation is conditionally authorised. Begin independent task1 safety fixtures only; coordinator edits await parent ownership agreement, common consumer tasks await DELIVERED T2383 task15/interface, heavy app tests await parent grant (T2382 owns current slot). Use actual make-it-so single-subagent delegation and approved Rune DAG. No settings/activation/push/merge/deployment approval is inferred; full prepush/Pulsar review remains completion gate.++## Implementation ownership confirmation++Parent confirmed T63 has no active write-coordinator changes and granted T2384 sole ownership of MCP/Writes/MCPWriteCoordinator.swift and coordinator-specific tests for the approved batch-only policy. T63 retains common read/server/types ownership. T2383 task/implementation approval is now granted but delivered task15 is still future; no consumer integration claim follows from approval. Heavy-test slot remains T2382 until parent grants it. Task1 fixture drafting is in progress, and its verified RED remains outstanding.++## Shared source resource cap coordination++T2383 owner approved a 32-container parser-input depth cap at Sentinel_9536d4df532c81919792e70801f128fb (amendment4a9d1be): root object/array counts1, scalar0. Over-cap retained source preserves original raw text/isError with unreadable/unestablished parsed evidence; no receipt rewrite. A readable original receipt can exceed32 after batch wrapper containers are added, so generated aggregate resource failure after effects selects the already prepared shallow complete serialization_failed bytes, never no-effect/fresh-key advice. Giant itemId/raw record/entity link data must not leak into compact fallback through common presentation/context. These are explicit consumer fixtures for existing AC5.2–5.4, not task15 delivery or guessed implementation. Shared delivery remains future.++## Verified API15 consumer preparation++Read-only verification now finds T2383 DELIVERED15 handoff `b21e358c8a5ea1e287afe332c1fc50d83303ce19`, runtime source `543c4a757e4cb7f9f73c973d7cb1be5725c8f342`. All 28 common files and 21 retained-owner files match their runtime manifest hashes. The consumer external delivery prerequisite is satisfied; later common tasks16–22 remain separate obligations. Preserve the reported verification limits: 98 passing bodies from the earlier unfinalized run plus two finalized corrected passes, without claiming a single clean finalized100 run.++Exact ten-file pure source/encoder dependency import is committed in `fe1c57f`. `api15-consumer-import.json` records hashes and confirms the coordinator, App, project and Makefile were preserved byte-for-byte. This import does not deliver modern server registration, retained-read integration or the approved isolated host setup. Task3 RED fixture drafting consumes the actual source/encoder declarations; no GREEN implementation or runtime verification is implied.++The ticket worktree still differs from the delivered isolated development target in App bootstrap, project/schemes, persistence helpers and signed-host preflight. Do not execute the old test-quick host. Before app-host RED execution, obtain the exact owner-coordinated isolation patch, apply it without importing unrelated read/server wiring, verify target and signed-host safeguards, then request the exclusive focused test slot through the parent. Live writes, activation and production launch remain held.+++## Final implementation acceptance++All 14 approved tasks are complete at worker evidence commit `0298daa4`; tested source is `5c42c7e`. Parent-approved shared handoff and the verified T63/T2383/T2382 baseline were integrated without competing ownership. Four internal reviewers and the root cleared the actual modern batch route, complete fallback and historic evidence boundary. Fresh finalized full macOS 2409/3049, isolated iOS unit 1289/1334 and UI 21/24 acceptance passed with no failures, skips or native runtime warnings; full lint passed. Actual proof and 31 independently verified artifact hashes are in `task14-green-actual.json`. No external review service, production write, client activation, push or merge occurred. Later T1734 scope remains separate; client readiness and specific publication/disclosure approvals remain release boundaries.++Local pre-push HTML was generated by the installed renderer and archived by Pulsar with exit0 at the path recorded in `local-review.json`. Source inspection established local file-only archive behavior; no external peer-review/forge request or global configuration change was made. Root completed the single phase changelog and overview/explanations; final handoff distinguishes local acceptance from publication/client gates.
specs/batch-task-mutations/design-review.md Added +44 / -0
diff --git a/specs/batch-task-mutations/design-review.md b/specs/batch-task-mutations/design-review.mdnew file mode 100644index 00000000..feee91a8--- /dev/null+++ b/specs/batch-task-mutations/design-review.md@@ -0,0 +1,44 @@+# T-2384 Design Review++Status: design approved in parent at `Sentinel_717be95229c48191a7c41b6e5e467e4c` for `a5950e9`; review below records the design gate package. Requirements were approved at `Sentinel_35dae4e67398819184369b41649ec75b`; task planning and implementation remain separate gates.++Review [design](design.md), [three-level explanation](explanation.md), and [decision log](decision_log.md).++## Concrete design choices++- Public tool name `mutate_tasks`, with explicit mode and nested item operations; no outer durable batch key.+- Preview uses a fresh non-saving context and returns saved local observations only. Unsaved UI inserts/edits/deletions are never copied, returned, saved or discarded. Temporary fallback records are unavailable as saved evidence. Preview is advisory; later saved changes/imports can invalidate it.+- Execution reuses the app-owned T2380 coordinator. A batch-only policy permits validated saved receipt replay/key conflicts while UI edits are pending, using existing read-only binding/durable-receipt APIs. New acceptance or unresolved recovery stops rather than flush pending UI state.+- Fresh phase checks cover acceptance, both post-await preparation branches and all save/rollback/recovery routes. Dirty detection returns before mutation-capable handlers; accepted unresolved bindings retain original-key recovery semantics.+- A synchronous batch-only identity check immediately before new domain apply rejects ambiguous UUIDs without changing standalone default behavior or historical replay.+- A complete modern recovery response is preencoded through the agreed T2383/T63 adapter before effects. Preparation failure executes nothing; postcommit encoding failure selects ready bytes without invoking the failed encoder again.+- Exact evidence checks determine advancement; current expiry does not invalidate an established commitment. Cancellation has explicit stop reason/next index/optional blocker; all committed stays all_committed after final-item cancellation, although delivery can be suppressed.++## Review mode and findings++The local design-critic reviewed first. Two internal peers then reviewed recovery/correctness and API/integration, using the documented peer-review-validator fallback. After the owner's saved-only instruction, the design was amended and all three reviewed it again. No external disclosure or app tests occurred.++| Finding | Settled resolution |+| --- | --- |+| Fallback might re-enter failed encoder | Fully deliverable modern bytes before effects; encoding-free selection. |+| Advancement predicate vague | Explicit supported v1 type/key/identity/revision/date/error checks; preserve unknown source and separate expiry protection. |+| Cancellation lacks blocker before first item | Stop descriptor with optional blocker; exact summary precedence. |+| Pending-value preview conflicts with owner | Fresh saved-only non-saving context; no pending UI exposure. |+| Receipt-blind dirty block violates approved replay | Existing coordinator read-only terminal/key-conflict inspection while dirty; unresolved/new work stops. |+| Dirty guards could enter rollback handlers | Direct-return boundary rule and explicit table for every fresh coordinator phase. |+| Mirrored enum schema could reject whole batch | Domain status/type/priority are string types with descriptive values, without enum/const constraints. |+| T2383 fallback vocabulary differs | T2384 summary serialization_failed means unestablished effect evidence; no second batch receipt outcome namespace. |++Critic and both final peers report no remaining design-gate blocker or substantive divergence. They require implementation fixtures for saved-only preview and dirty committed/rejected replay, key mismatch, missing/inconsistent sidecars, expired/unresolved evidence, and UI edits during both preparation continuations. These tests must precede shared integration in the task plan.++## Coordination and limits++T2383's draft matches complete-fallback preparation and lossless source/presentation separation; its exact common serializer design/API remains subject to its own approval. T63 remains sole writer of existing shared server/types/dispatch/schema wiring until handoff. No signature is guessed, no shared file is edited, and preview gains no covered-read five-second guarantee or cursor publication.++The design maps all 32 approved criteria to components and verification scenarios. The explanation self-review and source-level document checks were completed. No production source, guard data, recovery action, heavy build/test, client/server setting, deployment, push or merge was performed.++## Approved design gate (historical request)++**Does the design look good?**++Approval includes `mutate_tasks`, saved-only preview, read-only replay plus dirty-phase protection, the optional batch identity policy, and fully prepared response fallback. Shared integration still waits for T2383's approved contract and T63's handoff. On explicit approval, begin the Rune task plan with its own review/approval gate; implementation remains separately authorised.
specs/batch-task-mutations/design.md Added +147 / -0
diff --git a/specs/batch-task-mutations/design.md b/specs/batch-task-mutations/design.mdnew file mode 100644index 00000000..a4410f82--- /dev/null+++ b/specs/batch-task-mutations/design.md@@ -0,0 +1,147 @@+# Design: Batch Task Mutations++Review status: approved by owner in parent at `Sentinel_717be95229c48191a7c41b6e5e467e4c` for commit `a5950e9`. Task plan and conditional implementation approved at `Sentinel_edf7fd12288c819192ad45a04154372a`; external delivery/ownership/test-slot conditions still apply.++## Architecture++Add `mutate_tasks` as a core domain tool. Its mode selects pure preview or ordered calls to the existing app-owned `MCPWriteCoordinator`. It has no persisted batch model, guard, key namespace or recovery engine. Latest-only transport validation remains T2383's responsibility; `tools/call` notifications never reach this tool. See requirements 1–5 and ADRs 4–5.++Place batch request, preview, orchestration and result code in `MCP/BatchWrites/`. The handler supplies the shared container plus its existing write services/context and optional app-owned write coordinator; constructing a coordinator or opening reservation storage while handling a preview is forbidden. ModelContext, models, dictionaries containing Any, and ValidatedTaskUpdate stay on MainActor. Only immutable JSON evidence/encoded bytes and value identities cross actor boundaries through the approved T2383 adapter.++### Input contract and validation++```json+{"mode":"execute","items":[{"itemId":"canonical","operation":"update_task","arguments":{"taskId":"00000000-0000-0000-0000-000000000001","name":"Canonical","expectedRevision":"r1:<64 lowercase hex>","idempotencyKey":"workflow.canonical"}}]}+```++`mode` is exactly `dry_run` or `execute`; `items` contains 1–50 elements. Each item has exactly itemId, operation and arguments. No outer batch key or required correlation ID is added. Input indexes are zero-based and itemId must be a non-empty string; whitespace-only IDs are rejected. Original IDs/argument strings are otherwise preserved.++Validate the complete shape before model fetch, key acceptance, or execution. Reuse `MCPWriteCommand.validate` for nested operation fields and safety formats, with the additional batch restrictions: taskId is required, displayId is forbidden, unsupported operation/fields are rejected, metadata values must be strings, and repeated itemId, normalized target UUID or (operation,key) pair is rejected. UUID equality is used only for collision detection/mapping; original argument spelling reaches canonical request binding unchanged. A batch-local schema mirrors the three protected argument schemas without changing those schemas.++Publish conditional nested schemas for the three operation branches, `additionalProperties:false`, required safety fields, array minItems/maxItems and key/revision patterns. String-valued domain enums (status/type/priority) are validated at the item domain stage: the batch schema describes allowed values but accepts strings with no enum/const restriction so an invalid domain string does not trigger an unintended whole-batch shape rejection. Wrong JSON types and required-field omissions are shape failures; missing conditional status-comment author is a domain failure. Diagnostics contain index, usable itemId, field and existing input error code. No keys are accepted for shape failure.++### Pure preview++MCPBatchTaskPreview creates a fresh MainActor ModelContext over the same persistent ModelContainer, sets autosaveEnabled false before access, and constructs read-only validator services in that context. Fetches explicitly exclude pending changes. It reads saved records only: unsaved UI inserts, edits and deletions in container.mainContext are neither copied, returned, saved, rolled back nor refreshed. No await, transaction, model assignment, insert/delete, rollback, save, receipt lookup, cleanup or coordinator call occurs in the preview pass. observation is saved_local_store; no globally fresh/import-complete view, cursor or snapshot is promised. If durable storage is unavailable, items are unavailable without returning temporary in-memory records as saved evidence.++The preview pass validates all items against locally saved observations; it is not a multi-fetch database transaction. New saved local changes or imports before execution can change results. Unsaved UI state is never used to certify a preview. The shared UI context is untouched, including its original autosave flag and pending changes; only the privately owned read-only context has autosave disabled.++Resolve each task with a batch-only UUID fetch that establishes exactly one match, rather than `TaskService.findByID`'s first match. Zero matches returns TASK_NOT_FOUND; multiple matches returns DUPLICATE_TASK_IDENTIFIER; fetch failure is unavailable. Capture `MCPRecordSnapshot.task` including complete comment-covered revision evidence; only then project away comment bodies in preview output. A required snapshot/comment failure makes that item unavailable, never a valid empty observation. Compare expectedRevision for update/status items; add_comment has no precondition.++| Operation | Read-only validation and proposed effect |+| --- | --- |+| update_task | Reuse TaskUpdateValidator.validate and its read-only milestone resolution. Convert ValidatedTaskUpdate to changed fields/clear actions while still on MainActor; never call apply. Name/description normalization and metadata/milestone precedence match existing command behavior. |+| update_task_status | Share pure status/author/comment-input validation with MCPWriteCommand. Compare task.status using the existing service's same-status logic; describe raw status change and timestamp effects symbolically. A blank comment with a valid required author produces no comment. No timestamps or new comment identities are generated. |+| add_comment | Share pure comment content/author trimming validation with CommentService. Describe normalized comment fields with isAgent true. Never construct a Comment or allocate its UUID. |++Extract only pure validation helpers required for parity, leaving mutation and saving in the existing services. `MCPTaskMutationValidation` in MCP/BatchWrites covers MCP-specific status/comment inputs. Cross-platform pure comment normalization belongs in Services/CommentInputValidation.swift; CommentService uses it while retaining its save/resolve/error behavior, so iOS never depends on a macOS-gated MCP file. Preview valid means current domain constraints were satisfied; `keyState:"unchecked"` and `advisory:true` always accompany it. Persistence fallback is reported as unavailable saved evidence; the preview does not certify sidecar/store ownership or future writes.++### Execution and transaction boundary++`MCPBatchTaskCoordinator` owns the ordered loop, not durable state. After complete shape validation, prepare the compact recovery fallback. Before every item, check observed cancellation. The coordinator handles dirty-context saved-replay versus new-write availability without a loop-level receipt-blind block. Invoke the existing coordinator once with the exact original operation arguments and a batch-only pre-apply identity validation policy. Capture its complete result immediately; verify/classify that evidence before any next item. No live preflight is allowed before receipt replay.++Extend the coordinator internal execute path with an optional batch execution policy, default nil for standalone calls. It contains a clean-context requirement at fresh phase boundaries and a MainActor synchronous throwing pre-apply identity callback. When the shared write context has pre-existing pending changes, permit only read-only retained-outcome inspection before deciding write availability; neither save nor roll back those edits. The outer loop does not suppress saved replay or key-reuse detection.++Inside the existing coordinator, extract the read-only portion of retained inspection using only reservations.withValidatedBindings/lookup and receipts.lookup(durable:true). It validates the original local scope, payload binding, receipt association and expiry using existing validation. A valid unexpired durable terminal receipt returns its original replay even while UI edits are pending; retained different arguments return existing IDEMPOTENCY_KEY_REUSED. This dirty-context path never calls reserve/recordExpiry/reconcile/cleanup/recover/recoveryHook/save/rollback or fetches the task. A missing sidecar binding does not require repair to replay an independently validated terminal receipt in the same store scope; an existing inconsistent association or unreadable binding is uncertainty, not permission to use a new key. Accepted/unresolved evidence requiring recovery cannot progress while dirty. This is a read-only branch of the same coordinator/store APIs, not a second receipt engine.++If no protected replay/key-conflict result can be established while dirty, return an existing uncertainty-shaped result with accepted null (or true where the prior accepted binding is established) and reconciliation direction; no new key/domain effect is accepted. Next items are unattempted. Missing/expired receipts do not establish that the original effect never occurred. For clean contexts, the existing repair/recovery/acceptance path remains authoritative.++The clean-context policy guards fresh mutation-capable phases before any baseline save/cleanup/recovery and guards accepted execution after every suspension before baseline/rejection/commit work. Dirty detection returns directly before entering a phase, never throws into an existing rollback/recovery handler that might discard UI edits. No actor suspension exists between a clean check and that synchronous phase. Own acceptance/domain/receipt changes created within the phase are allowed; do not mistake them for unrelated edits. Dirty detection after acceptance returns accepted true/uncertain without terminal save, rollback or recovery, retaining the accepted binding under existing T2380 semantics. Once the UI owner independently saves/discards pending edits, original-key retry uses existing durable recovery, which can conclude no-effect rejection rather than rerun an interrupted item.++Call the identity callback inside the existing commit scope immediately before command.apply, after fresh binding validation and a clean baseline. It receives original command/target and existing service context, fetches all UUID matches and requires exactly one. No suspension lies between this check, target re-resolution, revision validation and apply. Ordinary validation errors follow the existing rejection/recovery path; only dirty-context safety stops bypass terminal-saving work. Retained read-only replay and active-key outcomes preserve existing results and bypass live identity validation even when the target is missing or ambiguous. Original standalone calls retain default-nil policy and existing behavior; reservation/receipt store files, payload/format/expiry algorithms and storage schema are unchanged.++The advancement predicate for T2380 v1 source is explicit:++- contractVersion is JSON numeric integer value 1 (including equivalent numeric spelling such as 1.0, matching T2380 canonical validation, not Boolean/coerced string), outcome is the string committed, accepted is JSON Boolean true, tool/key exactly match the submitted operation/key, and original optional isError is absent or Boolean false.+- entityId and saved record identity are valid UUIDs. For update/status, entityId and record.taskId equal the input task UUID. For add_comment, entityId equals record.id and record.taskId equals the input task UUID. UUID comparison does not alter source strings.+- record is an object with revision matching r1:[0-9a-f]{64}. For a nonblank requested status comment, the accompanying comment object has its own valid UUID/revision and the same taskId; a blank/absent comment does not require a fabricated comment.+- completedAt/replayExpiresAt are parseable UTC ISO 8601 millisecond strings with expiry later than completion. This validates terminal evidence, not current retention: do not compare expiry with the classification time to downgrade established commitment.++Unknown fields remain preserved; unsupported versions, absent/null/wrong-type required evidence, unreadable/malformed evidence or contradictory identity/error fields stop progression without assigning a new receipt classification. These checks establish the supported source contract, not a new hash of the record or certification of current contents.++Rejected/in_progress/uncertain results stop normally. Unknown evidence stops with a batch diagnostic. A stop descriptor carries reason (item_result, evidence_unavailable, pending_edits or cancelled), nextUnstartedIndex and optional attempted blocker {index,itemId}. An unsuccessful/unreadable attempted result supplies its blocker; cancellation before item zero or between committed items has no attempted blocker; a dirty-context coordinator stop identifies its attempted item even though no new effect/key acceptance occurred. Remaining items are not_attempted, refer to the stop descriptor, and have no coordinator invocation attributable to this loop.++Check cancellation after each returned outcome as well as before the next call. If the current item returns an unsuccessful/unreadable outcome, that result determines stopped/evidence_unavailable summary and optional observedCancellation diagnostic, preserving its original evidence. If it commits and items remain, observed cancellation produces interrupted with the next unstarted index and no failed blocker. If every item committed, summary remains all_committed even when cancellation is observed afterward; transport can still suppress delivery. A caller timeout/lost response alone is not observed cancellation. No loop task is detached to continue after observed cancellation, and no cancellation undoes a durable receipt.++### Clean-phase policy coverage++| Existing coordinator path | Batch policy boundary |+| --- | --- |+| execute active-key handling; acceptSynchronously before existingOutcome/baseline/cleanup | Active result remains read-only. Dirty context uses non-mutating retained inspection only; valid replay/key mismatch returns normally, otherwise uncertainty. Clean entry uses existing path. |+| existingOutcome → recover; missing sidecar repair | While dirty, no recover/repair hook is invoked. Durable terminal evidence can replay without repair; accepted/missing/inconsistent evidence stops. Clean path retains existing repair. |+| runAccepted preparation success | After await, direct clean check before baseline/commit; dirty returns accepted-true uncertainty without catch/rollback/recovery. |+| runAccepted preparation exception/cancellation | After await/error, direct clean check before baseline/completeRejection; dirty preserves UI edits and accepted binding. |+| acceptance-save failure → rollback → rejectBeforeDomain | Entry was clean and phase synchronous; only own staged changes can be rolled back/rejected. No unrelated UI state can interleave. |+| commit failure → rollback → recovery → completeRejection | Entry was clean; synchronous own-mutation rollback/recovery remains existing behavior. |+| terminal-rejection failure → rollback → recovery | Entry was clean; only own receipt state changed. Never enter this path from a dirty pre-phase stop. |++No batch-level lock is held across awaits and different batches can interleave between items. Shared item keys use the existing active-key protections; different keys can conflict through revision checks. This is ordered per-item execution, not an isolation guarantee for the whole plan. Historical canonical replay can advance to new closures after later edits; clients requiring current canonical contents reconcile separately.++## Result contract and serialization++The following names define T2384's logical payload, not common MCP transport types or T2383's wrapper/API.++| Logical field | Contract |+| --- | --- |+| contractVersion, mode, atomicity | 1, dry_run/execute, per_item. |+| summary | preview_valid/preview_invalid for preview; all_committed/stopped/interrupted/evidence_unavailable for delivered execution. confirmedCommittedCount counts only established commitments; stop carries reason/nextUnstartedIndex and an optional attempted blocker. Shape errors use rejected_input with indexed diagnostics; encoder fallback uses serialization_failed. |+| items | Input-ordered mapped entries carrying index/itemId/operation/idempotencyKey/original taskId. |+| item originalResult | Complete original parsed JSON value when readable, original text string, and original optional isError, preserving absence/null/unknown fields. Source and supplemental batch diagnostics are separate members. |+| preview observation/effects | Current record/revision when obtainable, changed fields/actions or normalized proposed comment, valid/invalid/unavailable state, advisory true and keyState unchecked. No committed metadata. |+| not_attempted diagnostic | Reference to stop reason/next index and optional blocker. No newly accepted flag, receipt, saved record or expiry is fabricated; existing keys could independently have prior outcomes. |++Parsed original results are transported losslessly through the approved T2383 JSON representation, not reconstructed using a typed known-field encoder. Original optional isError is absent when absent, rather than converted to false/null. Aggregate isError is true for input failure, any unsuccessful/unverified/unattempted item, invalid/unavailable preview, interruption or encoding failure. It is absent for all committed or fully valid preview results. Source receipt fields and original error flag are never changed to match this aggregate flag.++Supply the generated batch logical JSON and its compatible text as one source to T2383's approved source/presentation adapter. Its proposed immutable-source, collision-free source/presentation separation is the coordination boundary; exact common production type names, function signatures, output-schema plumbing and modern envelope are owned by T2383's approved design. Supplemental categories/links never overwrite nested source fields or retryAction. No serializer implementation is duplicated in this feature. Batch output schemas accept arbitrary unknown JSON inside retained source evidence and distinguish unavailable parsed evidence from explicit null.++Before any execute call, prepare the complete deliverable serialization_failed fallback through the agreed T2383/T63 transport adapter, including tool text/structured presentation, request ID/correlation, required modern result/metadata fields and fully encoded HTTP body bytes. Its logical recovery payload contains input indexes, operation names, original keys and task UUIDs plus reconciliation guidance. Omit unbounded itemId/record/raw-text fields; index maps to the retained original request. The adapter returns ready-to-select immutable bytes, not a logical value requiring a second pass through the failed encoder. No JSON/source/presentation/envelope encoding occurs when selecting fallback. T63/T2383 retain response selection and cancellation ownership; writes acquire no read-retention publication.++If complete fallback preparation fails or the approved shared adapter cannot provide this contract, execute no item. On unreadable item evidence, preserve raw text/isError if the normal failed aggregate can encode; otherwise select the complete preencoded fallback. If final payload/adapter/envelope encoding fails after effects, select those already deliverable bytes without reinvoking any failed encoder. It does not claim all effects uncertain, rejected or unattempted: batch effect knowledge is unestablished and original-key recovery/reconciliation is required. HTTP stream cancellation suppresses delivery; the app-owned coordinator's committed receipts survive.++Retry guidance preserves nested receipt directions. Matching retained item requests can be regrouped into another batch or called through their original protected tool, with the same exact arguments. Retained conclusive rejection stops identical-batch continuation until the caller excludes it or corrects it with a fresh key; transient same-request-retry outcomes keep their existing direction. Never use a fresh key to escape uncertainty. After replay expiry, or response loss with no establishable retention window/originating store, reconcile rather than assume missing receipt means no effect.++## Integration and pattern parity audit++| Site / component | Needs equivalent | T2384 integration / owner |+| --- | --- | --- |+| MCPToolDefinitions.coreTools/tools/all and description safety contract | Yes | Register mutate_tasks once with deterministic core order and batch-specific key explanation. Outer tool is not added to MCPWriteCommand.protectedTools because it has no outer receipt. T63 coordinates schema/registration edits. |+| JSONSchemaProperty/JSONSchemaItems in MCPTypes | Yes | Nested operation object/item bounds require richer schema representation; use agreed T2383 schema support with T63 handoff rather than independent changes. |+| MCPToolHandler tools/call dispatch and app injection | Yes | Dispatch batch before broad mutation fallback handling; preview remains available in fallback mode, execute uses existing per-item unavailable outcome. Supply existing services/coordinator to feature-local handler. T63 sole writer until handoff. |+| MCPWriteCommand.validate/protectedTools/revisionTools | Yes / no | Reuse validator for item shapes; batch not added to protected/revision sets. Shared pure status validation only, preserved standalone behavior. |+| MCPWriteCoordinator.execute/runAccepted/commit | Yes | Optional batch-only clean-phase/pre-apply policy; standalone default nil, clean replay bypasses live identity checks. No store/schema or new recovery engine. |+| TaskUpdateValidator.validate/apply, UpdateTaskIntent | Yes / no | Preview consumes pure validate; apply and App Intent behavior unchanged. |+| CommentService.addComment, AddCommentIntent, TaskService.updateStatus, UpdateStatusIntent | Yes / no | Pure normalization/status-input parity helpers only; retain existing mutation/save semantics and surface-specific errors. No App Intent batch. |+| CommentsSection, DisplayIDMaintenanceService comment callers | No new surface | Existing CommentService normalization/error behavior remains equivalent after helper extraction; add parity regression coverage, no preview/batch in these callers. |+| TaskEditMerge, DashboardView status callers; TaskService.abandon/restore and StatusEngine | No | Preserve service mutation/timestamp behavior; preview effect projection is read-only and tested against the existing status service. MilestoneListSection status belongs to milestone service and is outside task batch. |+| MCPRecordSnapshot/Revision and canonical JSON | No new algorithm | Authoritative comment-covered snapshots, existing request binding; no projected-token hashing. |+| MCPWriteOutcome, receipt resultJSON/resultIsError | Yes / no | Consume original evidence through T2383; no receipt rewrite or new batch storage. |+| MCPServer route validation/notifications/origin and T63 read classification | No new transport | Latest-only request validation stays T2383; mutate_tasks is outside covered read classification even in preview mode. No five-second preview promise or read-publication entries. |+| T2382 reusable snapshots and ordinary cursors | No | No freshness/cursor minting; regression coverage preserves frozen evidence. |+| Maintenance-tool gate, display-ID allocator, CLI intents | No | No maintenance operations, task creation, allocation or new CLI surface. |++Shared-file changes are handed to T63 as one integration patch after coordination; serializer integration waits for T2383's approved design. Feature-local tests/logic and the optional write policy can be planned independently of final transport signatures. No deployment, client/server settings change or activation is included; T2383's installed-client readiness prerequisite remains separate.++## Testing Strategy and Traceability++Use serialized Swift Testing suites with owning TestModelContainer fixtures. Inject item executor/evidence decoder/final encoder failures into feature-local tests; production uses the app-owned coordinator. Existing write fixtures exercise the actual callback path rather than mock receipt durability. Run heavy app suites only after T63 releases its slot and implementation is authorised.++| Requirements | Component and observable tests |+| --- | --- |+| 1.1–1.4 | Request parser/schema: 0/1/50/51 items, unknown fields/operations, missing safety fields, malformed revisions/UUIDs, duplicate IDs/UUID spelling/key namespaces, domain-string versus wrong-type boundaries and unchanged operation args. |+| 1.5, 3.4 | Commit policy/coordinator: missing/duplicate UUID, references, stale revision/comment failure, persistence fallback and unavailable coordinator; dirty-context terminal replay/key mismatch still returns saved evidence without repair; dirty shared context before new acceptance/during both preparation continuations stops without saving or rolling back unrelated edits, preserving accepted unresolved binding when applicable. Audit every clean-phase route and standalone default-nil behavior. |+| 2.1–2.5 | Preview: all-item diagnostics, normalization/no-op/status effects, comments and r1 omission parity; spies forbid saves/rollback/coordinator/receipt calls; unsaved UI insert/edit/delete observations never escape; shared pending edits/autosave remain unchanged on success and every failure; new saved edits before submit can invalidate preview. |+| 3.1–3.3, 3.5 | Ordered loop: canonical update then distinct closure/reason effects, stop on each outcome/unreadable result, cancellation before-first/between-items/during-current/after-last, exact stop descriptor/summary precedence, no next call after observed cancellation, no automatic compensation or detached continuation. |+| 4.1–4.7 | Replay: exact keys/args regrouped/direct tool use, active-key concurrency, restart, deletion/late edits, retained rejection versus transient retry, unknown first-response expiry, expired removed receipts and current-canonical caveat. |+| 5.1–5.6 | Result/adapter: complete mappings, lossless unknown fields/absent/null/raw text/error flags, comment versus parent identity, unknown source versions, absent/null/wrong-type terminal fields, equivalent numeric version spellings versus Boolean/string coercion, identity/error contradictions, malformed dates and expiry passing during classification, aggregate error independence, failure before complete fallback preparation and after commits/final serialization (failed encoder never reinvoked for fallback), no fake saved fields/retry directions. |+| 6.1–6.4 | Integration: motivating consolidation flow, modern one-request tools/call/notification rejection owned by transport, standalone output parity, unchanged cursor/comment revisions, T2383 structured/text/output-schema contract tests. |++Use seeded generated cases in Swift Testing, without a new dependency, for input permutation/collision properties and executor outcome/cancellation sequences. Properties: no effect on shape rejection/preview, original argument identity survives regrouping, executor calls form an input prefix ending at the first noncommitted result or observed cancellation/pending-edit blockage, one result per input index when a normal aggregate is delivered, exact raw evidence round-trip, and no new call after observed cancellation. Existing coordinator fault-injection tests establish durable behavior independently.++## Risks and Assumptions++- Risk: saved-only context/fault handling or phase guards unexpectedly access or flush unrelated UI state | Verify: early owning-container fixtures with pending inserts/edits/deletes and independent durable readback, plus UI edits injected during accepted preparation, before shared wiring | If wrong: stop batch availability and retain existing receipts without effects until the no-save boundary is proven; never expose or flush pending UI state as a fallback.+- Risk: large historic records exhaust aggregate encoding resources after commits | Verify: early encoder fault-injection and production-shaped record tests before shared adapter integration | If wrong: select the preencoded reconciliation fallback and preserve receipts; do not add a success truncation/byte limit without requirements review.++## Research basis++Repository sources settle operation normalization, first-match UUID lookup, coordinator replay/commit placement, snapshot coverage and existing schema limitations. [Apple's SwiftData introduction](https://developer.apple.com/videos/play/wwdc2023/10187/) describes contexts tracking pending edits and fetch options including excluding unsaved changes; preview uses its own context and explicitly excludes unsaved changes. The saved-only expectation comes directly from owner at Sentinel_bb00a4d9d8688191a33a0e6a34ea38db. Apple API reference pages were located but their Markdown content could not be read through this tool; no undocumented autosave guarantee is assumed, and the saved-only/dirty-phase fixture gate above is mandatory. No callable Context7 tool was available; local installed code and primary Apple documentation were used. T2383's approved requirements and design coordination define the transport/result boundary; T63/T2382 approved designs remain read-only dependencies.
specs/batch-task-mutations/explanation.md Added +57 / -0
diff --git a/specs/batch-task-mutations/explanation.md b/specs/batch-task-mutations/explanation.mdnew file mode 100644index 00000000..3f3d51eb--- /dev/null+++ b/specs/batch-task-mutations/explanation.md@@ -0,0 +1,57 @@+# Batch task mutations: implementation explanation++This explanation describes the completed feature-local implementation reconciled onto merged main `adc98b55`. Fresh full macOS and isolated iOS units passed at `b90e6f8`; the complete UI rerun passed at `b8f9fc7` after reviewed fixture corrections, with unchanged production/unit sources. See [publication-verification.json](publication-verification.json) for exact evidence and the retained failed first UI attempt. The owner approved publication and configured Claude review; MacBook client activation remains deferred and is not a merge blocker.++## Beginner Level++### What changed++`mutate_tasks` lets a caller submit a plan containing 1–50 explicit task edits, status changes, or comments in one tool call. Each item names one task and supplies its own retry key. Update and status items also supply the revision they expect to edit. A task can appear only once in a plan.++### Why it matters++A caller can preview a canonical description update and several duplicate closures before submitting them. Preview reads saved local records and describes normalized proposed effects without saving anything or reserving retry keys. Execution processes items in order and stops at the first unsuccessful or unverified result. Earlier successful items remain saved.++### Key concepts++A revision detects edits made since an earlier read. A retry key identifies one exact operation in the originating local store. A retained receipt records the original result, so retrying identical arguments can return that result without repeating the effect. The batch has no shared receipt or all-or-nothing transaction: retrying the batch can replay its completed prefix and continue previously unattempted items.++## Intermediate Level++### Changes overview++The feature lives in `MCP/BatchWrites`. Its parser validates the entire bounded request before privately constructing an executable plan. It preserves original argument spellings for the existing protected write coordinator. A saved-read factory provides a private, autosave-disabled context for preview. The batch coordinator invokes the existing protected operation once per attempted item and advances only after authoritative committed evidence.++### Implementation approach++The optional batch policy guards every relevant shared-context phase. Pending UI edits prevent new acceptance, mutation, save, rollback, or unresolved recovery through that context. Read-only retained terminal replay and key-conflict inspection remain available. Standalone writes keep their default policy. Comment validation is shared with the existing comment service, and status-plus-comment remains one protected transaction.++The batch result is one generated logical source. Every returned attempted-item result retains original text, optional `isError`, and available original JSON separately from the aggregate's classification. Common structured presentation adds task-identity link entries outside that source; the delivered common contract explicitly reports navigation unavailable pending its separate foundation. Before any effect, the handler prepares a complete response containing request correlation and compact original index/tool/key/UUID recovery mappings. Later encoding failure selects those ready bytes without running the encoder again.++### Trade-offs++The bounded list reduces round trips while retaining per-item transactions. It does not provide a CloudKit transaction, automatic duplicate selection, or compensation. Saved-only preview avoids disturbing pending edits but cannot certify imported freshness or future write availability. Existing receipt replay preserves historical results even when the target later changes or disappears; it does not certify current canonical contents.++## Expert Level++### Technical deep dive++Shape validation rejects unknown fields, safety-format errors, wrong JSON types, normalized UUID collisions, duplicate tool/key pairs, and exact caller-ID collisions before any item is attempted. Numeric integer fields are checked from original decimal tokens, avoiding floating-point rounding. Domain strings and conditional status-comment authors retain existing per-item validation semantics. Original UUID argument spelling stays part of T2380 payload binding.++The evidence classifier verifies receipt version, tool/key identity, types, target identity, revisions, terminal dates, and optional error flag before treating an item as committed. Unreadable or unsupported evidence cannot prove no effect. Cancellation is observed between attempts; it does not undo committed effects or turn a caller timeout into observed cancellation. An unstarted item has no acceptance attributable to this submission.++Original retained JSON is inserted through validated raw fragments rather than reparsed through Foundation dictionaries. Missing and null fields, unknown fields, numeric lexemes, and exact original text remain preserved. The common parser's 32-container cap can reject a generated aggregate whose individually readable nested receipts were shallower; that post-effect failure selects the preencoded shallow fallback. Compact fallback excludes giant caller labels, raw records, and entity links. Normal result context may carry explicit task UUID source positions while the prepared fallback context stays link-free.++### Architecture impact++The application batch remains one modern `tools/call`, outside protected single-operation key registration, covered-read admission, snapshot retention, and the five-second read contract. Its router must preserve the original JSON argument subtree before the older `Any` bridge. App-owned services, coordinator, and container are injected; no second receipt engine, guard format, or recovery action is introduced.++### Operational limits++Retry guarantees are local-store and retention scoped. Callers retain original arguments, keys, returned expiries, and original submission time when the first response is lost. Removed or expired receipts do not prove the original effect never happened; a removed key can execute as new under the existing write contract. Unknown commitment requires reconciliation with original keys, never automatic key rotation. A retained canonical update may replay while duplicate closures remain unattempted, so callers needing a current canonical-state condition reconcile it before those closures.++## Completeness Assessment++All 32 approved acceptance criteria are implemented and mapped in the internal spec review. Parsing, saved preview, dirty-context safety, authoritative ordered execution, original-evidence aggregates, complete fallback preparation, real tool registration, app injection, and caller documentation are complete. Fresh finalized verification passed: macOS 2,409 declarations / 3,049 cases; isolated iOS units 1,289 / 1,334; UI 21 / 24. All had zero failures, skips, expected failures, and native runtime warnings, normal exits, and complete owned-process drain. Focused integration 17 / 22 also passed and overlaps the full macOS result; these are not added into a unique total. No matching JUnit/coverage runner was detected for this Xcode project; native xcresult artifacts establish these results.++Modern installed-client compatibility and activation remain unverified and deferred to owner MacBook validation. Common link entries remain explicitly unavailable pending T572 navigation support; this batch does not invent URLs. The later T1734 participating-commit factory is separately coordinated; this feature does not claim a global import fence. External private-diff review, GitHub publication, PR creation, merge, and deployment remain held by the parent's recorded approval restrictions. No production writes, client configuration changes, or installed-app restart occurred.
specs/batch-task-mutations/final-critical-review.md Added +22 / -0
diff --git a/specs/batch-task-mutations/final-critical-review.md b/specs/batch-task-mutations/final-critical-review.mdnew file mode 100644index 00000000..f2f6427e--- /dev/null+++ b/specs/batch-task-mutations/final-critical-review.md@@ -0,0 +1,22 @@+# T2384 final implementation critical review++Current reconciled production source: `fde318d5`, based on merged main `adc98b55`; production/configuration matches the originally reviewed feature source. Fresh full macOS/iOS unit acceptance is pinned to `b90e6f8`; the separately reviewed UI-only fixture correction and full rerun are pinned to `b8f9fc7`. Four internal specialists cleared the unique current-main delta, and quality/spec reviewers cleared the UI fixture correction without assertion weakening. The root independently verified all final native summaries and 15 artifact hashes in [publication-verification.json](publication-verification.json).++## Findings++No unresolved source correctness or approved-scope blocker was identified. Four internal specialist reviews cover reuse, quality, efficiency, and the 32 acceptance criteria. The root independently inspected admission, execution, fallback, provider routing, dependency injection, source preservation, and caller reconciliation rules. Compile-only rich-schema annotations and explicit comment-validator probe dependencies were corrected without changing the intended behavior or weakening assertions.++The fresh finalized macOS result independently establishes 2,409 declarations / 3,049 executed cases passed, zero failures/skips/expected failures/runtime warnings, normal exit and complete owned drain. Isolated iOS unit acceptance independently establishes 1,289 declarations / 1,334 cases; UI establishes 21 / 24, with the same zero-failure/skip/warning and normal-drain conditions. The focused integration result independently establishes 17 declarations / 22 cases passed. Focused and full macOS inventories overlap and are not added into a unique total. Native artifacts were independently inspected by the root.++## Questions examined and answered++1. **Can a malformed later item leave an earlier effect?** Whole-request parsing privately constructs a plan only after all bounded shape/safety/collision checks pass. The modern router supplies original JSON before `Any` conversion; the exact fractional-integer route regression passed.+2. **Can preview or a new batch write flush unrelated edits?** Preview uses a separate saved-only, autosave-disabled context. Optional batch clean-phase policy guards new acceptance and every relevant save/rollback/recovery boundary; retained terminal replay/key conflict stays read-only. Existing standalone default behavior is preserved. The fresh full macOS run includes these safety and standalone regressions.+3. **Can a receipt replay substitute later live data?** Per-item authoritative original text, optional error flag, and available JSON are retained independently. Source serialization uses validated raw JSON fragments; original spelling remains part of the underlying protected operation binding. Modern presentation does not rewrite receipt outcomes or retry direction.+4. **Can aggregate encoding fail after a durable item without a deliverable recovery response?** The complete correlated compact fallback is prepared before dispatch. Post-effect source/encoder failure selects its immutable bytes without re-entering encoding. Root inspected separation of normal task UUID links from fixed fallback context; real route encoding-failure and depth-overflow fixtures passed.+5. **Can an unknown result authorize repeating an effect with a fresh key?** The strict commitment classifier stops on unsupported, uncertain, active, or rejected outcomes. Caller documentation explicitly preserves original keys/store/expiry context, identifies absent receipts as inconclusive, and explains batch continuation and current canonical reconciliation.+6. **Does this expand concurrent read or global-import guarantees?** The batch remains one application `tools/call`, outside protected outer-key registration, covered-read deadlines, read admission, and frozen snapshot retention. No global CloudKit transaction/import fence is claimed. The separately coordinated T1734 participating-commit factory remains a later owner-approved obligation, not an undisclosed batch dependency or guarantee.++## Current publication boundary++All native verification, lint, source-equivalence and cleanup checks passed. The first fresh UI attempt remains qualified as four real fixture failures plus sampled runner-only termination during stalled finalization; it was not counted as acceptance. The corrected full UI run finalized normally. The owner resolved prior GitHub/Claude disclosure holds and approved the configured review/eligible squash-merge workflow. PRPilot outcomes will be reported when observed. MacBook activation is deferred and is not a merge blocker. No production/live writes, client changes or deployment occurred.
specs/batch-task-mutations/final-handoff.md Added +35 / -0
diff --git a/specs/batch-task-mutations/final-handoff.md b/specs/batch-task-mutations/final-handoff.mdnew file mode 100644index 00000000..1b1fc549--- /dev/null+++ b/specs/batch-task-mutations/final-handoff.md@@ -0,0 +1,35 @@+# T2384 publication handoff++All 14 approved Rune tasks are complete. Reconciliation applies only the unique T2384 delta onto merged main `adc98b55e69af6be22e095126c81986d0d8e48a8`; the existing common T63/T2383/T2382 foundation is retained. Original feature worktree and paused T1734 work remain untouched.++## Source and review++- Publication worktree: `/Users/arjen/Documents/Codex/2026-10-03/task-4/transit-t2384-final`.+- Branch: `T-2384/publication`.+- Reconciled source: `fde318d5f8eedbef62f825bd9ad69889187c5f09`; tested pin: `b90e6f84255f01c3de39104ea59a9aa0c77c7acb`.+- All 271 production/configuration/isolation files compared are byte-identical to reviewed original tip `db775173`; merged main's test and documentation changes are preserved. Three documentation conflicts were resolved by retaining main and adding the feature.+- Four internal specialists cleared the current production delta. Review fixes correct the MCP guide's 13-tool list and restore the batch specs index row. Neither changes production behaviour.++`mutate_tasks` is one modern application tool call, with saved-only dry runs and 1–50 ordered update/status/comment items. It preserves original per-item receipt evidence, original argument binding, revision preconditions and atomic domain/result saves. Execution stops at the first unsuccessful or unestablished item; committed prefix effects remain. A complete correlated serialization-failure response is prepared before dispatch and later selected without reencoding. Caller retry/reconciliation guidance is in [the write contract](../../docs/mcp-write-contract.md#application-batch-task-mutations).++## Fresh reconciled acceptance++| Suite | Enabled declarations | Passing native cases | Source pin |+| --- | ---: | ---: | --- |+| Full macOS units | 2,409 | 3,049 | `b90e6f8` |+| Full isolated iOS units | 1,289 | 1,334 | `b90e6f8` |+| Full isolated iOS UI | 21 | 24 | `b8f9fc7` |++All three runs finalized normally with exit zero, exact enabled-inventory mapping, zero failures/skips/expected failures/native runtime warnings, and complete owned process drain without host signals. Only the UI fixture changed between pins; production, configuration and unit sources remain identical. Both fresh platform builds, the corrected UI incremental build, and final strict lint (596 Swift files and all guards) passed. The newly owned simulator was deleted; all other simulator UUIDs and existing stores were preserved.++The first fresh UI attempt completed 24 test bodies with four real fixture failures, then stalled in finalization. Its sampled owned runner was terminated (subprocess -15, wrapper 241), with no host signals and complete owned drain; that result is unfinalized and is not counted as acceptance. Three direct Settings assumptions were replaced by the existing overflow-aware toolbar helper. The portrait fixture now asserts a captured frame instead of timing out during a remote predicate query. All behavior assertions and all 21 declarations remain, and the full 24-case rerun passed. Native warnings are zero; ordinary XCTest debugger/animation-idle console diagnostics remain in logs.++See [publication-verification.json](publication-verification.json) for source-equivalence, native summaries, inventories, drain records and artifact hashes. The root independently checked every final native summary/inventory and all 15 recorded artifact hashes.++The original worktree's task14 evidence remains historical, including early qualified RED teardown failures. It is not substituted for the fresh publication results. No matching JUnit or line-coverage runner exists for this Xcode project; native results and inventories are retained without invented conversions.++## Publication and downstream boundaries++The owner explicitly approved GitHub pushes, disclosure to the configured Claude reviewer, and eligible overnight merges. Earlier automatic approval denials are historical and have been resolved by that approval. PRPilot will record actual external review/check/merge outcomes on the PR and in the final parent report; this document does not preclaim them.++MacBook installed-client compatibility/activation is owner-deferred and is not a merge blocker. Before feature use, validate the latest-only 2026-07-28 connection, structured/text result compatibility and advertised `mutate_tasks` schema. No production/live task writes, guard-store recovery, production application/server launch, client setting changes, CloudKit changes or deployment were performed during this publication workflow. Ticket status remains unchanged under the parent's no-live-writes constraint. T1734's participating-commit factory and T572 navigation remain separate; no global import fence or task navigation URL is claimed.
specs/batch-task-mutations/implementation.md Added +181 / -0
diff --git a/specs/batch-task-mutations/implementation.md b/specs/batch-task-mutations/implementation.mdnew file mode 100644index 00000000..3b80f405--- /dev/null+++ b/specs/batch-task-mutations/implementation.md@@ -0,0 +1,181 @@+# Batch task mutations: implementation explanation++This explanation describes the completed feature-local implementation and modern MCP integration at runtime source `5c42c7e059e8c810e89d366f0889aef132adf5c5`. Fresh native macOS, isolated iOS unit, and UI acceptance all passed. Publication and client activation remain separate approval/readiness boundaries.++## Beginner Level++### What changed++`mutate_tasks` lets a caller submit a plan containing 1–50 explicit task edits, status changes, or comments in one tool call. Each item names one task and supplies its own retry key. Update and status items also supply the revision they expect to edit. A task can appear only once in a plan.++### Why it matters++A caller can preview a canonical description update and several duplicate closures before submitting them. Preview reads saved local records and describes normalized proposed effects without saving anything or reserving retry keys. Execution processes items in order and stops at the first unsuccessful or unverified result. Earlier successful items remain saved.++### Key concepts++A revision detects edits made since an earlier read. A retry key identifies one exact operation in the originating local store. A retained receipt records the original result, so retrying identical arguments can return that result without repeating the effect. The batch has no shared receipt or all-or-nothing transaction: retrying the batch can replay its completed prefix and continue previously unattempted items.++## Intermediate Level++### Changes overview++The feature lives in `MCP/BatchWrites`. Its parser validates the entire bounded request before privately constructing an executable plan. It preserves original argument spellings for the existing protected write coordinator. A saved-read factory provides a private, autosave-disabled context for preview. The batch coordinator invokes the existing protected operation once per attempted item and advances only after authoritative committed evidence.++### Implementation approach++The optional batch policy guards every relevant shared-context phase. Pending UI edits prevent new acceptance, mutation, save, rollback, or unresolved recovery through that context. Read-only retained terminal replay and key-conflict inspection remain available. Standalone writes keep their default policy. Comment validation is shared with the existing comment service, and status-plus-comment remains one protected transaction.++The batch result is one generated logical source. Every returned attempted-item result retains original text, optional `isError`, and available original JSON separately from the aggregate's classification. Common structured presentation adds task-identity link entries outside that source; the delivered common contract explicitly reports navigation unavailable pending its separate foundation. Before any effect, the handler prepares a complete response containing request correlation and compact original index/tool/key/UUID recovery mappings. Later encoding failure selects those ready bytes without running the encoder again.++### Trade-offs++The bounded list reduces round trips while retaining per-item transactions. It does not provide a CloudKit transaction, automatic duplicate selection, or compensation. Saved-only preview avoids disturbing pending edits but cannot certify imported freshness or future write availability. Existing receipt replay preserves historical results even when the target later changes or disappears; it does not certify current canonical contents.++## Expert Level++### Technical deep dive++Shape validation rejects unknown fields, safety-format errors, wrong JSON types, normalized UUID collisions, duplicate tool/key pairs, and exact caller-ID collisions before any item is attempted. Numeric integer fields are checked from original decimal tokens, avoiding floating-point rounding. Domain strings and conditional status-comment authors retain existing per-item validation semantics. Original UUID argument spelling stays part of T2380 payload binding.++The evidence classifier verifies receipt version, tool/key identity, types, target identity, revisions, terminal dates, and optional error flag before treating an item as committed. Unreadable or unsupported evidence cannot prove no effect. Cancellation is observed between attempts; it does not undo committed effects or turn a caller timeout into observed cancellation. An unstarted item has no acceptance attributable to this submission.++Original retained JSON is inserted through validated raw fragments rather than reparsed through Foundation dictionaries. Missing and null fields, unknown fields, numeric lexemes, and exact original text remain preserved. The common parser's 32-container cap can reject a generated aggregate whose individually readable nested receipts were shallower; that post-effect failure selects the preencoded shallow fallback. Compact fallback excludes giant caller labels, raw records, and entity links. Normal result context may carry explicit task UUID source positions while the prepared fallback context stays link-free.++### Architecture impact++The application batch remains one modern `tools/call`, outside protected single-operation key registration, covered-read admission, snapshot retention, and the five-second read contract. Its router must preserve the original JSON argument subtree before the older `Any` bridge. App-owned services, coordinator, and container are injected; no second receipt engine, guard format, or recovery action is introduced.++### Operational limits++Retry guarantees are local-store and retention scoped. Callers retain original arguments, keys, returned expiries, and original submission time when the first response is lost. Removed or expired receipts do not prove the original effect never happened; a removed key can execute as new under the existing write contract. Unknown commitment requires reconciliation with original keys, never automatic key rotation. A retained canonical update may replay while duplicate closures remain unattempted, so callers needing a current canonical-state condition reconcile it before those closures.++## Completeness Assessment++All 32 approved acceptance criteria are implemented and mapped in the internal spec review. Parsing, saved preview, dirty-context safety, authoritative ordered execution, original-evidence aggregates, complete fallback preparation, real tool registration, app injection, and caller documentation are complete. Fresh finalized verification passed: macOS 2,409 declarations / 3,049 cases; isolated iOS units 1,289 / 1,334; UI 21 / 24. All had zero failures, skips, expected failures, and native runtime warnings, normal exits, and complete owned-process drain. Focused integration 17 / 22 also passed and overlaps the full macOS result; these are not added into a unique total. No matching JUnit/coverage runner was detected for this Xcode project; native xcresult artifacts establish these results.++Modern installed-client compatibility and activation remain unverified and deferred to owner MacBook validation. Common link entries remain explicitly unavailable pending T572 navigation support; this batch does not invent URLs. The later T1734 participating-commit factory is separately coordinated; this feature does not claim a global import fence. The owner has resolved the earlier publication/disclosure holds and explicitly approved pushes, configured Claude review and eligible overnight merge. PRPilot review and merge are the next publication steps; deployment and client activation remain outside this workflow. No production writes, client configuration changes, or installed-app restart occurred.++## Evidence and historical checkpoints++Fresh reconciled acceptance is in [publication-verification.json](publication-verification.json): full macOS 2,409/3,049 and iOS units 1,289/1,334 at `b90e6f8`; corrected full UI 21/24 at `b8f9fc7`. Only reviewed UI fixture corrections separate those pins; production/configuration/unit sources are identical. The first UI attempt had four genuine fixture failures and a sampled runner-only finalization termination; it remains explicitly failed/unfinalized. The corrected full rerun passed normally. Original-worktree acceptance and artifact hashes remain historical in [task14-green-actual.json](task14-green-actual.json). See [final-handoff.md](final-handoff.md) and [final-critical-review.md](final-critical-review.md) for current completion and publication boundaries.++The following checkpoint notes preserve the original observations and restrictions at their recorded stage. Pending-task and slot statements below are historical and superseded by the final acceptance above.+++## Task 1: intended RED confirmed++Executed the parent-granted focused command on 2026-10-03:++```sh+make test-quick TEST_TARGETS=TransitTests/MCPBatchTaskSafetyTests+```++The sandboxed attempt failed before compilation on dependency/Xcode access. The per-command escalated retry reached compilation. Explicitly typing the saved-read callback's ModelContext removed a cascading inference error; the final focused rerun failed only on the planned absent production seams:++- `MCPBatchWritePolicy` type and initializer.+- Coordinator `batchPolicy` argument.+- `MCPBatchSavedReadContext` at both factory call sites.++Final make exit: 2; Xcode exit: 65. No test bodies ran because this is an intentionally uncompilable RED against absent interfaces. This establishes the RED task, not passing behavior or implementation correctness. Full output is retained at `/Users/arjen/Documents/Codex/2026-10-03/task-4/verification/t2384-safety-red.log`.++After the final run, escalated `pgrep -fl 'xcodebuild|swift-frontend|swift-build|TransitTests|XCBBuildService'` exited 1 with no matches. The exclusive heavy slot was immediately released through the parent. Targeted strict SwiftLint and whitespace checks pass. The suite drafts 28 cases with persistent owning fixtures; unrelated production interfaces, shared serializer delivery and GREEN implementation were untouched.++Task 1 is complete; further test execution requires a new slot grant. T2383 delivered task 15 remains a prerequisite for later result/schema consumers.++## Task 2: focused GREEN confirmed++Under the approved DAG and sole coordinator ownership, Task 2 now implements the private synchronous saved-read factory and optional batch policy. Dirty admission uses existing validated binding and durable receipt inspection without repair, expiry writes, cleanup, recovery or domain fetch. Both accepted preparation continuations return directly when unrelated UI changes are present. The fresh synchronous apply callback validates exactly one saved task UUID; standalone callers retain the default nil policy.++Unchanged outcome helpers moved to `MCPWriteCoordinator+Outcomes.swift` so coordinator phase code remains within lint limits. Fixtures now consume the production identity validator and additionally cover retained payload conflict with malformed receipt and a direct missing-UUID callback. The safety suite has 30 cases.++The parent granted the exclusive focused GREEN command:++```sh+make test-quick TEST_TARGETS='TransitTests/MCPBatchTaskSafetyTests TransitTests/MCPWriteCoordinatorTests'+```++The per-command escalated run compiled and exited 0, with no fixes or reruns required. The result bundle reports 36 executed cases passed: 30 batch safety cases and six standalone coordinator regressions. There are 19 test declarations, including nine parameterized tests with 26 runs; no failures, expected failures, skips or runtime warnings. The full log and xcresult summary are retained in `/Users/arjen/Documents/Codex/2026-10-03/task-4/verification/t2384-safety-green.log` and `t2384-safety-green-summary.json`.++Escalated process inspection again returned exit 1/no matches for the build/test worker patterns after the job. The heavy slot was immediately released through the parent before read-only xcresult analysis. Full `make lint` passes all ownership/schema guards and 402 Swift files; whitespace checks pass.++Tasks 1 and 2 are complete. Task 3 remains blocked on delivered T2383 task 15. No result/schema consumer, common server wiring, guard-store format or recovery-engine change is included. These focused results establish the Task 2 safety and standalone-coordinator boundary, not whole-feature readiness.++The root's read-only source critic reported no Task 2 blocker after auditing dirty phase entries, both preparation continuations, retained association and repair-free replay, binding conflict precedence, synchronous identity validation, historical bypass, default nil policy and fallback saved-context refusal. The external consumer gate is delivered T2383 task 15 (`gpzncvz`), including source 3 (`gpzncvn`), presentation 5 (`gpzncvp`), encoder 7 (`gpzncvr`) and schema 9 (`gpzncvt`); approvals or declarations alone do not satisfy delivery.++## Task 3: RED fixture draft ready; isolated execution pending++Read DELIVERED15 handoff `b21e358c8a5ea1e287afe332c1fc50d83303ce19`, source checkpoint `543c4a757e4cb7f9f73c973d7cb1be5725c8f342`, and the actual source/runtime dependency manifests read-only. Root imported the exact common consumer files in `fe1c57f`, with evidence `7d8ba36`; this worker neither imported nor edited those files. Draft uses the delivered source, presentation, metadata, JSON value, encoder and provider-selection APIs directly. The only intentionally absent seams are batch-local evidence assessment and compact fallback source construction for Task 4.++New `MCPBatchTaskEvidenceTests.swift`, `MCPBatchTaskEncodingTests.swift` and `MCPBatchTaskResultFixtures.swift` contain 13 declarations / 52 synthetic cases. They cover strict numeric/type/identity/revision/time evidence, original text/optional flags/unknown fields/null/numeric lexemes, retained retry direction, giant item ID and context stripping, original recovery index/tool/key/UUID, preparation failure before dispatch, payload/presentation/envelope failure after a synthetic effect, encoding-free ready-byte selection, depth-32 readable evidence overflowing its generated aggregate and retained depth-33 unreadable evidence. All effects are counters; no models, live writes or receipt/recovery actions are used.++Targeted strict SwiftLint, Swift frontend **parse only** and whitespace checks pass. A lightweight fixture check confirms all 15 exact mutation fragments change the baseline and preserve JSON syntax. No typechecking, build or app test ran; meaningful RED is unverified and Task 3 remains in progress. The coordinator and existing safety production files are unchanged.++Intended focused inventory is exactly `MCPBatchTaskEvidenceTests` plus `MCPBatchTaskEncodingTests`. This is a selector specification, not a runnable legacy `make test-quick` command. Before execution, parent must select the isolated development-host foundation, coordinate containment-owner App/project changes, establish signed smoke/preflight and exact enabled inventory, then grant an exclusive focused slot. No isolation edits, common integration, GREEN implementation or later task is included in this draft.++## Task 3: meaningful runtime RED verified; teardown limit preserved++Parent explicitly granted the bounded exclusive sequence. Inspected and imported containment commit `bbdb9df64c87fb52bd62490d39c3bc9727f876a9` as `8be35ea`, preserving the complete MCP tree, existing coordinator/App constructor wiring and receipt schema. All owner checkpoint hashes match. Declaration-only RED shells `0512d99` preserve original source with canAdvance false and throw notImplemented for fallback; they implement no GREEN semantics. Their source bytes were already present at smoke build launch; the subsequent commit changed bookkeeping only.++Offline isolation checks, dedicated fresh smoke build, signed-host preflight and one isolated smoke body all passed (exit0). Smoke observed memory-only storage, effective CloudKit disabled, disabled counters and a temporary development-container sidecar. The fresh shared Debug build, signed host/explicit unit-test launch preflight, enumeration and exact13 declaration inventory also passed (exit0). No unverified/production host or live settings/data action ran. Shared compilation emitted existing test/scheme warnings, preserved in the raw log; no zero-warning claim.++Both selected suites executed all13 declarations and52 bodies (48 parameter cases plus4 standalone bodies). Console recorded16 issues exclusively at the intended false commitment/notImplemented fallback shells. This establishes meaningful RED, not passing feature behavior. Test finalization stalled after the complete body summary. Both exact owned processes (runner66051, host66059) were sampled successfully before signaling. Identity-checked TERM stopped only runner66051; the host drained without a signal. A cleanup poll encountered the transient zombie runner and stopped its identity assertion; the session reaped it, then final ps confirmed both absent. Test exit143 and the unfinalized xcresult are explicit limits. No teardown-only replay was performed. Heavy slot released immediately after drain, before evidence analysis.++Task3 is complete. Actual summary is `task3-red-verification.json`; raw commands, signed host proofs, inventory, logs, samples and local summary remain in `.codex-cache/task3-red-readiness/`. Offline log remains `/Users/arjen/Documents/Codex/2026-10-03/task-4/verification/task3-offline-isolation.log`. Task4 GREEN and further app runs have not started; future heavy execution requires a fresh parent slot grant.+++## Task 4: GREEN source checkpoint; runtime verification pending++Task4 is in progress under parent source-only authorization. The batch classifier consumes immutable delivered source evidence and preserves all text, JSON, optional flags and retry fields. Commit advancement requires exact decimal contract version one, scalar-exact tool/key, supported saved identities/revisions, canonical UTC millisecond dates with expiry strictly after completion, accepted true and no non-null contradictory error/retry fields. Supported unsuccessful evidence additionally requires typed error and outcome/accepted/retry consistency; incomplete or contradictory evidence is unavailable. No current clock, domain reread or receipt mutation is used.++The compact generated fallback retains original indexes/operation/tool/key/UUID only; it excludes unbounded item IDs, records and links. MCPBatchTaskPreparedResponse has a private initializer and constructs a usable capability only after the delivered encoder prepares complete correlated modern bytes. It retains fixed context and immutable ready bytes, and selection delegates to the common provider selector with a callback returning those bytes rather than reencoding. Later executor construction must require this capability; no executor is introduced in this task.++Original Task3 test files and 13 declarations /52 cases are unchanged. Separate prepared-response and evidence-boundary suites add eight declarations /32 cases: preparation blocks dispatch, ready encoding precedes effects, post-effect provider/encoder failures select exact bytes without repeating preparation, giant IDs/context stripping and correlation/metadata, adjacent decimal and equivalent numeric versions, normalized invalid dates, opaque scalar identities, and supported versus malformed failure contracts. Focused GREEN inventory is four suites, 21 declarations /84 intended bodies. These supplemental cases are drafted but not executed.++Targeted strict no-cache SwiftLint, Swift frontend syntax parse and git whitespace checks pass. No app build, test or typecheck was executed for Task4. Root independent source review and a new parent exclusive heavy-slot START grant precede signed host preflight, exact inventory and focused GREEN execution. Task4 remains in progress; no later task was started. The prior accepted RED run's exit143/unfinalized result limitation remains unchanged.++Final compatibility review permits absent or explicit null error/retryAction on otherwise valid commitment, preserving saved optional-field distinctions. Non-null contradictory error/direction remains unavailable. Four supplemental cases exercise this boundary without changing the original13/52.++## Task 4: finalized isolated GREEN verified++Parent granted START for reviewed source `85bec71` (implementation `28bee6a`). Configuration guard, private incremental Debug build, signed isolated development host preflight, enumeration and exact four-suite21-declaration inventory all exited0. All21 declarations and84 bodies executed and passed:14 parameterized declarations with77 parameter cases plus7 standalone bodies. Finalized xcresult is Passed, zero failures/issues/skips and empty runtimeWarnings. Original13/52 fixtures remained unchanged; supplemental8/32 exercised exact decimal/date/opaque/null/failure-contract boundaries and the required prepared capability.++Test exit0; owned runner81469 and isolated host drained normally, confirmed by scoped process inspection. Slot immediately released before extraction. No cleanup sample, signal or replay was required. Default sandbox xcresult summary extraction exited64 on its report-cache write; the per-command escalated read/extraction exited0, without rerunning tests. Existing build warnings and the Xcode matching-destination warning remain in raw logs; no zero-console-warning claim. Prior task3 exit143/unfinalized limits remain historical evidence, not overwritten.++Task4 is complete. This delivers pure strict saved-evidence classification, shallow provider-owned fallback and the private prepared-response capability required by later executor construction. Source and supplemental independent review are in `task4-green-review.md`; actual summary in `task4-green-verification.json`. Local command/preflight/inventory/build/test/result/drain evidence remains `.codex-cache/task4-green-readiness/`, with fresh Task4Green result paths and the prior RED preserved. No live writes, client activation, push/merge/deployment or subsequent app job occurred.+++## Task 5: request and schema RED draft; runtime execution pending++Parent accepted finalized Task4 GREEN at 011660e and authorized Task5 fixture preparation under the approved DAG. Rune task5/eptphz6 is in progress on sole stream1; Task6 has not started. Read actual request design, requirements, task review, MCPWriteCommand.validate and its existing public operation schemas. Existing Int/Bool helpers already reject Boolean-number/string coercion; standalone metadata validation is object-only, while batch additionally requires string values.++Batch-local MainActor MCPBatchTaskRequest.parse consumes the delivered lossless MCPJSONDocument and declares valid request versus indexed INVALID_INPUT diagnostics. Items retain exact logical original arguments and an existing validated MCPWriteCommand, preserving opaque caller identity and original strings while keeping normalized UUID mapping separate. No service/coordinator/store or admission callback is reachable from parsing. MCPBatchTaskSchema declares a rich input MCPJSONDocument only, with registration deferred to the current shared owner. Both declaration-only methods throw notImplemented; no parsing or schema GREEN semantics have been introduced. These shells permit actual compiled runtime RED instead of absent-symbol failure.++Separate request/schema suites contain 17 declarations /109 intended bodies. Coverage includes 0/1/50/51 bounds, exact explicit mode/operation, closed outer/item/argument fields, indexed usable caller diagnostics, UUID/key/revision safety including newline anchors, strict JSON types and nested metadata values, no-op update, untouched original numeric lexeme and scalar/UTF8 spellings, domain strings/conditional status author shape admission, opaque IDs versus normalized UUID/tool-key collisions and four deterministic shuffled collision plans. A malformed last item admits zero earlier items. Rich schema tests assert closed nested branches, exact public fields/required sets, UUID/key/revision formats, bounded array, domain descriptions without enum/const restrictions, no conditional status-author constraint and add_comment without revision.++All prior84 evidence/encoding fixtures, common source files and coordinator/App/project files remain unchanged. Targeted strict no-cache SwiftLint, Swift syntax parse and whitespace checks pass; full lint is recorded after the draft. No app build, runtime test or typecheck has been run for Task5. Root independent source review and an explicit parent START are required before signed pinned development host preflight, exact17 declaration discovery and actual109 body execution. Source-only checks do not establish meaningful RED or Task5 completion.+++Task5 runtime RED is now meaningful and independently cleared. Attempt1 at reviewed1edc6b9 stopped at build65 on one unrelated heterogeneous Any ternary fixture compiler issue, with no host/body execution; its workers drained and all artifacts are preserved. The narrow equivalent switch correction is f428f94. Parent/root explicitly authorized the same focused retry with fresh attempt2 paths, preserving attempt1.++Attempt2 sourcef428f94 passed serial build0, signed isolated development/unit-test preflight0, enumeration0 and exact17 declaration inventory0. All109 bodies ran (105 parameter cases +four standalone); all109 issues were the intended caught notImplemented from parser/schema declaration shells. Root independently counted starts/issues and cleared meaningful RED, with no unrelated runtime issues.++The Xcode runner stalled after bodies, so owned runner93600 and isolated host93608 were sampled successfully before bounded cleanup. Identity-checked TERM went only to runner93600; host93608 drained without any signal. Session89516 exit143 and unfinalized xcresult are explicit limits, not a clean finalized test failure. Final escalated inspection proved no owned workers remain; RELEASE was immediately sent through root before this minimal bookkeeping. No teardown-only replay was performed. Raw attempt2 evidence remains .codex-cache/task5-red-attempt2; structured copy is task5-red-verification.json. Task5 complete; Task6 source awaits continued coordination and has not begun.+++## Task6: GREEN source checkpoint; runtime verification pending++Approved Task6/eptphz7 is in progress on sole stream1 after meaningful Task5 RED. The parser accepts a delivered document or its original validated JSON value, before any Any conversion; shared modern routing must bind that raw subtree at coordinated Task14 integration. The entire bounded closed shape, typed fields, safety formats and duplicate item/tool-key/normalized UUID identities are established before a privately constructed request can escape. Exact UTF8 comparison covers structural names as well as opaque caller IDs. Each item preserves its original logical arguments and existing validated MainActor MCPWriteCommand; no model/service/coordinator, key store or receipt access occurs here. Domain strings and conditional status-comment authors remain per-item validation; no-op update and standalone add_comment semantics are preserved.++Integral JSON numbers are validated from decimal mantissa/exponent with checked arithmetic and exact Int range, never Double/Decimal. Fractions rounded toward an integer or underflowing toward zero cannot pass; mathematically equivalent integral spellings retain their original numeric tokens alongside the exact Int bridge. Zero, negative integers and integral scientific notation remain allowed shapes, with no new positivity restriction.++The schema derives field types/required safety from actual nonisolated protected core definitions and emits a feature-local rich MCPJSONDocument; it closes outer/item/argument objects, bounds items1...50, fixes mode/operation discriminators and UUID/key/revision formats, describes actual captured enum values without applying enum/const to domain strings, and constrains metadata values to strings. Shared registration/transport files are untouched.++Metadata names that would collapse in Swift's canonical-equivalent String dictionaries are rejected as indexed whole-input INVALID_INPUT before command construction. This mirrors the delivered latest-only MCPModernWire.requestValue representability check (a8fcc715): its UnsupportedArguments sentinel is rejected by modern preflight as RPC invalidParams/-32602 before protected key admission, rather than an item-domain failure. This is inherited bridge compatibility, not a new transport policy or historical receipt rewrite; the original document is unchanged. Raw structural duplicate guards remain active on the value overload.++Original Task5 17declarations/109cases and earlier84 evidence/encoding cases are unchanged. Separate RequestBoundaryTests add4declarations/23cases:15 exact numeric edges,2 metadata representability cases,3 scalar-exact structural names and3 raw duplicate positions. Focused GREEN inventory is three suites21declarations/132bodies. Root independent source critic cleared parser/schema/private construction, actor-safe captured definitions and supplemental scope. Targeted strict no-cache lint, Swift syntax parse, whitespace and full make lint pass; no Task6 app build, typecheck or runtime job has run. Task6 remains in progress until signed source-pinned host/exact inventory and actual GREEN after parent slot grant. T1734 currently owns heavy slot; Task7 has not started.+++Task6 focused GREEN is now finalized and independently cleared. Parent START pinned reviewed5066a06/source565c336; source/owned/protected/artifact hashes and fresh paths verified, with no source changes during the job. Serial isolated build0, signed development/unit-test host preflight0, enumeration0 and exact three-suite21 declaration inventory0 all passed. Actual finalized Task6Green.xcresult reports132 cases passed (128 runs across17 parameterized declarations plusfour standalone), zero failures/skips/expected failures and no runtime warnings. Test job session5411 exited0 normally, with no fixture correction, rerun, signal or cleanup. Root independently confirmed console21/132/no issues.++Final escalated process inspection showed no owned runner/host/build workers. RELEASE was sent immediately before off-slot readonly xcresult extraction; result finalized normally, unlike the separately preserved RED teardown limitations. Task6 complete. Raw commands/logs/signed host proof/exact inventory/unchanged fixture hashes/finalized summary remain .codex-cache/task6-green-readiness; structured result is task6-green-verification.json. Shared routing/raw argument binding, actual batch execution and later preview tasks remain outside this checkpoint. Task7 has not started and requires root Rune retrieval/delegation; no live writes, activation or extra app jobs occurred.
specs/batch-task-mutations/requirements-review.md Added +48 / -0
diff --git a/specs/batch-task-mutations/requirements-review.md b/specs/batch-task-mutations/requirements-review.mdnew file mode 100644index 00000000..b3f9d2db--- /dev/null+++ b/specs/batch-task-mutations/requirements-review.md@@ -0,0 +1,48 @@+# T-2384 Requirements Review++Status: requirements approved at Sentinel_35dae4e67398819184369b41649ec75b, including final transport clarification in 9b5122c. This records the requirements review; design/tasks/implementation remain separate gates. Scope/name were approved in the parent at `Sentinel_4fd40b3fecf48191a57ce03897d3e7ec`; design/tasks/implementation remain unapproved.++Review [requirements](requirements.md) and [decisions](decision_log.md). The approved scope led to the normal workflow status change to Spec with its comment; the live MCP result confirmed commitment. No production implementation or heavy tests have begun.++## Proposed behavior++- A single domain tool call supports 1–50 explicit task updates, status changes with optional reason/comment, or standalone comments.+- Tasks use UUID selectors; one operation per normalized target UUID per batch. Same-task property plus separate comment edits require another call. Standalone comments retain their current lack of revision checking.+- Dry run validates every item's current local state, returns proposed normalized effects and diagnostics, and touches no domain/receipt/guard state or pending edits. Retry-key state is explicitly unchecked.+- Execute commits items in order, advances only on authoritative understood commitment, and stops after the first unsuccessful/unreadable result. Remaining items are not_attempted; earlier successes remain committed.+- Explicit item keys retain T2380 local-store/tool binding, exact original operation arguments and replay windows. There is no durable outer batch replay. An identical batch retry can recover earlier commits and continue with unstarted items.+- T2383 supplies the approved transport-neutral result adapter; original receipt text, unknown fields, missing/null distinctions, saved revisions, item isError and retryAction remain authoritative. T2384 adds no transport migration.++## Recovery limits to review carefully++A preview is not a reservation. A matching-key submission may replay a historical success even when a current-state preview is stale or the target was deleted. Replaying a canonical update does not prove its current contents still justify closing duplicates; callers requiring that condition must reconcile the current canonical task before submitting new closures.++A lost response does not prove no effects. Retain original requests/keys and any returned expiry. If the first response was lost, retain submission-time context and reconcile when the replay guarantee cannot be established; missing or removed receipts do not prove the original effect never occurred. Expired removed keys can execute anew under T2380. Unknown commitment never warrants a fresh key.++## Critic and independent peers++Mode: **internal peer fallback**, explicitly authorised for this work. No external model/service disclosure occurred, despite PERSONAL_PROJECTS=1. The local design-critic ran first, followed by two independent peers applying the documented peer-review-validator method: correctness/recovery and API/architecture. Their perspectives are internal agents rather than distinct external models.++The critic identified five issues, all incorporated:++| Finding | Requirements resolution |+| --- | --- |+| Unknown/unreadable outcomes could allow later writes | Only understood authoritative commitment advances execution; unknown result stops without fabricated receipt state. |+| Historical item isError omitted | Preserve item flag separately from aggregate flag. |+| Transient results described as durable outcomes | Do not promise terminal retention for transient rejection/in_progress/uncertain responses. |+| Shape/domain failure boundary ambiguous | Whole-request rejection for type/safety/structure errors; individual failure for invalid domain values or missing status-comment author; diagnostics include indexes. |+| UUID normalization could change key binding | Normalize only collision detection/mapping, preserve original operation arguments. |++Both peers agreed with these resolutions. The API peer additionally required lossless unknown-field/raw-text preservation. The recovery peer required unknown-expiry guidance and the historical-canonical caveat above. These were incorporated. There was no unresolved divergence or blocking peer finding; the user still owns the proposed behavior choices.++## Validation and coordination++The requirements contain six one-line stories and 32 unique EARS acceptance criteria with granular anchors. A source-level document check verified anchors, keywords, Markdown line breaks and clean whitespace. This is document validation, not implementation testing. Requirement 6 defines the eventual meaningful automated scenarios, including failures after commit and historical replay parity.++T63 remains sole writer of MCPServer/MCPTypes/common dispatch/schema wiring until coordinated handoff. T2383 confirmed historical T2380 results are authoritative and shared serialization must not override retryAction or reread live state. T2383 reported approved latest-only 2026-07-28 scope; its requirements and concrete adapter remain under their own approval gates. T2384 does not require legacy JSON-RPC arrays. Historic unknown-key collisions must not be overwritten by supplemental classifications or links; installed-client migration readiness remains a separate reported blocker. Approved T63/T2382 specs were inspected read-only; frozen cursor revisions and comment-covered canonical r1 remain protected. No T2381 dependency is introduced.++## Requirements gate (closed by explicit approval)++**Do the requirements look good or do you want additional changes?**++Approval includes the proposed 50-item bound, UUID-only targets, one operation per task, stop-on-first-unsuccessful execution, receipt-blind advisory preview, standalone-comment precondition behavior, and the replay/continuation limits above. The parent can collect changes before approval. Design starts only after explicit requirements approval; task approval and implementation authorisation remain separate.
specs/batch-task-mutations/requirements.md Added +99 / -0
diff --git a/specs/batch-task-mutations/requirements.md b/specs/batch-task-mutations/requirements.mdnew file mode 100644index 00000000..aa7e872e--- /dev/null+++ b/specs/batch-task-mutations/requirements.md@@ -0,0 +1,99 @@+# Requirements: Batch Task Mutations++Ticket: T-2384  +Review status: approved in parent at `Sentinel_35dae4e67398819184369b41649ec75b`, including final transport clarification in commit `9b5122c`.++## Introduction++Agents consolidating tasks need to preview and submit a canonical task update, duplicate status changes and reasons with fewer round trips. This feature provides explicit ordered task operations with item-level saved outcomes and retry protection in the originating local store. It makes partial progress visible so interrupted work can be reconciled without repeating effects.++## Non-Goals++- Whole-batch atomicity, rollback of earlier committed items, compensation, or global CloudKit transactions.+- Automatic duplicate matching, canonical-task selection, duplicate links, or dependence on T2381.+- Task creation, project/milestone mutation, arbitrary tool invocation, App Intent batching, or a new authorization model.+- Multiple operations on the same task in one submission, implicit revision chaining, or merging property and status edits into a new combined operation.+- New durable batch-key storage, longer T2380 retention, or automatic resubmission after expiry/across stores.+- JSON-RPC transport batch changes, protocol-version migration, or extending T63's five-second read deadline contract.++## Requirements++### 1. Explicit Bounded Operations++**User Story:** As an MCP caller, I want one domain batch of explicit task operations, so that I can submit a consolidation plan efficiently.++**Acceptance Criteria:**++1. <a name="1.1"></a>The system SHALL expose a domain batch tool accepting an explicit dry-run or execute mode and 1–50 ordered items supporting only `update_task`, `update_task_status`, and `add_comment`; a domain batch SHALL remain one tool call independent of any JSON-RPC transport array.  +2. <a name="1.2"></a>Each item SHALL identify its target by `taskId` UUID, declare a non-empty unique client `itemId`, and supply an explicit `idempotencyKey` matching `[A-Za-z0-9._:-]{1,128}`; update and status items SHALL also supply `expectedRevision` matching `r1:[0-9a-f]{64}`.  +3. <a name="1.3"></a>WHEN the outer request or any item's shape is invalid, including unsupported fields/operations, malformed safety inputs, duplicate item IDs, duplicate tool/key pairs, duplicate target UUIDs after UUID normalization, or an out-of-range item count, the system SHALL reject the entire request before executing any item and SHALL report validation diagnostics correlated by input index and item ID when usable, without accepting keys. Wrong JSON types and malformed safety formats SHALL be whole-request shape failures; invalid status/type/priority values and missing status-comment authors SHALL be item domain failures.  +4. <a name="1.4"></a>The system SHALL retain each operation's existing field semantics and normalization, including atomic status-plus-comment with its required author, property-update milestone validation, and standalone `add_comment` without a revision precondition; a batch SHALL NOT weaken required inputs or infer target tasks from descriptions.  +5. <a name="1.5"></a>WHEN a new item is attempted, the system SHALL validate unambiguous task identity, supported references, current local preconditions, and the existing server/store write-availability restrictions before committing its domain effect; a lookup, comment-fetch, or validation failure SHALL NOT be interpreted as a missing permission or empty successful record.  ++### 2. Advisory Mutation-Free Preview++**User Story:** As an MCP caller, I want to inspect every proposed effect before submission, so that I can correct invalid or stale plans.++**Acceptance Criteria:**++1. <a name="2.1"></a>WHEN mode is dry-run and the request shape is valid, the system SHALL validate every item's current local identity, references, preconditions, normalization and domain constraints without stopping at the first invalid item, and SHALL return ordered valid/invalid/unavailable diagnostics with client mappings and observed record/revision when obtainable.  +2. <a name="2.2"></a>A dry run SHALL create or modify no domain records, timestamps, comments, display-ID allocations, durable keys, receipts or guard state, SHALL perform no cleanup/recovery or save of pre-existing pending edits, and SHALL leave pending edit state unchanged.  +3. <a name="2.3"></a>A valid preview SHALL describe the normalized proposed changed fields and status/comment effects without inventing committed timestamps, comment identities, saved revisions or replay expiries; invalid/unavailable previews SHALL distinguish caller mistakes, revision conflicts and failed state validation.  +4. <a name="2.4"></a>The preview SHALL explicitly report that retry-key state is unchecked, that it reserves neither keys nor target revisions, and that submission independently revalidates new writes or replays retained outcomes; preview validity SHALL NOT promise write availability, durability, identical later results, or imported CloudKit freshness.  +5. <a name="2.5"></a>WHEN comment bodies are excluded from observed preview records, the returned task revision SHALL remain the authoritative comment-covered `r1`; projection SHALL NOT remint a revision from the visible fields.  ++### 3. Ordered Per-Item Application++**User Story:** As an MCP caller, I want explicit partial-commit semantics, so that I know which effects survived a failed submission.++**Acceptance Criteria:**++1. <a name="3.1"></a>WHEN mode is execute and the request shape is valid, the system SHALL attempt items in input order, advance to the next item only after an understood authoritative committed outcome, and retain each committed item independently; it SHALL NOT claim whole-batch or cross-device atomicity.  +2. <a name="3.2"></a>WHEN an attempted item returns rejected, in_progress or uncertain, the system SHALL stop further attempts and return every remaining item as not_attempted with the blocking item ID; transient rejection/in_progress/uncertain responses SHALL NOT be described as durably terminal unless their authoritative outcome establishes that; earlier committed effects SHALL remain committed.  +3. <a name="3.3"></a>WHEN status and an accompanying comment form one item, the system SHALL preserve T2380's both-or-neither persistence and replay boundary; an uncertain outcome SHALL refer to the whole item rather than permit a partial status/comment result.  +4. <a name="3.4"></a>WHEN a new update/status item's locally observed revision has changed since preview or another read, that item SHALL return `REVISION_CONFLICT`, current record/revision and no accompanying effect; prior successes SHALL NOT override this conflict.  +5. <a name="3.5"></a>WHEN execution is interrupted before later items begin, the system SHALL perform no background continuation of unstarted items; unavailable response delivery SHALL NOT imply that already attempted items had no effect. Interruption SHALL mean observed cancellation or execution failure, not merely a caller timeout or lost response whose cancellation the server has not observed.  ++### 4. Item Keys, Replay and Safe Continuation++**User Story:** As an MCP caller, I want existing retry guarantees for each item, so that missing batch responses do not duplicate comments or edits.++**Acceptance Criteria:**++1. <a name="4.1"></a>Each item's key SHALL retain T2380's local-store/tool namespace and canonical operation-argument binding; outer mode, ordering, client item ID and any batch correlation ID SHALL NOT create a new durable namespace or change the underlying operation payload. UUID normalization SHALL serve collision detection/mapping only and SHALL NOT change original argument spelling used for receipt binding; a differently spelled UUID argument under a retained key remains subject to T2380 payload comparison.  +2. <a name="4.2"></a>WHEN a retained item key is retried with identical operation arguments, the system SHALL return its authoritative saved outcome before checking current target existence, revision or domain validity, even after later edits/deletion or restart; changed arguments under that key SHALL return `IDEMPOTENCY_KEY_REUSED` with no new effect.  +3. <a name="4.3"></a>WHEN a completed item is replayed, the system SHALL preserve its original normalized record/revision, accepted/outcome/retryAction fields, original completion/expiry, and missing/null distinctions; replay SHALL NOT reread live state to replace them or extend the guaranteed seven-day window.  +4. <a name="4.4"></a>WHEN simultaneous submissions share an identical item key/request, the system SHALL preserve T2380's at-most-one logical effect and committed/rejected replay, in_progress or uncertain response; one response's uncertainty SHALL NOT authorize a second key for that effect.  +5. <a name="4.5"></a>The batch contract SHALL instruct callers to retain item arguments, keys and returned expiries, retry identical retained requests in the originating store after response loss, and stop for reconciliation when commitment is uncertain or a replay guarantee is expired/unavailable across store scope; the system SHALL NOT automatically rotate keys, repair guards or apply compensation. WHEN the first response was lost and no replay expiry is known, callers SHALL retain the original submission time as reconciliation context and SHALL NOT assume indefinite replay protection; absent/removed receipts SHALL NOT be presented as proof that the original effect never happened, and expired removed keys MAY execute as new requests under T2380.  +6. <a name="4.6"></a>WHEN a retained item conclusively rejected without effect is corrected, the system SHALL require a new item key for changed arguments; not_attempted items SHALL have no new key acceptance attributable to that batch and MAY be resubmitted with their unchanged keys.  +7. <a name="4.7"></a>The outer batch SHALL provide no durable whole-response replay guarantee; an identical batch retry MAY replay earlier items and execute previously not-attempted items, SHALL still stop on its first unsuccessful item, and SHALL describe this continuation explicitly. A replayed canonical update SHALL NOT certify its current contents; callers requiring a current canonical-state condition before new duplicate closures SHALL reconcile current state before submitting those closures, rather than expect receipt replay to revalidate it.  ++### 5. Correlated Records and Machine-Readable Outcomes++**User Story:** As an MCP caller, I want a complete item mapping and saved outcomes, so that I can verify partial progress without additional successful-write readbacks.++**Acceptance Criteria:**++1. <a name="5.1"></a>A completed batch response SHALL identify its contract version, mode and per-item atomicity, return an entry for each input item in input order with client item ID, operation, key and target UUID, and identify any stopping item and whether all items committed; preview responses SHALL clearly identify preview validity instead of commitment.  +2. <a name="5.2"></a>Every attempted execution entry SHALL preserve the complete authoritative T2380 outcome including unknown JSON fields, original result text bytes, and original item-level result `isError` separately from aggregate `isError`, preserving committed/rejected/in_progress/uncertain classification, accepted true/false/null, saved records/revisions/comments when present, error code/currentRecord/retryAction and terminal replay expiry when present; batch-local not_attempted entries SHALL NOT fabricate a receipt, saved record or expiry.  +3. <a name="5.3"></a>WHEN state cannot be read or verified, or the aggregate result cannot be serialized/delivered, the system SHALL stop further execution unless an understood authoritative result proves commitment, return remaining items as not_attempted when delivery is possible, preserve available original item result text/error flag without inventing a receipt outcome, and report an explicit aggregate failure; the system SHALL NOT present an empty successful batch, mark committed items rejected, fabricate certainty, or recommend a fresh key for an unresolved attempted effect.  +4. <a name="5.4"></a>The batch result SHALL expose a structured result value through the T2383 result contract and compatible JSON text with the same semantic batch data; adaptation of nested stored outcomes SHALL preserve their historical meaning without rewriting their receipts, and error categories SHALL NOT override their retryAction.  +5. <a name="5.5"></a>Execution responses containing any rejected/in_progress/uncertain/not_attempted item and previews containing any invalid/unavailable item SHALL set tool-level `isError` true; full commits and fully valid previews SHALL NOT set `isError` true. Protocol/outer-input failures SHALL remain distinguishable from domain item failures.  +6. <a name="5.6"></a>Saved and replayed item records SHALL identify the commit-time snapshot rather than promise equality with later live readback; existing text payloads, frozen cursor revisions and canonical comment-covered `r1` semantics SHALL remain compatible.  ++### 6. Verifiable Recovery and Compatibility++**User Story:** As a maintainer, I want observable contract tests, so that batches cannot weaken existing writes or concurrent read guarantees.++**Acceptance Criteria:**++1. <a name="6.1"></a>Automated verification SHALL cover the preview/submission of one canonical description update followed by distinct duplicate status-plus-reason items, and SHALL verify ordered saved records and comment identities without automatic duplicate decisions.  +2. <a name="6.2"></a>Automated verification SHALL cover zero-effect dry runs with pending edits, malformed whole-request rejection, same-task/alias/key collisions, stale and ambiguous targets, reference and comment-fetch failures, stop-after-failure, interrupted iteration, and exact mapping of unattempted items.  +3. <a name="6.3"></a>Automated verification SHALL cover matching/mismatched item retries, batches regrouping the same underlying item, shared-key concurrency, later edits/deletion before replay, retained no-effect rejection, restart recovery, uncertain commitment, expiry limitations including a lost first response with unknown expiry and retry after receipt removal, and aggregate serialization/delivery failure after an item commits.  +4. <a name="6.4"></a>Automated verification SHALL preserve standalone write behavior and the transport ordering supported by the approved T2383 protocol contract, comment-covered revisions with omitted bodies, frozen snapshot/cursor records, and semantic text/structured parity for historic receipt outcomes; these checks SHALL NOT require legacy JSON-RPC arrays.  ++## Approved Requirements Gate++Approved choices: 1–50 operations; UUID-only task selectors; at most one operation per task; stop on first unsuccessful item; advisory all-item preview with retry-key state unchecked; standalone comments retain the existing absence of revision checking. These choices are settled for design; changes require reopening the requirements gate.++The full-spec scope and feature name were approved in the parent conversation at `Sentinel_4fd40b3fecf48191a57ce03897d3e7ec`. Requirements were approved at `Sentinel_35dae4e67398819184369b41649ec75b`; design was approved at `Sentinel_717be95229c48191a7c41b6e5e467e4c`; task plan and conditional implementation were approved at `Sentinel_edf7fd12288c819192ad45a04154372a`; dependent work awaits its documented delivery/ownership/test-slot conditions.
specs/batch-task-mutations/scope.md Added +65 / -0
diff --git a/specs/batch-task-mutations/scope.md b/specs/batch-task-mutations/scope.mdnew file mode 100644index 00000000..81e0af7a--- /dev/null+++ b/specs/batch-task-mutations/scope.md@@ -0,0 +1,65 @@+# T-2384 — Batch task mutations: scope review++Status: scope/name approved in parent at `Sentinel_4fd40b3fecf48191a57ce03897d3e7ec`. Requirements/design/tasks remain separate gates; no implementation is authorised. The original proposals below inform the requirements review.++## Verified starting point++- Canonical repository: `/Users/arjen/projects/personal/transit`.+- Canonical `main`, `origin/main`, and `HEAD` all resolved to `201205bd4e786c7f152d8f99006b37da7da888c7` immediately before worktree creation on 2026-10-03. This is merged T2380 (#249), following T2379 (#248).+- Dedicated branch: `T-2384/batch-task-mutations`; worktree: `/Users/arjen/Documents/Codex/2026-10-03/task-4/transit`. Its HEAD and merge bases with both main refs equal that SHA.+- Existing canonical untracked `.kiro/` and every other worktree were preserved.+- A read-only `require_escalated` probe and escalated `git worktree add` both succeeded under per-command auto-review. No global permission changes were requested.+- Live running `query_tasks` schema was inspected, then full T2384 and T2383 records were fetched. T2384 is a medium-priority feature in Idea, revision `r1:a4e89fd41bf00148d8efd03906ea61abcdb86060848ce75011c08efc1cf92a07`.++## Workflow and feature name++Recommend the **full Starwave spec process**, named **`batch-task-mutations`**. The public mutation contract, partial failure behavior, and replay semantics are expensive to reverse; atomic versus per-item application also presents a real user-owned decision. The requested substantive full-spec process independently requires this route.++The local Transit router and Starwave creating-spec, requirements, design, and tasks instructions were read. Repository `CLAUDE.md`, `.claude/rules`, merged write-safety specs/source, and the approved T63/T2382 designs were inspected. No repository `AGENTS.md` or `.agents/skills` directory was present. Local Transit memory was read without changes.++Gate sequence: scope/name approval → requirements and clarifications → requirements review/approval → design, ADRs and review/approval → Rune task plan and review/approval. Implementation remains a separate authorisation. Creating the isolated spec branch early follows the explicit delegation; it is not approval of scope or implementation.++Formal requirements/design reviews will use the documented internal peer fallback: design critic followed by at least two independent peer lenses. External model disclosure is not authorised by this delegation. No peer review has yet been claimed or performed for this scope gate.++## Recommended product scope++Provide one bounded **domain tool** for explicit task property updates, task status changes (including their existing atomic reason/comment), and standalone comments. A domain batch is a single `tools/call` carrying item operations; it is separate from an HTTP JSON-RPC array of independent requests. Existing transport batching keeps its current ordering and error behavior, and gains no transaction promise from this tool.++The motivating flow updates a caller-selected canonical task, closes caller-selected duplicate tasks with reasons, and returns saved records/outcomes in input order for verification. Matching duplicates, choosing the canonical task, duplicate links, and consolidation policy remain with the caller; T2381 is not a dependency. Task creation, project/milestone mutations, automatic compensation, and cloud-wide transactions are outside the initial proposal.++Recommend **ordered per-item commits**, rather than a whole-batch transaction. Each submitted effect uses the existing T2380 protected tool, explicit caller item key, and expected revision where that tool requires one. A status change plus its reason/comment retains the existing single-item atomic boundary. Earlier committed items remain committed if a later item fails. This reuses authoritative acceptance, durable receipts, payload binding, recovery classification, and seven-day completed-result retention; unresolved bindings do not expire under that policy.++Recommended execution policy: validate the complete outer shape before any execution; execute in caller order; stop after the first rejection, in-progress, or uncertain result; return explicit not-attempted outcomes for the remainder. This reduces the risk of closing duplicates after their canonical update failed. No rollback of earlier successes is promised. An alternative continue-on-conclusive-rejection policy can be discussed at the requirements gate.++Recommend a small explicit item bound (initial candidate: 50, to confirm in requirements), unique client item IDs, and explicit item idempotency keys matching T2380. The outer batch correlation ID is not a new durable idempotency namespace and must not imply whole-response replay. Replaying a batch recovers each retained item independently; changing item arguments under an existing key fails under T2380's binding rules. Missing responses, interrupted iteration, expired receipts, and ambiguous store scope require documented reconciliation, not fresh-key resubmission.++Recommend initially rejecting repeated resolved task identities in a batch. Same-task workflows use the existing status-plus-comment operation where possible or a later submission with the resulting revision. This avoids inventing revision chaining between items during the first version. If combined property/status/comment edits on one task are required in one submission, they need an explicitly approved item contract rather than reusing a stale pre-batch revision for multiple writes.++## Preview, outcome, and retry contracts to settle++A dry run performs no domain mutations, display-ID allocation, receipt/guard reservation, cleanup, recovery, or baseline save of pending edits. It validates supported input, resolved identities/references, current revisions, and observable domain constraints, returning proposed normalized effects and per-item diagnostics. It is advisory: a later submit revalidates against current state and cannot treat preview success as a reservation. Domain failure or unavailable storage is an explicit diagnostic, never an empty success.++Submission outcomes preserve T2380 distinctions: committed, rejected, in_progress, uncertain, plus batch-local not_attempted. Every item retains client mapping, tool/key, resolved identity when known, accepted state, machine-readable error/retry direction, and saved record/revision when committed. A rejected item can already have a retained accepted receipt; accepted is not synonymous with committed. Uncertain items must not invite a new key. Saved receipt records represent that item's commit and can differ from a later live readback.++A lost outer response is not evidence of no effects. Retry the identical retained item requests in the originating store while their guarantees apply; stop/reconcile unresolved outcomes. No automatic replay past expiry or across local-store scopes is promised. Aggregate serialization failure must not relabel committed items as rejected; outcome recovery remains item-key based even if the full response cannot be delivered.++## Integration and concurrent ownership++| Area | Proposed boundary |+| --- | --- |+| T2380 `Writes/MCPWriteCoordinator`, command, snapshots and receipts | Reuse authoritative per-item execution. Do not open, alter, reset or repair production guard stores during specs. Implementation must not duplicate recovery machinery. |+| New batch request/preview/orchestration types | Prefer feature-local MCP files; proposed design must establish a truly read-only validation boundary rather than calling write coordinator for preview. |+| T63 `MCPServer`, `MCPTypes`, common handler dispatch and schema wiring | Sole writer remains T63 until parent coordinates a handoff. Batch tool registration, nested item schema support, and dispatch must be staged as an interface request, not concurrent edits. |+| T63 read deadlines/admission/publication | Domain mutations remain writes. A dry run's read-only nature does not automatically classify it under existing covered-read deadlines; classification and immutable preview DTOs need explicit coordination. Do not reuse cursor publication as a write transaction. |+| T2382 capture and reusable snapshots | Read-only design reference. Frozen cursor/snapshot revisions remain unchanged; preview and submission use current authoritative task state. |+| T2383 serialization | Coordinate a common batch envelope and nested T2380 outcomes, structuredContent/text compatibility, error categories, normalized saved fields, and serialization failure semantics before shared wiring. Historical receipt JSON remains the source for replay; adding structured output must not rewrite receipts or remint records. |++Canonical `r1` includes comments even when response comment bodies are omitted. A preview or projected result must preserve that token rather than hash its output fields. Current text JSON payload compatibility must be retained. The task snapshot and comment fetching paths can fail; those failures cannot masquerade as a successful preview or a clean revision.++No heavy builds or tests were run; T63 owns that slot. At the initial scope gate, no production source, live ticket status, write guards, recovery actions, pushes, merges, deployments, or approved peer specs were changed. Following scope approval, the workflow status transition to Spec was committed through the authorised MCP tool with its comment and fresh key.++## First review gate (parent to ask user)++Approve **full spec**, feature name **`batch-task-mutations`**, and the initial scope: bounded explicit update/status/comment operations with a no-write dry run, ordered per-item commits, and T2380 item-level replay protection?++Recommended starting semantics are stop-on-first-unsuccessful item and one resolved task per batch; both remain proposals for requirements, not approved decisions. The parent may collect changes or an alternative name. On explicit scope approval, move T2384 to Spec using its current revision and a fresh key with the workflow comment, then begin requirements. Requirements, design and tasks each require their own explicit gate.
specs/batch-task-mutations/task-review.md Added +76 / -0
diff --git a/specs/batch-task-mutations/task-review.md b/specs/batch-task-mutations/task-review.mdnew file mode 100644index 00000000..de149548--- /dev/null+++ b/specs/batch-task-mutations/task-review.md@@ -0,0 +1,76 @@+# T-2384 Task Plan Review++Status: tasks and conditional implementation approved by owner in parent at `Sentinel_edf7fd12288c819192ad45a04154372a` for plan `d592907`. Independent task1 may start; external delivery, ownership and test-slot gates remain.++Review [Rune task list](tasks.md), [approved design](design.md), [requirements](requirements.md), and [decision log](decision_log.md).++## Execution dependencies outside this Rune file++These are owner-controlled readiness conditions, not locally completable tasks. Rune blocked_by links describe the local DAG only; an apparently ready task must also satisfy these conditions.++- Task approval and conditional implementation authorisation were granted at Sentinel_edf7fd12288c819192ad45a04154372a. Start independent safety fixtures only until the remaining readiness conditions are satisfied.+- Before task 2 coordinator patch: agree write-coordinator ownership with parent/T63 and reconcile delivered shared changes. No independent shared edits; proposed patch is applied only by the owner or after explicit handoff. Task 1 can draft isolated fixtures without production changes.+- Before tasks 3–6 and 11–14 consume common interfaces: T63 shared handoff followed by T2383 delivery of approved immutable source/lossless JSON, encoder/full ready fallback, richer schema and provider seam. Require delivered T2383 task 15 (`gpzncvz`) commit/interface, including completed task 3 (`gpzncvn`, lossless source), 5 (`gpzncvp`, presentation), 7 (`gpzncvr`, complete bytes/fallback) and 9 (`gpzncvt`, output/schema). These are current draft Rune IDs, not delivery or task approvals. No guessed production interface, no duplication of serializer. T2383 validates this with a synthetic provider aggregate and has no dependency on production mutate_tasks or these final batch tests.+- Before tasks 13–14 shared wiring: T63 agreed integration ownership/handoff plus delivered common provider registration; one patch, no competing source edits.+- Before executing app tests: explicit implementation authorisation and T63 release of the heavy-test slot. Tests use isolated owning fixtures; no live guard store/recovery actions.+- Modern real-client activation remains T2383's explicit client-readiness prerequisite; tasks use automated capability fixtures without changing settings. No config/activation/deployment task is included here.++Sequence is T63 handoff → T2383 synthetic-tested common delivery → T2384 consumer/real registration. No reverse edge exists. One stream avoids conflicting coordinator/helper/integration ownership; seven adjacent RED/GREEN pairs add substantial behavior without trivial setup tasks.++## Verified external Rune references++Read-only sibling list: `/Users/arjen/Documents/Codex/2026-10-03/task-3/transit/specs/structured-mcp-results/tasks.md`.++| T2383 task | Stable ID | Required delivery |+| --- | --- | --- |+| 3 | gpzncvn | Owned lossless JSON documents/source factories |+| 5 | gpzncvp | Source-only presentation/provider selectors |+| 7 | gpzncvr | Complete result bytes/provider-owned mutation fallback; synthetic batch fixtures |+| 9 | gpzncvt | Output descriptor/schema providers |+| 15 | gpzncvz | Common source/schema/fallback plus modern dispatch integration after T63 handoff; delivered commit/interface is the consumer gate |++T2383 task 22 (`gpzncw6`) uses synthetic batch/current tool contracts and never waits for production mutate_tasks. Its covered-read task 17 is outside batch consumption. Cross-file prerequisites are recorded here rather than invalid foreign stable IDs in the local Rune blocked_by DAG. Reconcile references if sibling IDs change, and record the actual delivery commit before executing dependent consumers.++## Early risks++Saved-only observations and dirty coordinator routes are proved by tasks 1–2 before all later work. Complete fallback/resource behavior is proved by tasks 3–4 before execution and final integration. Failed safety fixtures block availability; flushing, rolling back UI edits or guessing an encoder is never a fallback.++## Coverage and required checks++| Approved criteria | Rune tasks |+| --- | --- |+| 1.1–1.4 | 5–8 and 13–14 |+| 1.5 | 1–2, 7–10 |+| 2.1–2.5 | 1–2 and 7–8; omitted-comment parity also 13–14 |+| 3.1–3.5 | 3–4 and 9–10 |+| 4.1–4.7 | 1–2, 5–6 and 9–10 |+| 5.1–5.6 | 3–4, 7–12 and 13–14 |+| 6.1–6.4 | Early fixtures plus 9–14 integration/regression fixtures |++Rune list rendered all 14 pending tasks without parsing warnings. One stream has one locally ready task and 13 blocked tasks; no work has started. Every GREEN is adjacent to and blocked by its RED. All dependency stable IDs resolve to earlier tasks, yielding an acyclic graph; both design risks block later consumers. Automated document checks cover all 32 requirement anchors and review links. No noncoding deployment/config/client activation tasks, decorative phases, independent parallel streams or orphan final components were added.++## Internal review synthesis++The local design critic reviewed first, followed by two independent internal peers focused on recovery/correctness and integration/maintainability under the documented fallback. No external model disclosure occurred.++| Reviewer | Findings and disposition |+| --- | --- |+| Critic | Narrow preview spies to new effect identities/timestamps, allowing saved UUID/date parsing. Separate post-await UI edits from impossible interleaving during clean synchronous phases. Name the external seam gates at their first consumer and correct MCP/Writes paths. All corrections adopted; final critic reports no blocker. |+| Recovery peer | Confirms 32-criterion coverage, early safe-context/fallback tests, historic replay/cancellation and isolated synthetic then real postcommit encoding tests. Stale design title/status metadata fixed; no substantive blocker. |+| Integration peer | Confirms incremental seven-pair plan, schema/domain boundary, one-stream ownership, early risks and noncircular external delivery. T2383 supplied current draft external Rune IDs, verified locally and recorded below; delivery remains a gate, no blocker. |++Consensus: plan is ready for its approval gate. No substantive reviewer divergence remains. What only implementation can establish—saved-only multi-context behavior, every dirty coordinator phase and complete fallback under encoder/resource faults—has explicit early RED/GREEN fixtures; a failed boundary blocks batch availability. External seam delivery, parent ownership/handoff, implementation authorisation and T63 test-slot release remain execution conditions, not assumed approvals. No app builds/tests, production source changes, guard changes or recovery actions were performed during planning.++## Approved task gate (historical request)++**Do the tasks look good?**++Parent routes this question to the user after required reviews. Task approval completes the spec plan; it does not silently authorise production implementation, shared-file handoff, heavy-test scheduling, settings, push, merge or deployment.++Owner approved the task plan and implementation once shared dependencies are ready at Sentinel_edf7fd12288c819192ad45a04154372a. This answers the gate; no further approval is requested for already authorised independent work.++## Actual external delivery consumed++Verified T2383 `DELIVERED15/gpzncvz` at handoff `b21e358c8a5ea1e287afe332c1fc50d83303ce19`, runtime source `543c4a757e4cb7f9f73c973d7cb1be5725c8f342`. All manifest source hashes match. Consumer dependency delivery is now satisfied; exact ten-file pure seam import `fe1c57f` preserves the coordinator/App/project/Makefile. Task3 resumes fixture preparation against real APIs. Later common16–22 are not reverse dependencies.++Before Task3 app-host RED, this older worktree still requires the parent-selected isolated foundation and containment-owned narrow App/project integration described in the delivered development-isolation component handoff. No runnable app command is claimed until signed isolated host preflight and exact suite inventory can be verified. Intended focused suites: `TransitTests/MCPBatchTaskEvidenceTests` and `TransitTests/MCPBatchTaskEncodingTests`. Request an exclusive slot only after that readiness exists. No old test-quick/production host fallback, client activation or live mutation is permitted.
specs/batch-task-mutations/task4-green-review.md Added +16 / -0
diff --git a/specs/batch-task-mutations/task4-green-review.md b/specs/batch-task-mutations/task4-green-review.mdnew file mode 100644index 00000000..5af9e8e9--- /dev/null+++ b/specs/batch-task-mutations/task4-green-review.md@@ -0,0 +1,16 @@+# Task 4 independent source review and GREEN readiness++Reviewed runtime-pending source `390fae8`, bounded-field correction `123dc9c`, and null compatibility correction `28bee6ae0bf48a756da7220a5840ba24cb0e7aa3`. Mode: internal independent root critic, separate from the implementation worker; no external disclosure/service.++Result: CLEAR for focused GREEN execution, not a runtime acceptance claim.++- Classifier preserves the entire immutable input source, optional error flag, raw text and parsed unknown/null/numeric evidence. Only supported committed proof advances. Numeric equality to1 is decimal-lexeme based; opaque fields use exact scalars; UUIDs normalize comparison only; revisions retain their saved spelling. Canonical UTC millisecond timestamps roundtrip and compare expiry with completion, never with the current clock.+- Supported failure results remain distinct from malformed evidence. Review tightened typed error/code/message and outcome/accepted/retry consistency without a business-code allowlist or rewriting retryAction.+- Review corrected benign error/retryAction nulls: explicit null remains in saved evidence and does not alone contradict commitment. Non-null contradictions remain unavailable. Oversized bounded safety fields are length-checked before array allocation.+- Compact provider-owned serialization_failed source is shallow and omits item IDs, raw records and links. It retains original index/tool/key/task UUID and unestablished effect evidence.+- The private prepared-response initializer requires actual complete correlated common encoder bytes. Preparation failure yields no dispatch capability. Selection supplies already prepared immutable bytes through the delivered common selector; no encoder/checkpoint callback is retained or invoked for fallback selection. Real executor construction must require this capability when introduced in the later approved task.+- Coordinator, common imports, App/isolation files and original13-declaration/52-case fixtures retain recorded hashes. Separate adapter/boundary suites add8 declarations/32 cases, total21/84. Full lint430files passed on initial source; later corrections passed targeted strict lint, parse-only and whitespace checks. No compiler/app/runtime verification was performed in this preparation.++Concrete bounded sequence in `.codex-cache/task4-green-readiness/guarded-commands.json`: configuration guard; private incremental Transit/Debug arm64 build with locked packages, serial1 job and local signing; NEW signed source-pinned unit-test host launch configuration; exact four-suite21-declaration discovery; serial selected bodies requiring84 actual passes. New Task4GreenBuild/Task4Green result paths preserve the prior RED evidence. Prior dedicated smoke was accepted; its isolation inputs are unchanged.++Before accepting GREEN, verification must answer: does the signed host retain the development identity/no CloudKit-push-groups/explicit unit-test guard; does compiled inventory exactly match21 declarations; do all84 bodies pass; and do owned workers drain with finalization limits reported separately? Task4 remains in progress until actual GREEN. Parent exclusive-slot START is required before any app job.
specs/batch-task-mutations/task5-red-review.md Added +11 / -0
diff --git a/specs/batch-task-mutations/task5-red-review.md b/specs/batch-task-mutations/task5-red-review.mdnew file mode 100644index 00000000..ce34b381--- /dev/null+++ b/specs/batch-task-mutations/task5-red-review.md@@ -0,0 +1,11 @@+# Task 5 parser and schema RED source review++Reviewed source: `ff606929de9eae8da336332b68e7b0ff8ed6f6d2`. Mode: independent internal root review, separate from the implementation worker. External review services were not used.++The declaration-only parser accepts the delivered immutable JSON document and exposes either a completely validated request or indexed input diagnostics. Its MainActor items retain original logical arguments and the existing write command, with normalized UUID identity separate from caller spelling. No service, model context, receipt store, coordinator or key-admission callback is reachable through this seam. The schema seam supplies a rich logical JSON document; shared registration remains deferred. Both entry points explicitly throw `notImplemented`, providing runtime RED boundaries without implementing Task 6.++The 17 declarations /109 intended bodies cover request bounds, exact modes and operations, missing/unknown fields, strict JSON types, UUID/key/revision formats, collision namespaces, preserved input order, original string bytes and number lexemes, domain string admission, no-op update, and rejection of a malformed final item before any earlier admission. Negative fixtures require INVALID_INPUT with a nonempty field and usable input mapping; representative safety and type cases assert the exact field. Nested schemas assert exact argument properties and required sets, closed branches, string-only metadata, UUID/safety formats, and descriptive domain values without enum/const or conditional-author constraints. Add-comment has no revision precondition.++Review corrections incorporated before commit: exact diagnostic fields; newline safety boundaries; explicit successful numeric-lexeme replacement; UTF8/scalar spelling assertions; precise schema fields and required sets; metadata Boolean/null cases; and an update with only required safety fields. The actual existing Bool/Int helpers already reject Boolean-number/string coercion; the review does not attribute a nonexistent coercion defect to standalone commands.++Source review is clear. Prior 84 evidence/fallback cases and shared source, coordinator and isolation inputs are unchanged. This is source-only review: no app build, compiled inventory, runtime RED or Task 5 completion is claimed. Execution requires the parent's exclusive-slot START, successful isolated configuration/build/signed-host checks, exact 17-declaration discovery, and actual 109-body accounting. Task 6 remains pending. Live writes and routine phone uploads remain held.
specs/batch-task-mutations/task6-green-review.md Added +15 / -0
diff --git a/specs/batch-task-mutations/task6-green-review.md b/specs/batch-task-mutations/task6-green-review.mdnew file mode 100644index 00000000..9df16478--- /dev/null+++ b/specs/batch-task-mutations/task6-green-review.md@@ -0,0 +1,15 @@+# Task 6 parser and schema GREEN source review++Reviewed source: `565c336afd4c02bbb4d52c34aa9904ee5d0eca41`. Review mode: independent internal root critic, separate from the implementation worker. No external review service was used.++Source review is clear. The request's private initializer permits construction only after the full bounded closed shape and collision checks succeed. Parsing reaches no services, contexts, receipt/guard stores or coordinator. Items retain original logical arguments and their existing validated MainActor command; normalized UUID identity is used only for mapping/collision detection. String domain values and conditional status-comment authors pass shape validation for later domain checks. Add-comment has no revision precondition; updates with only safety fields remain valid shapes.++Structural names, opaque caller IDs and tool/key identities use exact UTF8 comparisons rather than Swift's canonical String equality. Metadata string values are retained without trimming. Canonically equivalent metadata member names that cannot survive the existing dictionary binding reject the whole input with indexed INVALID_INPUT diagnostics before command construction. This mirrors the delivered modern request bridge's unsupported-envelope rejection; it neither drops a field nor rewrites historical evidence. Closed-member duplicate checks also protect the immutable-value entry point.++The integer bridge checks decimal mantissa/exponent, mathematical integrality and Int range with checked arithmetic. It never rounds through Double/Decimal and never adds a positivity restriction. Original numeric spelling remains in the logical arguments. The schema derives actual protected field types/required fields, removes displayId, requires taskId, preserves safety formats, and describes captured domain enums without enforcing enum/const on them. Shared definitions and registration remain untouched.++The document entry point delegates to the immutable-value entry point. Coordinated Task 14 wiring must pass the original modern arguments subtree before the generic Any request bridge, preserving original number tokens and exact input diagnostics. This review grants no shared routing edit or ownership handoff.++The original 17 declarations /109 parser cases and prior 84 evidence/fallback cases were independently compared with `dc10b9c`: eight fixture files are byte-identical. Four supplemental declarations /23 cases cover integer boundaries, metadata bridge representation, Unicode structural aliases and raw duplicate member positions. The planned GREEN selection is three suites, 21 declarations /132 bodies.++Targeted lint, syntax parsing, whitespace and full lint passed (438 files). These are source-only checks: no Task 6 app build, typecheck, inventory or runtime GREEN has executed. Task 6 remains in progress. Execution requires the parent's exclusive slot, a rebuilt signed isolated source-pinned host, exact 21-declaration discovery, all 132 bodies passing and owned-process drain. T1734 currently owns the slot. No live writes, routine uploads, common/coordinator edits or Task 7 work occurred.
specs/batch-task-mutations/task7-fixture-lifetime-review.md Added +15 / -0
diff --git a/specs/batch-task-mutations/task7-fixture-lifetime-review.md b/specs/batch-task-mutations/task7-fixture-lifetime-review.mdnew file mode 100644index 00000000..b4f096ca--- /dev/null+++ b/specs/batch-task-mutations/task7-fixture-lifetime-review.md@@ -0,0 +1,15 @@+# Task 7 fixture lifetime correction — independent review++The root reviewed the owned preview fixture correction and off-process cleanup helper independently of the implementation worker. This is source-only readiness for a corrected RED attempt, not Task 7 completion.++The fixture previously deleted its SQLite backing directory in `deinit`, while `TestModelContainer` deliberately retains containers for the process lifetime. The correction preserves that directory until the owned host drains and records an exact prefixed UUID ownership marker. The fixture setup, saved snapshots, pending object identities, descriptors, revisions, symbolic effects, and every assertion remain unchanged. Production normalization/preview shells, coordinator, services, global retention and historical safety fixture remain unchanged.++The cleanup helper defaults to validation. It checks clean pinned source and hashes, run identity and log hash, finite ordered drain times, owned PID absence, exact development temp containment, canonical ownership markers, regular bounded directory contents and guard bytes before any deletion. It rejects replays, interleaved/duplicate markers, old unmarked stores, traversal, links, live owned processes and excessive directories. It sends no signals. All directories validate before deletion; no real store cleanup was executed during preparation.++Independent artifact checks confirmed original runtime log SHA-256 `0d3c110ac3c0c0c0f0756b76f2493c2cc61368f21bf8fabb1338c1ae1d6b0b94`, eight physical run starts, seven automatic restarts and 1,170 vnode-unlinked messages. The original complete run reported 25 declarations/68 bodies, 53 intended placeholder issues and 15 passing existing-service controls. Later partial automatic runs and four unclassified interleaved partial issues remain separate evidence. Samples establish framework waits, not a preview deadlock. The runner-only SIGTERM/exit 143 and verified owned drain are recorded separately; no clean runtime exit or finalized result bundle is claimed.++Source-only checks passed: strict targeted lint, required full lint (444 files), syntax parse, whitespace, a bounded serial three-helper typecheck using the valid attempt-5 app module, and 18 synthetic cleanup-boundary checks. The first typecheck driver flag diagnostic is retained separately; the corrected command exited zero. No new app build, host launch or runtime retry was performed.++Corrected attempt 6 retains the same three suites, 25 declarations and 68 bodies, expecting 53 placeholder issues and 15 independent controls. It requires a fresh signed development-host preflight and exact inventory after the parent grants the exclusive heavy-test slot. Task 7 stays in progress; Task 8 is not started. T2383 owns the current slot.++The historical safety fixture has the same deletion/retention pattern and needs coordinated later assessment; it was not edited within this narrow correction. Actual cleanup requires pinned run/drain evidence, current process checks and the parent route before bookkeeping changes the run HEAD. Old unmarked attempt-5 stores remain untouched.
specs/batch-task-mutations/task7-red-boundary-review.md Added +15 / -0
diff --git a/specs/batch-task-mutations/task7-red-boundary-review.md b/specs/batch-task-mutations/task7-red-boundary-review.mdnew file mode 100644index 00000000..7073db44--- /dev/null+++ b/specs/batch-task-mutations/task7-red-boundary-review.md@@ -0,0 +1,15 @@+# Task 7 corrected RED boundary review++The root independently reviewed the actual corrected run at `e008ad1b46dfab2fc39a128e16546a95220bee39`. Fresh guarded build, signed development-host preflight and exact declaration inventory passed. Console method summaries account for 18 parameterized declarations/61 bodies plus seven standalone bodies: 25 declarations and 68 bodies total.++All 53 issue records are intended `.notImplemented` placeholders: 46 caught errors and seven explicit diagnostic continuations. No issue remains unclassified. The four existing-service baseline declarations account for 15 passing controls. Their assertions and the original preview/validation assertions were unchanged.++There was one physical run, no automatic restart, no vnode-unlinked fault and exactly 48 prefixed fixture directory markers. This establishes that the corrected lifetime preserves backing stores through the test body and eliminates the observed premature-unlink failure. It does not establish successful Xcode finalization: finalization stalled after bodies, both owned processes were sampled successfully, the runner alone received SIGTERM, and exit 143 is preserved separately. The host drained without a signal; the final drain inventory is empty. No finalized xcresult or clean runtime exit is claimed.++The console SHA-256 is `e5c77788ce6ad0bcc1d5dc448060464b0d6ca94a7d717528bbc03fca7fc3b84d`. Raw log, signed preflight, exact inventory, samples, issue classification and drain proof are retained in `.codex-cache/task7-red-attempt6/`. Attempts 1–5 remain separate, including original body results, automatic partial restarts, compiler diagnostics and the earlier lifetime fault.++Before bookkeeping changed HEAD, the pinned marker-only cleanup dry run validated all 48 directories. Deletion then rechecked the same guards and removed exactly those 48 owned directories, with no signals. Historical unmarked stores were untouched. Cleanup is complete; no production guard store or recovery action was involved.++The parent accepted this meaningful RED evidence with the sampled teardown limitation. Task 7 may be complete and Task 8 may proceed with approved source work. Task 8 GREEN runtime requires a new coordinated slot. The historical safety fixture remains unchanged and its separate lifetime assessment is not covered by this run.++Review questions resolved: Are all failures attributable to the intended shell boundaries? Yes, all 53 records were classified. Did the backing-store lifetime fault recur? No observed unlink fault or restart in the single corrected run. Was teardown successful? No; exit 143 and unfinalized-result limits remain explicit. Was cleanup restricted to this run? Yes, the pinned guard admitted and removed exactly its 48 marked directories.
specs/batch-task-mutations/task7-red-review.md Added +33 / -0
diff --git a/specs/batch-task-mutations/task7-red-review.md b/specs/batch-task-mutations/task7-red-review.mdnew file mode 100644index 00000000..df444f23--- /dev/null+++ b/specs/batch-task-mutations/task7-red-review.md@@ -0,0 +1,33 @@+# Task 7 saved-only preview RED source review++Reviewed source: `46363eecd2a929d452297c1abd851cf188efa278`, based on finalized Task 6 `6eae0f30e82263a337d078367463d9419c4587f9`. Internal independent root critic review; the implementation child drafted the source. No external peer service or disclosure was used.++Disposition: source preparation is ready for the exact focused RED run after parent exclusive START. Task 7 remains in progress. This is neither a runtime RED result nor Task 8 implementation authority.++## Boundary and parity findings++- `CommentInputValidation` is a cross-platform pure value declaration. MCP status validation and saved preview remain MainActor; only immutable Sendable JSON/value results leave the boundary. All three new behavior methods explicitly throw `notImplemented`. Existing service and protected-command behavior is unchanged.+- The preview takes only the container, persistence state and saved-read seams. It has no write-coordinator, reservation, receipt or mutation-service dependency. Its descriptor hooks expose task/comment/milestone `includePendingChanges` checks and private-context autosave/no-changes checks. The later implementation must set pending exclusion itself, including milestone descriptors; the fixture never silently repairs a descriptor.+- Owning persistent fixtures use CloudKit-disabled temporary stores and independently reopen them. They compare canonical covered task/comment/milestone fields, including dates and identities, and six entity counts; pending task/comment/milestone insert/edit/delete objects and original shared autosave settings are checked after both normal and failed-read paths. Deferred verification reports readback exceptions rather than swallowing them. A marker and absent receipts supplement these checks without constructing any coordinator or sidecar.+- Tests require every mixed item to receive an ordered valid/invalid/unavailable outcome. UUID cardinality, task/comment/milestone fetch failures, an empty-comment read failure, persistence fallback and revision conflicts stay distinct. Full saved comments contribute to canonical r1 before projection; later independently saved comment evidence invalidates an earlier preview. The actual protected error code is `REVISION_CONFLICT`.+- Pure and integrated status cases retain conditional author semantics: invalid status precedes author validation; any supplied comment requires a nonblank author even when its content is blank; absent comments ignore unused blank authors. Same-status comments do not produce timestamp transitions. Real transitions describe last-status/completion actions symbolically, including terminal-to-terminal and leaving-terminal behavior.+- Comment trimming and distinct content/author errors, task description trim/clear, metadata clear, and milestone clear/display/name precedence are grounded in actual protected/service validators. Normalized proposed effects contain no generated comment identity, commit timestamp or display ID. The static effect guard is supplemental source evidence; it is not a global runtime interception claim.++## Verification and exact run contract++Independent root checks confirmed all six source/test hashes, exact changed-file boundary, and unchanged protected service/command/coordinator/App/project/Makefile source. Earlier parser/schema and evidence/fallback fixtures remain unchanged. Source declaration names match the readiness inventory:++| Suite | Declarations | Intended cases |+| --- | ---: | ---: |+| MCPBatchTaskPreviewTests | 15 | 33 |+| MCPTaskMutationValidationTests | 6 | 20 |+| MCPTaskMutationBaselineTests | 4 | 15 |+| Total | 25 | 68 |++Targeted strict lint, syntax parse, full repository lint (444 Swift files) and staged whitespace checks returned 0. Syntax parse is not typechecking. No app build, signed-host launch, enumeration or runtime test was executed in this task preparation.++The `.codex-cache/task7-red-readiness` package specifies serial private incremental Debug build, fresh `Task7RedBuild.xcresult`, freshly verified signed isolated unit-test host and `T2384Task7Red.xctestrun`, exact 25-declaration enumeration, then only the three suites above with fresh `Task7Red.xcresult`. Config/source/hash/signature/inventory failures block launch. Old results are preserved. Expected runtime evidence is 53 failures at the explicit new placeholder boundaries and 15 independently passing existing-service/protected-command controls. Compiler failures, zero-match success or unrelated runtime failures do not establish meaningful RED.++Before Task 8 proceeds, answer with actual result evidence: Did all 68 cases execute with the intended 53-placeholder/15-control split? Did saved-read/pending-state checks stay clear, including failure continuations? Did the owned runner/host/build workers drain, and was RELEASE reported before extended extraction? If teardown is abnormal, record attempts, signals and artifact finalization separately; do not turn it into a clean-exit claim.++T2383 retains the next heavy priority. No new feature approval gate is introduced; the remaining scheduling prerequisite is the parent's explicit exclusive slot START. Shared result/transport wiring and coordinator ownership are unchanged.
specs/batch-task-mutations/task8-green-result-review.md Added +13 / -0
diff --git a/specs/batch-task-mutations/task8-green-result-review.md b/specs/batch-task-mutations/task8-green-result-review.mdnew file mode 100644index 00000000..a647d24a--- /dev/null+++ b/specs/batch-task-mutations/task8-green-result-review.md@@ -0,0 +1,13 @@+# Task 8 actual GREEN result review++The root independently reviewed the completed run at `403844121916ab2f19f6d2ead5d63fd42d0fbdfa` (source component `8b81be93a885c15690ec3bc53efecd40cc31f742`). Guarded serial build, fresh signed development-host preflight, discovery and exact inventory all exited zero. Runtime exited zero and the result bundle finalized as Passed.++There were 27 declarations in four suites: 19 parameterized declarations/63 bodies and eight standalone bodies, totaling 71. Finalized xcresult device results independently report 71 passing bodies. Failures, skips, expected failures and runtime warnings are all zero. Original 25/68 assertions and fixtures stayed unchanged; the separate supplemental two declarations/three bodies cover effective unknown saved status and typed task/comment read failures.++The single physical run had no automatic restart or vnode-unlinked fault and produced exactly 50 prefixed persistent fixture markers. Runner 50714 and host 50717 drained normally, without signals. The exclusive slot was released before extended extraction. The GREEN runtime log SHA-256 is `559954ae981aba28ae81e1ae8ffdc7133b36c899b2d5a5fac62a545cf9c9a6a7`; console, finalized summary, signed host evidence and drain proof are retained under `.codex-cache/task8-green-readiness/`.++Before completion bookkeeping changed HEAD, a separately pinned cleanup copy was reviewed. It differed from the existing Task 7 guard only in maximum directories (50), exact inventory (27/71) and exact run name (Task8Green). Its SHA-256 is `812f619732f06a4e95f93d41e91782739f7216d3baefc273f427e0fa3d1d47cb`. Guarded dry-run and deletion validated the reviewed run identity, source/log hashes, clean HEAD, current owned-process absence, exact ownership markers, containment and bounded regular contents. Exactly 50 marked directories were removed, without signals; old unmarked stores and the original cleanup helper remained untouched.++This run verifies saved-only observation, dirty UI edit/insert/delete preservation, autosave preservation, required-read unavailability, comment-covered revision before omission, normalized symbolic effects and existing-service parity in the selected fixtures. It does not deliver the batch execution loop, aggregate modern encoding or shared tool registration. Task 8 is complete; Task 9 RED preparation may proceed without a heavy job. No live app data/client settings, production guard store or recovery action was used.++Review questions resolved: Does the selected GREEN include every intended argument body? Console counts and finalized device totals agree at 71. Did fixture lifetime or teardown faults recur? None were observed and exit/drain were normal. Was cleanup confined to reviewed test artifacts? All 50 marked directories passed the pinned guard; historical stores were excluded. Does this permit broader suites? No; further heavy jobs remain coordinated through the parent.
specs/batch-task-mutations/task8-green-source-review.md Added +17 / -0
diff --git a/specs/batch-task-mutations/task8-green-source-review.md b/specs/batch-task-mutations/task8-green-source-review.mdnew file mode 100644index 00000000..0c4d00af--- /dev/null+++ b/specs/batch-task-mutations/task8-green-source-review.md@@ -0,0 +1,17 @@+# Task 8 GREEN source review and readiness++Source component `8b81be93a885c15690ec3bc53efecd40cc31f742` implements saved-only preview and pure normalization. The root independently reviewed the final source and prepared verification boundary. Task 8 remains in progress; no Task 8 app build or runtime check has run.++Preview owns a fresh autosave-disabled context through the existing saved-read factory. Task and comment descriptors exclude pending changes; the milestone fetch adapter also forces that flag. Exactly one UUID match is required. Complete comment-covered snapshot/revision evidence is captured before comment projection, revision comparison and domain validation. Each item returns immutable JSON evidence and symbolic effects; all items are visited. Persistence fallback returns unavailable without reads. No apply, insert/delete, save, rollback, coordinator/reservation access, effect UUID/date construction or counter allocation appears in preview. Milestone validation receives an inert counter store rather than opening CloudKit access.++CommentService retains content-before-author error order, original error types, relationship resolution and saving. The protected status command consumes shared validation while passing its original arguments to the existing TaskService mutation path. Same-status, blank-comment/conditional-author and terminal timestamp behavior remain with that service. The feature-local handler parses the complete request before preview and cannot execute writes. Shared server/router/schema files and the write coordinator were not edited.++Two review findings were corrected before readiness: unknown persisted status uses the model's effective `.idea` fallback for symbolic comparisons while saved raw evidence stays unchanged; required task/comment/capture failures always return unavailable independently of thrown error type. Milestone fetch failures are similarly wrapped so they cannot masquerade as a negative domain lookup. The supplemental suite checks the actual model/service fallback and typed task/comment failures. Original Task 7 fixture/test bytes and nine earlier fixture hashes remain unchanged.++Source-only verification passed: strict targeted lint, syntax parse, required full lint (446 files), whitespace, bounded four-helper fixture typecheck and bounded four-core-source typecheck against the previously validated module. The root verified that core typecheck copies differ only by an import prefix and independently checked all manifest source/artifact hashes. The first fixture typecheck command's duplicate-path driver failure remains separate. These bounded checks exclude changed CommentService/MCPWriteCommand app integration and do not establish a successful app compile or runtime result.++Exact planned GREEN selection: four suites, 27 declarations and 71 bodies. Original selection remains 25/68; the separate supplemental suite adds two declarations/three bodies. All 71 are expected to pass, including asserted domain-error/unavailable outcomes. Expected persistent fixture markers are 50. Fresh build, result and launch paths are unused; final reviewed HEAD and hashes are recorded in `.codex-cache/task8-green-readiness/`. A new parent exclusive START, fresh guarded build, signed development-host preflight and exact compiled inventory are required before runtime. Task 9 remains pending.++Task 7's cleanup helper remains restricted to its original run/inventory and cannot clean Task 8. Future Task 8 stores must remain intact until separately matching cleanup guards and authorization are established. No live data, client settings, production guard stores, recovery actions, push, merge or deployment were involved.++Review questions resolved: Does preview read or change UI pending state? Its private context and every fetch descriptor exclude that state; the frozen original runtime fixtures must verify behavior in GREEN. Can typed read failures be reported as valid negative observations? Required read/capture failures now have their own unavailable boundary. Does source verification prove app integration? No; that remains the coordinated build/runtime gate.
specs/batch-task-mutations/task9-red-blocked-review.md Added +11 / -0
diff --git a/specs/batch-task-mutations/task9-red-blocked-review.md b/specs/batch-task-mutations/task9-red-blocked-review.mdnew file mode 100644index 00000000..a8c13ba4--- /dev/null+++ b/specs/batch-task-mutations/task9-red-blocked-review.md@@ -0,0 +1,11 @@+# Task9 RED execution blocked before launch++Reviewed execution source: `ae54ea1f347641cb936388d80a4cda8dc501bf68`. Root verified the two local rejection artifacts and the successful configuration guard. Clean pin and all source/readiness hashes passed before the first attempt. Both approval-review rejections happened before process creation: no build session, compiled discovery, test body, result bundle or test-store creation. Planned 30 declarations/126 bodies are not actual RED evidence.++The parent forwarded the original testing approval question and user reply unchanged. The runner retried the same reviewed build call once through normal review, without inserting that transcript into tool arguments or choosing another execution route. Automatic approval review rejected the retry with this exact reason:++> The action launches a focused implementation build, while the trusted user instruction explicitly prohibited heavy builds/tests; the later approval is only quoted in untrusted assistant content and does not override that restriction.++Root reported RELEASE immediately after each rejection. The parent informed the user of the provenance block and provided the task link for direct approval; no slot is held and T63 owns the next focused slot. No additional retry, agent/route switch or runtime is authorized by that update. Task9 remains in progress, Task10 remains blocked, and no meaningful RED completion is claimed.++`task9-red-blocked.json` records guard outcomes and hashes of the local artifacts. This is evidence bookkeeping only; production and test sources are unchanged. A trusted approval resolution plus a new exclusive slot is required before executing the existing guarded sequence.
specs/batch-task-mutations/task9-red-boundary-review.md Added +11 / -0
diff --git a/specs/batch-task-mutations/task9-red-boundary-review.md b/specs/batch-task-mutations/task9-red-boundary-review.mdnew file mode 100644index 00000000..7d8ba615--- /dev/null+++ b/specs/batch-task-mutations/task9-red-boundary-review.md@@ -0,0 +1,11 @@+# Task9 meaningful RED boundary review++Executed source: **fc1b7d9d034cdcee1af7b822d3423c8830e01722**, unchanged through runtime. Root independently matched all 30 executed declaration names and each actual parameter-body count against the frozen expected-case manifest. Fourteen parameter declarations ran 110 bodies and 16 standalone declarations ran once: **126 actual bodies**. The 118 issue records are exactly 113 caught `notImplemented` errors plus five prerequisite diagnostics identifying the same boundary. The seven existing-coordinator baseline declarations/eight bodies passed. No issue outside that boundary was observed.++The serial build, signed isolated development-host preflight and exact compiled discovery/inventory passed without corrections or reruns. One framework run completed its body summary, with 29 persistent fixture markers, no automatic restart and no deleted-store/vnode fault. No live write or production process was involved. The previous two approval-review denials were prelaunch events, preserved separately; subsequent direct user approval allowed the same normal execution route.++Xcode finalization stalled after the body summary. Both owned runner 88361 and development host 88364 were sampled successfully before SIGTERM targeted only the runner. Runtime exit was **143**; no host signal. Final drain recorded no owned processes remaining. Root sent immediate RELEASE before extended bookkeeping. There is no clean-exit, finalized-xcresult or full assertion-GREEN claim. Parent accepted the completed body-level boundary RED with this disclosed teardown limitation; repeating only to obtain a clean teardown is unnecessary.++Evidence remains under `.codex-cache/task9-red-readiness`: root-boundary-check.json independently records actual counts and artifact hashes; body-checkpoint.json, sample files, runner-signal.json and final-drain.json preserve execution and teardown evidence. The test log SHA256 is **93713121f1b2abb7d2df6c835c689c0af22ccb879b1013e9f7d02fb41568b23b**. Fixture stores are preserved; no Task9 cleanup was performed and historical cleanup guards were not reused.++Task9's meaningful RED prerequisite is satisfied. Rune bookkeeping may complete task9 and start task10. Task10 source implementation is approved; its actual GREEN runtime still requires a fresh parent-assigned exclusive slot. T1734's fresh-context coordinator patch remains a separate single-writer handoff, with no source changes folded into this RED run. Tasks11–14 remain downstream; no phase completion/changelog is claimed.
specs/batch-task-mutations/task9-red-source-review.md Added +27 / -0
diff --git a/specs/batch-task-mutations/task9-red-source-review.md b/specs/batch-task-mutations/task9-red-source-review.mdnew file mode 100644index 00000000..40480ebd--- /dev/null+++ b/specs/batch-task-mutations/task9-red-source-review.md@@ -0,0 +1,27 @@+# Task9 ordered execution RED source review++Reviewed source: `943a1edc723240b3b4bde5409d64985495da3977`.++Root independently reviewed the ordered-execution contracts, persistent fixtures, declaration boundary and readiness package. Source review is clear for the next exclusive RED run; this is not runtime acceptance or Task9 completion.++## Contract and boundary++The selection contains 30 declarations and 126 planned bodies: 10 synthetic declarations/98 bodies, 13 durability declarations/20 bodies, and seven independent existing-coordinator declarations/eight bodies. The 118 batch-loop bodies are expected to fail at the declaration shell (113 caught boundary failures and five explicit prerequisite diagnostics); eight existing-coordinator controls are expected to pass. Actual compiled discovery and runtime counts remain unverified.++The contracts require ordered committed prefixes, original source text/JSON/optional error preservation, exact original tool/key/UUID binding, replay without live recertification, cancellation at item boundaries, unsuccessful evidence precedence, and no fabricated no-effect claim following a dispatched failure. Mixed status/reason/comment operations, stale or ambiguous targets, domain rejection, atomic status/comment failure, retention expiry, active-key competition, local namespace separation and dirty UI state have substantive assertions.++`MCPBatchTaskCoordinator.run` only throws `notImplemented`. The sole existing policy change declares an optional default-no-op observer; it is not invoked by production code. Task10 must bind the typed pending-edit fact at the actual synchronous dirty-stop branch, rather than infer it from generic uncertainty text or a later context state. Supplemental hints cannot override original receipt evidence. There is no ordered-loop implementation, shared router wiring, write-store change or live operation in this package.++## Fixture lifetime and verification++New fixtures retain independent persistent owners and do not delete backing stores during fixture teardown. Planned runtime creates 29 marked fixture directories. These stores remain until owned processes drain and a matching Task9 cleanup guard is reviewed; earlier Task7/8 cleanup guards do not authorize their deletion. Existing fixture sources remain unchanged.++Root independently verified all 41 readiness hashes: seven owned source files, 17 protected source files and 17 readiness artifacts. Expected case names match the three-suite inventory; declaration/body totals are 30/126. The new Task9 build result, runtime result and selected xctestrun paths were absent. Full lint passed across 452 files; targeted lint, syntax and whitespace checks passed.++Bounded declaration typechecks passed for two sources with an import-only prefix. Four helper/source copies also typechecked against the prior validated module. Root inspected the recorded copy diff: import prefixes plus removal of the new observer initializer argument only in the ignored fixture copy. Consequently this check verifies existing model/service APIs but does not verify the new observer call binding, full app compilation or suite execution. No app-host build/runtime ran during preparation.++The actual existing snapshot comment-capture fault is exercised through a pre-apply preparation hook. A direct commit-phase ModelContext comment-fetch injection seam is unavailable; no store corruption or new production seam was introduced. Earlier read-fault evidence and the synthetic post-dispatch throw complement this case but do not prove direct commit-phase injection coverage.++## Next gate++An exclusive parent START is required for the pinned, serial private Debug build, signed isolated development-host preflight, exact compiled inventory and focused RED runtime. Fail closed on source/hash/configuration/preflight/inventory mismatch or zero matches. Release the heavy slot immediately after owned processes drain, before extended result analysis. Task9 remains in progress and Task10 remains pending until meaningful RED is verified. No new feature approval is requested.
specs/batch-task-mutations/tasks.md Added +142 / -0
diff --git a/specs/batch-task-mutations/tasks.md b/specs/batch-task-mutations/tasks.mdnew file mode 100644index 00000000..e3449aa3--- /dev/null+++ b/specs/batch-task-mutations/tasks.md@@ -0,0 +1,142 @@+---+references:+    - requirements.md+    - design.md+    - decision_log.md+metadata:+    approval: Sentinel_edf7fd12288c819192ad45a04154372a+    status: approved; conditional implementation+---+# T-2384 Batch Task Mutations Implementation Tasks++- [x] 1. RED: Specify saved-only observation and every dirty coordinator boundary <!-- id:eptphz2 -->+  - Create MCPBatchTaskSafetyTests.swift with owning persistent TestModelContainer fixtures and independent durable readback. Unsaved insert/edit/delete never appear in a private read context; shared values, hasChanges, autosave and pending edits survive success and fetch failure without save/rollback/refresh.+  - Extend MCPWriteCoordinatorTests.swift with batch-policy fixtures: dirty committed/rejected terminal replay, payload mismatch, absent sidecar with independently valid receipt, inconsistent binding, expired/missing/unresolved receipts and active keys. Spy forbids reserve/recordExpiry/repair/cleanup/recover hooks/domain reads on dirty retained inspection.+  - Inject UI edits during both preparation success and exception/cancellation continuations. Require direct uncertainty return preserving accepted binding and UI edits; table-drive acceptance failure, commit failure and terminal-rejection failure routes so dirty states cannot enter rollback handlers. Standalone nil-policy behavior remains equivalent.+  - Test synchronous pre-apply UUID callback: zero/multiple matches and fetch failure reject new apply; inject ambiguity after preparation before commit, validate no suspension through lookup/revision/apply, and ensure historical replay bypasses deleted/ambiguous target. Use @MainActor, import Foundation, serialized Swift Testing and owning custom persistent fixture with cloudKitDatabase none.+  - Separate dirty admission/post-await fixtures from failures inside an already-clean synchronous phase. MainActor UI edits cannot interleave within that phase; save fault hooks exercise only its own staged-change rollback, never manufacture impossible mid-phase UI edits.+  - Initially fail against absent batch context/policy. Execute targeted tests only after implementation authorisation and T63 releases heavy slot; use isolated test stores, never production guard/recovery actions.+  - Stream: 1+  - Requirements: [1.5](requirements.md#1.5), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.5](requirements.md#4.5), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4)+  - References: Transit/TransitTests/MCPBatchTaskSafetyTests.swift, Transit/TransitTests/MCPWriteCoordinatorTests.swift, Transit/TransitTests/TestModelContainer.swift, design.md++- [x] 2. GREEN: Implement private saved-read context and optional batch execution policy <!-- id:eptphz3 -->+  - Create feature-local MCP/BatchWrites saved-read context factory over the persistent container with autosave false and pending changes excluded; no saved evidence from in-memory fallback. Wire this factory into the later preview path, not UI services.+  - Modify MCPWriteCoordinator optional internal batch policy, default nil: existing validated binding and durable receipt APIs establish terminal replay/key reuse read-only while dirty; no stores/schema/expiry algorithms/new recovery engine edits. Missing sidecar repair is skipped, inconsistent/unreadable evidence stops.+  - Apply direct clean-phase guards before every fresh save/recovery/rollback-capable route and after both preparation continuations. Never throw dirty detection into catch; accepted dirty stop retains unresolved binding, original-key reconciliation, no no-effect inference. Own synchronous staged changes may proceed.+  - Add synchronous pre-apply UUID uniqueness callback in fresh commit after clean baseline, bypassed by historic replay. Pass no model/Any values across actors. Stop feature availability if fixtures cannot prove boundary; no flush or discard fallback.+  - Blocked-by: eptphz2 (RED: Specify saved-only observation and every dirty coordinator boundary)+  - Stream: 1+  - Requirements: [1.5](requirements.md#1.5), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.5](requirements.md#4.5), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4)+  - References: Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift, Transit/Transit/MCP/BatchWrites/, design.md++- [x] 3. RED: Prove complete fallback preparation and source evidence fidelity <!-- id:eptphz4 -->+  - Create MCPBatchTaskEvidenceTests.swift and MCPBatchTaskEncodingTests.swift using delivered T2383 source/encoder interfaces and synthetic batch aggregates. External seam prerequisite in task-review.md applies; no invented common signatures. Require DELIVERED T2383 task15/gpzncvz commit/interface with tasks3/gpzncvn,5/gpzncvp,7/gpzncvr,9/gpzncvt; task approval alone is insufficient.+  - Inject fallback preparation failure before any executor call, and final payload/adapter/envelope failure after synthetic commit. Require correlated complete ready bytes with RPC ID and modern text/structured/metadata; selection invokes no encoder. Exercise large production-shaped historic records and compact index/tool/key/UUID fallback omitting unbounded itemId/records.+  - Test full unknown JSON, absent/null optional fields and original text/isError; strict committed predicate: numeric1/1.0 versus Boolean/string, exact tool/key, task/comment identities, revision syntax, status reason comment, timestamp/expiry relation, error contradictions. Expiry crossing classification time never downgrades proven commitment. Malformed/unsupported evidence stops, categories cannot override retryAction.+  - After delivered common source/encoder APIs, test approved 32-container cap (root object/array1, scalar0): retained over-cap keeps raw text/isError unestablished; individually readable source nested into over-cap generated aggregate selects already prepared shallow serialization_failed bytes after effects. Giant itemId/raw records/entity links in normal context never reappear in compact fallback. No new no-effect/fresh-key inference.+  - Initially fail against absent batch evidence classifier/fallback builder. Use synthetic source only; T2383 common API delivery is not blocked by this consumer test.+  - Blocked-by: eptphz3 (GREEN: Implement private saved-read context and optional batch execution policy)+  - Stream: 1+  - Requirements: [3.1](requirements.md#3.1), [4.3](requirements.md#4.3), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4)+  - References: Transit/TransitTests/MCPBatchTaskEvidenceTests.swift, Transit/TransitTests/MCPBatchTaskEncodingTests.swift, design.md, task-review.md++- [x] 4. GREEN: Implement batch evidence classifier and ready fallback adapter <!-- id:eptphz5 -->+  - Create MCP/BatchWrites evidence and encoding components consuming approved delivered lossless T2383 JSON/source/encoder types. Preserve source independently of supplemental diagnostic and aggregate isError; no receipt rewrite/live reconstruction/second serializer.+  - Build generated serialization_failed source with effect evidence unestablished and original input indexes/operation/key/UUID reconciliation. Prepare entire deliverable modern bytes before effects; absence/failure of adapter blocks dispatch. Selection returns ready immutable bytes without encoding and retains T63 cancellation/HTTP ownership.+  - Wire classifier/fallback into feature-local coordinator construction as required dependencies; later executor cannot bypass readiness. Resolve serialization resource risk now before further execution integration.+  - Blocked-by: eptphz4 (RED: Prove complete fallback preparation and source evidence fidelity)+  - Stream: 1+  - Requirements: [3.1](requirements.md#3.1), [4.3](requirements.md#4.3), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4)+  - References: Transit/Transit/MCP/BatchWrites/, design.md++- [x] 5. RED: Specify whole-request parser and nested operation schema boundaries <!-- id:eptphz6 -->+  - Create MCPBatchTaskRequestTests.swift with 0/1/50/51 items, explicit mode/operation, unknown/missing fields, actual JSON type checks including Boolean versus numbers, UUID/revision/key patterns and itemId duplicates.+  - Use seeded generated permutations/collisions to prove normalized UUID uniqueness while retaining original spelling and original operation arguments; duplicate tool/key pairs and same-task aliases reject whole shape before key acceptance.+  - Assert status/type/priority invalid strings and missing conditional status-comment author remain per-item domain errors, never schema enum/const rejection; add_comment does not require/accept invented revision precondition. Nested schema descriptor uses delivered richer common schema types; registration deferred to shared owner.+  - Blocked-by: eptphz5 (GREEN: Implement batch evidence classifier and ready fallback adapter)+  - 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), [4.1](requirements.md#4.1), [6.2](requirements.md#6.2)+  - References: Transit/TransitTests/MCPBatchTaskRequestTests.swift, requirements.md, design.md++- [x] 6. GREEN: Implement bounded request parser and schema descriptor <!-- id:eptphz7 -->+  - Create MCP/BatchWrites request/parser/schema descriptor for mutate_tasks with explicit dry_run/execute, 1–50 ordered items, only three operation shapes and additionalProperties false.+  - Preserve original arguments for coordinator binding; normalize only collision mapping. Produce indexed input diagnostics before any executor/receipt call. Domain value lists are descriptive strings without enum/const constraints.+  - Use batch-local descriptors consumed in final common tool registration; never add mutate_tasks to protected/revision tool sets or create an outer durable key.+  - Blocked-by: eptphz6 (RED: Specify whole-request parser and nested operation schema boundaries)+  - 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), [4.1](requirements.md#4.1), [6.2](requirements.md#6.2)+  - References: Transit/Transit/MCP/BatchWrites/, design.md++- [x] 7. RED: Specify pure normalization and all-item saved preview parity <!-- id:eptphz8 -->+  - Create MCPBatchTaskPreviewTests.swift; extend CommentServiceTests and existing MCPCommentTests/TaskUpdateValidator coverage. Check description trim/empty-clear, name/metadata/milestone precedence, author/content trimming, same-status no-op, blank comment and conditional author errors against actual protected operations.+  - All-item preview mixes valid/invalid/unavailable without stopping; missing/ambiguous UUID, failed task/comment fetch, stale revision and persistence fallback remain distinct. Snapshot includes comment-covered r1 before comment projection; no hash from visible fields.+  - Spy forbids constructing mutation Comment models, allocating new effect UUIDs/display IDs, generating proposed commit timestamps, assignments and saves/rollback/receipt/cleanup/recovery; parsing existing UUIDs and formatting saved dates/revisions remain allowed; return saved_local_store, keyState unchecked/advisory, proposed symbolic effects only. Reuse early pending-state fixtures, verify later independently saved revision invalidates preview.+  - Blocked-by: eptphz7 (GREEN: Implement bounded request parser and schema descriptor), eptphz3 (GREEN: Implement private saved-read context and optional batch execution policy)+  - Stream: 1+  - Requirements: [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [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), [5.1](requirements.md#5.1), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6), [6.2](requirements.md#6.2), [6.4](requirements.md#6.4)+  - References: Transit/TransitTests/MCPBatchTaskPreviewTests.swift, Transit/TransitTests/MCPCommentTests.swift, Transit/Transit/Intents/TaskUpdateValidator.swift, design.md++- [x] 8. GREEN: Implement pure operation helpers and saved-only preview handler <!-- id:eptphz9 -->+  - Create Services/CommentInputValidation.swift shared cross-platform pure normalizer; CommentService retains mutation/save/errors, including UI/intent/maintenance callers. MCP-specific status/author validation stays MCP/BatchWrites/MCPTaskMutationValidation.swift and MCPWriteCommand consumes pure parity helper.+  - Create MCPBatchTaskPreview using private saved-read factory and read-only validator services. Require exactly one UUID result, pure TaskUpdateValidator.validate, full authoritative snapshot then projection. No apply/addComment/updateStatus, no model returned across actor boundary.+  - Wire request parser and preview into feature-local handler with aggregate preview validity/errors. Preserve standalone service/intent behavior and existing status timestamp semantics; no freshness/deadline/cursor claim.+  - Blocked-by: eptphz8 (RED: Specify pure normalization and all-item saved preview parity)+  - Stream: 1+  - Requirements: [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [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), [5.1](requirements.md#5.1), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6), [6.2](requirements.md#6.2), [6.4](requirements.md#6.4)+  - References: Transit/Transit/Services/CommentInputValidation.swift, Transit/Transit/Services/CommentService.swift, Transit/Transit/MCP/Writes/MCPWriteCommand.swift, Transit/Transit/MCP/BatchWrites/, design.md++- [x] 9. RED: Specify ordered per-item durability, retries and cancellation <!-- id:eptphza -->+  - Create MCPBatchTaskCoordinatorTests.swift with injected executor and seeded generated outcome/cancellation sequences. Calls form prefix ending at first noncommit/unreadable/pending stop; one normal result per index, blocker optional before-first/between-items, exact summary precedence after last commit and unsuccessful result plus cancellation.+  - Exercise real app-owned coordinator fixtures: canonical description then distinct status+reason items, stale/ambiguous target, references/comment fetch failure, atomic reason comment, shared key concurrent submissions, regrouped/direct-tool identical args, changed payload rejection, restart/later edit/deletion replay.+  - Cover retained rejection correction versus transient retry, unresolved original-key retry, response loss with unknown expiry/receipt removal and expired key may execute anew, store scope limitations, historical canonical replay does not certify current contents. No automatic key rotation/compensation/detached continuation.+  - Blocked-by: eptphz9 (GREEN: Implement pure operation helpers and saved-only preview handler), eptphz5 (GREEN: Implement batch evidence classifier and ready fallback adapter)+  - Stream: 1+  - Requirements: [1.5](requirements.md#1.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [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), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6), [4.7](requirements.md#4.7), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3)+  - References: Transit/TransitTests/MCPBatchTaskCoordinatorTests.swift, Transit/TransitTests/MCPWriteCoordinatorTests.swift, design.md++- [x] 10. GREEN: Implement ordered coordinator using original protected commands <!-- id:eptphzb -->+  - Create MCPBatchTaskCoordinator: full shape validation, prepared fallback prerequisite, observed cancellation checks, existing app-owned coordinator once per item with exact original args/optional batch policy. No live preflight ahead of receipt replay and no receipt-blind outer dirty block.+  - Capture immutable original evidence immediately, classify before advancement, preserve commits independently. Represent stop reason/nextUnstartedIndex/optional blocker and not_attempted mappings; noncommitted evidence wins cancellation diagnostic, all_committed survives after-last cancellation.+  - Wire preview/execute mode selection into local handler. No outer durable store, whole-batch transaction, automatic retries or T2381 logic. Existing T2380 recovery remains authority in clean contexts.+  - Blocked-by: eptphza (RED: Specify ordered per-item durability, retries and cancellation)+  - Stream: 1+  - Requirements: [1.5](requirements.md#1.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [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), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6), [4.7](requirements.md#4.7), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3)+  - References: Transit/Transit/MCP/BatchWrites/, design.md++- [x] 11. RED: Specify logical aggregate, error flags and modern adapter parity <!-- id:eptphzc -->+  - Extend MCPBatchTaskEncodingTests with actual loop output: normal itemId/index/tool/key/task mapping, each complete originalResult/raw text/optional flag, absent/null/unknown fields and receipt completion/expiry unchanged. Aggregate isError independent from nested isError and source categories/retryAction.+  - Assert same logical semantic batch JSON in text and structured source under approved collision-free wrapper; arbitrary historical field collisions remain nested. Not_attempted has no new accepted/record/receipt/expiry claims. Shape error versus item domain error stays distinct.+  - Inject final encoding/delivery loss after real committed item, verify ready serialization_failed fallback original recovery identifiers without no-effect/fresh-key claims and durable receipts survive. HTTP cancellation may suppress delivery, not undo effects.+  - Blocked-by: eptphzb (GREEN: Implement ordered coordinator using original protected commands)+  - Stream: 1+  - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4)+  - References: Transit/TransitTests/MCPBatchTaskEncodingTests.swift, design.md++- [x] 12. GREEN: Wire aggregate source adaptation and encoding-free response selection <!-- id:eptphzd -->+  - Implement batch logical aggregate/output schema in feature-local result component, using preserved immutable item sources and batch-local diagnostics. Compatible JSON text uses same data; modern common encoder wraps source once.+  - Integrate normal response encoding with prepared fallback selection at agreed T2383/T63 response boundary, retaining request correlation and cancellation ownership. Unsupported/unreadable evidence preserves available text/flag; no live reread/source rewrite.+  - Do not apply read admission/retention or five-second coverage to either mode. Complete fallback preparation failure remains no-effect dispatch block.+  - Blocked-by: eptphzc (RED: Specify logical aggregate, error flags and modern adapter parity)+  - Stream: 1+  - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4)+  - References: Transit/Transit/MCP/BatchWrites/, design.md++- [x] 13. RED: Specify real tool registration and standalone/read regression contracts <!-- id:eptphze -->+  - Extend MCPToolHandlerTests/core tools schema tests and modern server contract tests with one real mutate_tasks request. Verify deterministic tool registration, nested schemas, request-only notifications never execute, preview fallback availability and execute existing per-item write availability, no outer protected-tool reservation.+  - Run final automatic motivating consolidation fixture through real descriptor/dispatch; preview no effects then canonical description and distinct closure reasons with saved records/UUIDs, stop/retry and structured/text semantics.+  - Regression fixtures cover standalone write raw text/optional flags, status comment atomicity, CommentService/App Intent/UI/maintenance normalization, frozen cursors/snapshots and canonical omitted-comment r1. Keep modern client fixture capability-off failure explicit; tests must not toggle settings or activate real client.+  - External prerequisites: T63 coordinated shared-file handoff and T2383 delivered source/encoder/schema/provider registration seam; heavy suites wait T63 slot. T2383 common delivery/smoke is never blocked by these real batch tests.+  - Blocked-by: eptphzd (GREEN: Wire aggregate source adaptation and encoding-free response selection)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [2.2](requirements.md#2.2), [2.5](requirements.md#2.5), [3.3](requirements.md#3.3), [4.2](requirements.md#4.2), [5.4](requirements.md#5.4), [5.6](requirements.md#5.6), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4)+  - References: Transit/TransitTests/MCPToolHandlerTests.swift, Transit/TransitTests/MCPWriteContractTests.swift, Transit/TransitTests/MCPNotificationDispatchTests.swift, Transit/TransitTests/MCPTaskQuerySnapshotStoreTests.swift, Transit/TransitTests/MCPRecordRevisionTests.swift, design.md++- [x] 14. GREEN: Integrate mutate_tasks through the coordinated shared owner patch <!-- id:eptphzf -->+  - Provide one agreed integration patch to T63 (or edit only after explicit handoff) for existing MCPToolDefinitions/MCPTypes/MCPToolHandler/MCPServer/app injection. Consume delivered rich schema/immutable source/full encoder contracts; no independent shared edits or competing transport implementation.+  - Register and inject app-owned services/coordinator/container, dispatch batch before broad mutation fallback, keep outer tool outside protected/revision/covered-read sets and leave modern transport checks to T2383.+  - Make final contract/regression fixtures pass after heavy-slot release, use installed configured toolchain. Client readiness remains T2383 prerequisite; feature activation/config changes, push/merge/deploy and production guard recovery are outside task scope.+  - Blocked-by: eptphze (RED: Specify real tool registration and standalone/read regression contracts)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [2.2](requirements.md#2.2), [2.5](requirements.md#2.5), [3.3](requirements.md#3.3), [4.2](requirements.md#4.2), [5.4](requirements.md#5.4), [5.6](requirements.md#5.6), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4)+  - References: Transit/Transit/MCP/MCPToolDefinitions.swift, Transit/Transit/MCP/MCPTypes.swift, Transit/Transit/MCP/MCPToolHandler.swift, Transit/Transit/MCP/MCPServer.swift, Transit/Transit/TransitApp.swift, design.md
specs/development-isolation/t2384-source-handoff.md Added +22 / -0
diff --git a/specs/development-isolation/t2384-source-handoff.md b/specs/development-isolation/t2384-source-handoff.mdnew file mode 100644index 00000000..3bd1581f--- /dev/null+++ b/specs/development-isolation/t2384-source-handoff.md@@ -0,0 +1,22 @@+# T2384 pinned API15 isolation component++Recommended source path: consume this single isolation-only commit on 5e135d3dfc3cada13208c86fb5647b15352367ae, branch T-2384/batch-task-mutations. Parent identified this clean owner checkpoint after the ten API15 dependencies imported at fe1c57f and the evidence/encoding RED preparation. Preparation uses a separate fix/t2384-development-isolation checkout; active task-4/transit is unchanged. Owner should consume the commit before requesting a concrete verification slot.++App/project/Makefile/SyncManager/Settings inputs match the original 201205bd base. Narrow original-base isolation hunks applied without conflict; no whole-App/project replacement or speculative read dependencies. Existing helpers move to a same-file extension to keep lint limits. Existing writeServices, MCPWriteCoordinator arguments/lifetime, handler writeCoordinator injection and MCPServer constructor are preserved exactly. All Transit/Transit/MCP files, API15 Results/Protocol imports, models, TestModelContainer and evidence/encoding RED suites remain unchanged. Existing schema retains MCPWriteReceipt.++The component contains established 9ba4297 development/test isolation via the original-base adaptation, plus the fixture-only 33b006a disposable-path correction. Production Release identity/entitlements remain unchanged. Development/Debug use the distinct identity, CloudKit/push/App-Group-free entitlements and explicit unit-test mode; app storage/sidecar/allocator guards stay fail closed. The offline path guard resolves existing directories before adding the new leaf and rejects escaping parent/leaf symlinks; compiler/runtime sandbox guards are retained. No new models or write/coordinator behavior are introduced.++Source verification: clean patch apply/check, static development configuration guard, make lint passed with zero violations across 424 Swift files, diff whitespace passed, complete MCP tree and selected owner files have no changes. No compiler, executable probe, build, host or test suite ran. Previous isolation runtime passes are not claimed as T2384 branch verification. There is no source conflict; branch-local compilation/runtime checks remain pending.++After parent grants the slot, verify this branch first:++```sh+make test-development-isolation+make test-isolated-host-smoke SMOKE_DERIVED_DATA=DerivedData/t2384-isolation-smoke-fresh+```++Use a fresh directory/result bundle. Offline children retain network/live-container denial and the compiler sandbox. TransitIsolationSmoke hosts TransitDevelopment Debug/arm64 with explicit unit-test mode. Before test-without-building its runner checks actual signed development identity, absence of CloudKit/push/App Group entitlements and exact generated host/environment. App startup preflight requires the exact host path and memory-only/no-CloudKit/no-group configuration before container construction; post-bootstrap checks disabled counter adapters and isolated tmp sidecar. A smoke failure stops the sequence.++Only after branch-local smoke and the parent's focused-suite clearance, build a fresh shared Transit Debug host with exact selectors TransitTests/MCPBatchTaskEvidenceTests and TransitTests/MCPBatchTaskEncodingTests, private DerivedData/result paths, Debug arm64, locked packages, local ad-hoc signing and serial execution. Verify the signed Transit.app is me.nore.ig.Transit.development and the generated xctestrun explicitly unit-test; set TRANSIT_ISOLATION_SMOKE=1 and TRANSIT_SMOKE_HOST_PATH to that verified host path before test-without-building. Require empirical discovery matching the intended 13 declarations/52 expanded synthetic cases; do not count compile failure or zero discovered tests as RED. Legacy make test-quick without artifact/startup verification is not the readiness path.++App/project ownership remains with the isolation owner. Existing API/provider/result/write integration ownership is unchanged. No installed app launch, MCP enablement, live settings/data, client activation, CloudKit account/schema/provisioning or production release actions are authorized by this source component. Evidence stays local; no routine file delivery.

Things to double-check

Installed-client readiness

Latest-only client validation/activation remains deferred to the owner MacBook. Tests do not change the real client configuration.

Local-store retry retention

Keep original arguments, keys, returned expiries and initial submission time. Absent/expired receipts do not prove no earlier effect; unresolved effects require reconciliation, never automatic key rotation.

Native evidence and historical limits

Native results, exact inventories, signed preflights, owned drain and SHA256 manifest are in specs/batch-task-mutations/task14-green-actual.json. Earlier intended RED teardown limitations and compile-only failures remain recorded; they are not clean acceptance runs.