Transit Approved tasks 22 / 22 Acceptance criteria 39 / 39 Passing case executions 4,694 Intentional macOS skips 5

T-1734: typed task links — final local review

Approved participating-write implementation; fresh PR-native corrections verified at bbe3a25; landed base e04c1268.

At a glance

  • Preserves original tasks, physical occurrences, canonical linkage and exact repair evidence. No consolidation or permanent deletion shortcut.
  • Four independent internal reviews covered the full branch plus corrective deltas. Three configured Claude reviews posted; final review/check passed at remote head 76152873 with minor suggestions only.
  • Unsaved data is excluded. Participating local saves are atomic with receipts; independent writers/imports can race.
  • Native saved projection is distinct from a certified retained MCP capture. T-2381 consolidation and T-2402 live CloudKit verification remain deferred.
  • Fresh focused native: 20 passes. Full lint: 652 files, zero violations. All 30 recorded runtime PIDs absent; owned simulator shut down/deleted.
  • Generic JUnit/coverage unavailable: configured ecosystem detects SwiftPM, while Transit uses Xcode. Actual xcresult trees and exit records independently verified; totals above count executions across platforms.
  • T-2381 can use the merged typed-link foundation for its separately gated consolidation spec. T-2402 remains the live CloudKit/production-promotion gate. Live Transit ticket status was not changed under the no-live-writes instruction.

Verdict

Merged and remote tree verified

PR #254 squash-merged at 169ac244a11ebfbdacce3d4a25fcddfe395ac6d2. Fetched origin/main exactly matches the merged commit; its full tree matches reviewed head 76152873 and application/test/Makefile content matches tested source bbe3a25. Final Claude/check passed. Fresh full verification: 4,694 passes, five intentional macOS skips, zero failures. No deployment or live writes.

Review findings

5 raised · 4 fixed · 1 skipped

Jump to findings →

Tests

Pass rate: n/a

New tests: 126

Diff coverage: n/a

Jump to tests →

Author's PR description

Shown verbatim — the markdown the author wrote, unmodified.

Tasks previously had no typed relationship evidence for dependency selection or duplicate identification. This adds blocks/blocked-by, relates-to, introduced-by and duplicate-of links, with saved-only query assessments, exact protected edits/repair, and read-only native relationship visibility/navigation. Duplicate chains identify a canonical task while preserving every original task and comment. Link authoring uses protected standalone MCP operations; native editing is outside this feature.

PR review corrections add direction-relative incoming attribution/duplicate labels and cancellable 100-ms notification-burst coalescing after immediate generation invalidation. Initial loads stay immediate, obsolete providers never capture, and complete saved graph evidence is preserved.

All 22 tasks and 39 acceptance criteria in `specs/typed-task-links/` are implemented in the approved local scope. Participating local writes validate saved source/endpoint revisions and save domain changes with their receipt. Independent writers/imports can race; no global CloudKit atomicity is claimed. Native saved projection is distinct from a certified retained MCP snapshot. Consolidation remains T-2381; live CloudKit schema/setup/export/deletion verification remains T-2402 and a prerequisite for production schema promotion. This repository merge does not deploy, promote the schema, activate a client or perform live writes.

Final isolated verification at application/test source `bbe3a2560584f7fb822aa8006b20f08d22284ce4` (later commits are documentation only):

- Focused native: 20 expanded passes / seven declarations, including ten label contracts and two burst/cancelled-start controls with prior cases unchanged.
- Full macOS units: 3,265 expanded passes, zero failures, five intentional opt-in skips (two primitive diagnostics, closed-store stage, development schema precheck, outside-writer observation).
- Full iOS units: 1,403 expanded passes; iOS UI: 26 expanded passes; zero failures/skips.
- Full lint: 652 files, zero violations; ownership, source-schema and development isolation guards passed. All builds/signing preflights passed.
- All 30 recorded runtime PIDs are absent and the owned simulator was shut down/deleted. Two transient inspection timeouts recovered with bounded retries charged to original deadlines.
- Four independent internal reviews covered the branch and corrective deltas. Configured Claude reviews posted at earlier heads; all suggestions are validated in PR overview comments. Historical failed/partial runs and the earlier 81f78e7 source's 4,670 passes remain separately recorded.

4,694 is passing case executions across final platform runs, not distinct declarations. CI runs the configured Claude reviewer; native build/test/lint results above were executed and independently checked locally. Exact evidence is in `specs/typed-task-links/pr254-native-corrections.md` and `local-review.md`.

Review map: start with `Models/TaskLinkOccurrence.swift` and `TaskLinkRemovalEvidence.swift`, `Services/TaskLinks/TaskLinkGraphIndex.swift` and `TaskLinkPlan.swift`, `MCP/Writes/TaskLinkOwnedPlan.swift` and `TaskLinkOwnedApply.swift`, `MCP/Reads/MCPReadCaptureBuilder.swift`, `MCP/Links/`, then `Views/TaskDetail/TaskLinksSection.swift`.

Commits

Three-level explanation

### What changed

Tasks can record five kinds of relationship: blocks, blocked-by, relates-to, introduced-by and duplicate-of. A link records an occurrence between two task UUIDs. Duplicate-of can identify a canonical task through a chain, but each original task keeps its identity, content and comments.

### Why it matters

Agents can select work using recorded dependencies and inspect duplicate relationships without combining several changing responses themselves. Native task details show saved relationship labels and diagnostics. Selecting a resolved relationship opens that exact saved task; ambiguous or missing destinations do not choose an arbitrary record.

### Key concepts

A revision is a content token used to reject edits based on old evidence. Current task revisions cover link membership as well as existing task fields and comments. A receipt preserves a protected write's original result for retry. A frozen query page preserves its original saved evidence even if tasks change later. These are local-store guarantees; they do not certify remote CloudKit convergence.

### Implementation approach

Two additive scalar SwiftData models store active occurrences and separate bounded removal evidence. All physical rows remain visible to value-only graph projection, including repeated UUIDs and malformed imports. Dependency assessment uses direct blockers: Done satisfies a valid blocker; Abandoned and other recognized non-Done statuses do not. Cycles, missing or colliding endpoints, unknown direct blocker status and conflicting evidence are reported explicitly. Duplicate resolution walks a directed chain and stops on repeated identity, cardinality or endpoint faults.

Standalone create/update link directives use the existing protected coordinator. The adapter resolves current source and affected endpoint revisions in a clean owned context, validates the entire proposed graph, stages task fields and exact occurrence changes, encodes the terminal result, then saves domain changes and receipt together. No-op additions/removals preserve timestamps and content tokens. Removal-only repair can reduce precisely identified corruption without silently deleting equivalent rows or adding unrelated changes. Batches retain their approved per-item fields and reject link directives before acceptance.

### Reads and compatibility

The MCP capture builder freezes selected task values, full graph closure, required comments and evaluation time inside the existing history/generation fence. Graph filters run before body serialization, ordering and page publication. Closure tasks support assessment without becoming selectable or changing portfolio totals. Current `r1` tokens explicitly cover empty incidence; old pre-feature tokens cannot authorize fresh preconditioned edits. Historical receipt bytes and results missing graph coverage are preserved rather than reminted.

### Trade-offs

Participating writes cannot interleave the synchronous final coordinator phase. Independent containers, external writers and imports can race with it and leave inconsistent saved links. Later reads report available faults; no automatic repair, post-commit rollback, task redirect or consolidation is introduced. Native sections use fresh saved value DTOs and generation/cancellation checks. Their observation is distinct from a fenced retained MCP snapshot.

### Technical details

The graph indexes domain UUIDs to every physical match and preserves raw occurrence tuples. Iterative strongly connected component traversal retains every structurally resolved physical dependency, so logical deduplication cannot hide cycle evidence. `l1` fingerprints include occurrence identity, kind, endpoints and immutable creation time. Current `r1` incidence includes identity/kind/endpoints with physical multiplicity; endpoint labels/status, removal expiry and derived assessments remain separately observed data. Authoritative snapshot entry points require explicit incidence coverage, including an explicitly empty set.

Owned write commitment refetches and binds the original receipt to its exact store scope, tool, key, payload, version and state. Source revalidation precedes staging; exact deletion additionally checks physical identity and immutable tuple/date bits. Allocation selects a new task UUID before graph validation and assigns it before insertion. Dirty shared contexts are checked before acceptance and after preparation success or error. Retained replay remains read-only and precedes current graph lookup; uncertain persistence retains original-key reconciliation instead of clearing durable guards.

Capture reuses the task population already fetched within the fence, avoiding a second fetch that could replace selected evidence before canonical serialization. The original five-second deadline reaches graph construction, body selection, filters and encoding. Existing physical read admission and five-minute/eight-view/16-MiB retention caps remain intact; graph backing values, index membership and diagnostics are charged. Deadline or capacity exhaustion produces a whole failure without late publication. Startup cleanup separately scans at most 512 evidence candidates, deletes at most 128 eligible uniquely identified rows and uses one owned save with rollback on failure.

### Architecture and limits

The extension joins the landed read capture, modern result, reusable portfolio and batch coordinator foundations. Saved native navigation checks uniqueness both at click and at macOS window resolution, then returns the exact physical model owned by the navigation context. Native saved projections invalidate the prior generation before a cancellable 100-ms same-source notification wait, recheck generation/source/cancellation before capture and publication, and retain immediate initial loads; they do not advertise the MCP capture's certified frozen boundary. Optional efficiency follow-ups include diagnostic indexing and notification coalescing, within the same budgets and freshness semantics.

Live Development CloudKit schema/export/deletion verification remains T-2402 work. Installed-client activation, production promotion and T-2381 consolidation are outside this local implementation. Local schema migration and scalar compatibility do not prove CloudKit-wide atomicity or convergence.

Important changes — detailed

Preserve physical link evidence

Transit/Transit/Models/TaskLinkOccurrence.swift

Why it matters. Store directed typed occurrences without redirecting or merging originals.

What to look at. Additive scalar link and removal evidence models; explicit raw diagnostics and exact removal.

Validate graph-aware owned writes

Transit/Transit/MCP/Writes/TaskLinkOwnedApply.swift

Why it matters. Reject stale source/endpoint evidence and commit domain changes with the original protected receipt.

What to look at. Participating synchronous owned-save phase, explicit graph guards, repair/no-op/replay semantics.

Freeze saved graph query evidence

Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swift

Why it matters. Keep pending drafts out of results and preserve existing capture budgets.

What to look at. Capture all physical graph closure within existing fences; filter before ordering and page publication.

Expose saved native relationships

Transit/Transit/Views/TaskDetail/TaskLinksSection.swift

Why it matters. Show diagnostics and navigate only an exact unique saved task.

What to look at. Correct incoming labels, cancellable 100-ms notification coalescing after generation invalidation, immediate initial loads and exact unique saved navigation.

Retain compatibility and evidence

specs/typed-task-links/local-review.md

Why it matters. Make current scope and historical failures reviewable.

What to look at. 39 criteria mapped, final platform results, corrective controls and explicit deferred boundaries.

Key decisions

Participating local write boundary Owner approved pre-save validation and owned same-store domain/receipt saving. Independent writers and imports are outside the synchronous boundary; available saved faults are reported without automatic repair.
Separate duplicate relationships from consolidation Duplicate chains identify a canonical UUID while retaining every original task and comment. T-2381 preview/apply/undo consolidation remains separately gated.
Internal review fallback Unavailable external review was replaced with documented independent local peer perspectives; no source disclosure.

Review findings

SeverityAreaFindingResolution
mediumSaved graph captureA duplicate task fetch could replace selected canonical evidence.Reuse the already captured full task population; original malformed-canonical assertion remains intact.
mediumCompatibility error precedenceProject/milestone hooks and shape precedence drifted.Restore discarded error checks and validate selector shape before hooks; focused 170 cases and all full suites pass.
lowCaller contractNonexistent batch tool name advertised.Corrected to mutate_tasks.
lowMaintenance / bounded efficiencyDuplicate status catalog, unused parameter, preparation repetition, broad notifications and diagnostic scans.Optional follow-ups; reviewed bounded behavior is correct.
mediumNative notification freshness and directionSave/import bursts repeated whole-graph work; incoming attribution/duplicate labels were misleading.Immediate generation invalidation, cancellable 100-ms same-source wait, provider/publication guards and explicit source-relative labels. Fresh 20 focused and all full-platform runs passed.

Tests

Source: local run at 2026-10-05T05:15:49.297395+00:00 · snapshot bbe3a2560584f7fb822aa8006b20f08d22284ce4

Baseline: none

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

Coverage scope: every test in the repository

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 e04c1268ee37bd4ae925d4d686954cf2121005c7.

Dependents none found Changed Dependencies none found . Transit/Transit Transit/Transit/MCP …ansit/Transit/MCP/BatchWrites Transit/Transit/MCP/Links Transit/Transit/MCP/Reads Transit/Transit/MCP/Results Transit/Transit/MCP/Writes Transit/Transit/Models Transit/Transit/Services …it/Transit/Services/TaskLinks …nsit/Transit/Views/TaskDetail Transit/TransitTests Transit/TransitUITests tests/mcp-write-probe tests/typed-task-links …sk-links/development-cloudkit MakefileMakefile Transit/Transit/TransitApp.swift…nsit/Transit/TransitApp.swift Transit/Transit/UITestScenario.swift…/Transit/UITestScenario.swift Transit/Transit/MCP/MCPPortfolioCaptureCharge.swift…PPortfolioCaptureCharge.swift Transit/Transit/MCP/MCPTaskQueryRequest.swift…MCP/MCPTaskQueryRequest.swift Transit/Transit/MCP/MCPToolDefinitions+Protected.swift…olDefinitions+Protected.swift Transit/Transit/MCP/MCPToolDefinitions.swift…/MCP/MCPToolDefinitions.swift Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift…CPToolHandler+TaskQuery.swift Transit/Transit/MCP/MCPToolHandler+TaskQueryFailureChecks.swift…+TaskQueryFailureChecks.swift Transit/Transit/MCP/MCPToolHandler.swift…nsit/MCP/MCPToolHandler.swift Transit/Transit/MCP/MCPTypes.swift…it/Transit/MCP/MCPTypes.swift Transit/Transit/MCP/TaskLinkWireSchema.swift…/MCP/TaskLinkWireSchema.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreview.swift…tes/MCPBatchTaskPreview.swift Transit/Transit/MCP/BatchWrites/MCPBatchTaskSchema.swift…ites/MCPBatchTaskSchema.swift Transit/Transit/MCP/BatchWrites/MCPBatchWritePolicy.swift…tes/MCPBatchWritePolicy.swift Transit/Transit/MCP/Links/TaskLinkQueryOptions.swift…ks/TaskLinkQueryOptions.swift Transit/Transit/MCP/Links/TaskLinkQueryProjection.swift…TaskLinkQueryProjection.swift Transit/Transit/MCP/Links/TaskLinkQuerySchema.swift…nks/TaskLinkQuerySchema.swift Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swift…s/MCPReadCaptureBuilder.swift Transit/Transit/MCP/Reads/MCPReadCaptureTypes.swift…ads/MCPReadCaptureTypes.swift Transit/Transit/MCP/Reads/MCPReadProjection+ProjectSelector.swift…jection+ProjectSelector.swift Transit/Transit/MCP/Reads/MCPReadProjection.swift…Reads/MCPReadProjection.swift Transit/Transit/MCP/Reads/MCPReadService+CaptureRequest.swift…dService+CaptureRequest.swift Transit/Transit/MCP/Reads/MCPReadService.swift…CP/Reads/MCPReadService.swift Transit/Transit/MCP/Reads/TaskLinkCaptureIntegration.swift…kLinkCaptureIntegration.swift Transit/Transit/MCP/Results/MCPResultClassification.swift…MCPResultClassification.swift Transit/Transit/MCP/Writes/MCPRecordSnapshot.swift…rites/MCPRecordSnapshot.swift Transit/Transit/MCP/Writes/MCPWriteCommand.swift…/Writes/MCPWriteCommand.swift Transit/Transit/MCP/Writes/MCPWriteCommitServices.swift…/MCPWriteCommitServices.swift Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift…tes/MCPWriteCoordinator.swift Transit/Transit/MCP/Writes/TaskLinkIncidence.swift…rites/TaskLinkIncidence.swift Transit/Transit/MCP/Writes/TaskLinkOwnedApply.swift…ites/TaskLinkOwnedApply.swift Transit/Transit/MCP/Writes/TaskLinkOwnedPlan.swift…rites/TaskLinkOwnedPlan.swift Transit/Transit/MCP/Writes/TaskLinkWireRequest.swift…tes/TaskLinkWireRequest.swift Transit/Transit/MCP/Writes/TaskLinkWriteAdapter.swift…es/TaskLinkWriteAdapter.swift Transit/Transit/MCP/Writes/TaskLinkWriteFailure.swift…es/TaskLinkWriteFailure.swift Transit/Transit/Models/TaskLinkOccurrence.swift…dels/TaskLinkOccurrence.swift Transit/Transit/Models/TaskLinkRemovalEvidence.swift…TaskLinkRemovalEvidence.swift Transit/Transit/Services/TaskService.swift…it/Services/TaskService.swift Transit/Transit/Services/TaskLinks/TaskLinkEvidenceMaintenance.swift…LinkEvidenceMaintenance.swift Transit/Transit/Services/TaskLinks/TaskLinkGraph.swift…TaskLinks/TaskLinkGraph.swift Transit/Transit/Services/TaskLinks/TaskLinkGraphCharge.swift…nks/TaskLinkGraphCharge.swift Transit/Transit/Services/TaskLinks/TaskLinkGraphIndex.swift…inks/TaskLinkGraphIndex.swift Transit/Transit/Services/TaskLinks/TaskLinkGraphValues.swift…nks/TaskLinkGraphValues.swift Transit/Transit/Services/TaskLinks/TaskLinkNativeDetailState.swift…skLinkNativeDetailState.swift Transit/Transit/Services/TaskLinks/TaskLinkNativeLabels.swift…ks/TaskLinkNativeLabels.swift Transit/Transit/Services/TaskLinks/TaskLinkNavigationResolver.swift…kLinkNavigationResolver.swift Transit/Transit/Services/TaskLinks/TaskLinkPlan.swift…/TaskLinks/TaskLinkPlan.swift Transit/Transit/Services/TaskLinks/TaskLinkService.swift…skLinks/TaskLinkService.swift Transit/Transit/Views/TaskDetail/TaskDetailView.swift…skDetail/TaskDetailView.swift Transit/Transit/Views/TaskDetail/TaskDetailWindowView.swift…il/TaskDetailWindowView.swift Transit/Transit/Views/TaskDetail/TaskLinksSection.swift…Detail/TaskLinksSection.swift Transit/TransitTests/MCPBatchTaskCoordinatorDurabilityTests.swift…rdinatorDurabilityTests.swift Transit/TransitTests/MCPBatchTaskCoordinatorFixture.swift…hTaskCoordinatorFixture.swift Transit/TransitTests/MCPBatchTaskPreviewFixture.swift…BatchTaskPreviewFixture.swift Transit/TransitTests/MCPBatchTaskSafetyFixture.swift…PBatchTaskSafetyFixture.swift Transit/TransitTests/MCPDuplicateTaskDisplayIDTests.swift…icateTaskDisplayIDTests.swift Transit/TransitTests/MCPFallbackStorageRejectionTests.swift…ckStorageRejectionTests.swift Transit/TransitTests/MCPReadCaptureBuilderTests.swift…ReadCaptureBuilderTests.swift Transit/TransitTests/MCPReadServiceTests.swift…sts/MCPReadServiceTests.swift Transit/TransitTests/MCPRecordRevisionTests.swift…/MCPRecordRevisionTests.swift Transit/TransitTests/MCPTaskQueryFailureTests.swift…CPTaskQueryFailureTests.swift Transit/TransitTests/MCPTaskQuerySelectorPrecedenceTests.swift…SelectorPrecedenceTests.swift Transit/TransitTests/MCPTaskQueryTests.swift…Tests/MCPTaskQueryTests.swift Transit/TransitTests/MCPWritePersistenceProbeTests.swift…tePersistenceProbeTests.swift Transit/TransitTests/NumericDisplayIdParsingTests.swift…icDisplayIdParsingTests.swift Transit/TransitTests/TaskLinkClosedStoreMigrationTests.swift…osedStoreMigrationTests.swift Transit/TransitTests/TaskLinkCommitBoundaryTests.swift…LinkCommitBoundaryTests.swift Transit/TransitTests/TaskLinkFoundationIntegrationTests.swift…ndationIntegrationTests.swift Transit/TransitTests/TaskLinkGraphGeneratedTests.swift…LinkGraphGeneratedTests.swift Transit/TransitTests/TaskLinkGraphServiceTests.swift…skLinkGraphServiceTests.swift Transit/TransitTests/TaskLinkGraphTests.swift…ests/TaskLinkGraphTests.swift Transit/TransitTests/TaskLinkMigrationTests.swift…/TaskLinkMigrationTests.swift Transit/TransitTests/TaskLinkNativeLabelTests.swift…askLinkNativeLabelTests.swift Transit/TransitTests/TaskLinkNativeProjectionTests.swift…nkNativeProjectionTests.swift Transit/TransitTests/TaskLinkNativeRefreshTests.swift…kLinkNativeRefreshTests.swift Transit/TransitTests/TaskLinkOwnedPhaseTests.swift…TaskLinkOwnedPhaseTests.swift Transit/TransitTests/TaskLinkOwnedScopeTests.swift…TaskLinkOwnedScopeTests.swift Transit/TransitTests/TaskLinkParticipatingBoundaryTests.swift…ticipatingBoundaryTests.swift Transit/TransitTests/TaskLinkPlanTests.swift…Tests/TaskLinkPlanTests.swift Transit/TransitTests/TaskLinkProtectedBoundaryTests.swift…kProtectedBoundaryTests.swift Transit/TransitTests/TaskLinkQueryBoundaryTests.swift…kLinkQueryBoundaryTests.swift Transit/TransitTests/TaskLinkQueryTests.swift…ests/TaskLinkQueryTests.swift Transit/TransitTests/TaskLinkReadCaptureBoundaryTests.swift…eadCaptureBoundaryTests.swift Transit/TransitTests/TaskLinkReadCaptureTests.swift…askLinkReadCaptureTests.swift Transit/TransitTests/TaskLinkRemovalEvidenceTests.swift…inkRemovalEvidenceTests.swift Transit/TransitTests/TaskLinkRevisionTests.swift…s/TaskLinkRevisionTests.swift Transit/TransitTests/TaskLinkWireTests.swift…Tests/TaskLinkWireTests.swift Transit/TransitTests/TaskLinkWriteFixture.swift…ts/TaskLinkWriteFixture.swift Transit/TransitTests/TaskLinkWriteIntegrationTests.swift…nkWriteIntegrationTests.swift Transit/TransitTests/TaskLinkWriteRepairTests.swift…askLinkWriteRepairTests.swift Transit/TransitTests/TestModelContainer.swift…ests/TestModelContainer.swift Transit/TransitUITests/TaskLinkNativeUITests.swift…s/TaskLinkNativeUITests.swift tests/mcp-write-probe/CoordinatorProbe.swift…-probe/CoordinatorProbe.swift tests/mcp-write-probe/FoundationProbe.swift…e-probe/FoundationProbe.swift tests/mcp-write-probe/Probe.swift…s/mcp-write-probe/Probe.swift tests/mcp-write-probe/ServiceProbe.swift…rite-probe/ServiceProbe.swift tests/typed-task-links/audit_schema_sources.py…links/audit_schema_sources.py tests/typed-task-links/pending-schema-registration.patch…ing-schema-registration.patch tests/typed-task-links/prepare_capture_run.py…-links/prepare_capture_run.py tests/typed-task-links/prepare_evidence_run.py…links/prepare_evidence_run.py tests/typed-task-links/prepare_foundation_run.py…nks/prepare_foundation_run.py tests/typed-task-links/prepare_graph_run.py…sk-links/prepare_graph_run.py tests/typed-task-links/prepare_native_run.py…k-links/prepare_native_run.py tests/typed-task-links/prepare_participating_run.py…/prepare_participating_run.py tests/typed-task-links/prepare_query_run.py…sk-links/prepare_query_run.py tests/typed-task-links/prepare_revision_compatibility_run.py…revision_compatibility_run.py tests/typed-task-links/prepare_revision_run.py…links/prepare_revision_run.py tests/typed-task-links/prepare_scope_run.py…sk-links/prepare_scope_run.py tests/typed-task-links/prepare_unit_run.py…ask-links/prepare_unit_run.py tests/typed-task-links/prepare_wire_run.py…ask-links/prepare_wire_run.py tests/typed-task-links/prepare_writes_run.py…k-links/prepare_writes_run.py tests/typed-task-links/run_closed_store.py…ask-links/run_closed_store.py tests/typed-task-links/run_commit_diagnostic.py…inks/run_commit_diagnostic.py tests/typed-task-links/development-cloudkit/Smoke.swift…elopment-cloudkit/Smoke.swift tests/typed-task-links/development-cloudkit/preflight.py…lopment-cloudkit/preflight.py
addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

149 files: 118 code · 31 docs. Click to expand.

Code (118)

Makefile Changed +2 / -2
diff --git a/Makefile b/Makefileindex ceb44b76..cb80d265 100644--- a/Makefile+++ b/Makefile@@ -145,7 +145,7 @@ build: build-ios build-macos # Nested macro sandboxing is unavailable in some already-sandboxed runners. # Set MCP_PROBE_SWIFT_FLAGS=-disable-sandbox there; the outer runner policy stays active. MCP_PROBE_SWIFT_FLAGS ?=-MCP_PROBE_MODELS = Transit/Transit/Models/{Project,TransitTask,Comment,Milestone,SyncHeartbeat,DisplayID,TaskPriority,TaskStatus,TaskType,MilestoneStatus,MCPWriteReceipt}.swift+MCP_PROBE_MODELS = Transit/Transit/Models/{Project,TransitTask,Comment,Milestone,SyncHeartbeat,DisplayID,TaskPriority,TaskStatus,TaskType,MilestoneStatus,MCPWriteReceipt,TaskLinkOccurrence,TaskLinkRemovalEvidence}.swift Transit/Transit/Services/TaskLinks/TaskLinkGraphValues.swift  # These standalone executables never launch Transit. Runtime children use a # network-denying sandbox and synthetic stores confined to DerivedData/tmp.@@ -200,7 +200,7 @@ test-mcp-write-guards: prepare-cache-dirs .PHONY: test-mcp-write-foundation 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 \+		$(MCP_PROBE_MODELS) Transit/Transit/MCP/Writes/{MCPCanonicalJSON,MCPRecordSnapshot,MCPRecordRevision,TaskLinkIncidence,MCPLocalReservationStore,MCPWriteReceiptStore}.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
Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreview.swift Changed +2 / -1
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreview.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreview.swiftindex 268fbb51..b7b8ddd1 100644--- a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreview.swift+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskPreview.swift@@ -84,7 +84,8 @@ import SwiftData                     code: tasks.isEmpty ? "TASK_NOT_FOUND" : "DUPLICATE_TASK_IDENTIFIER")             }             task = resolved-            snapshot = try MCPRecordSnapshot.task(task) { id in+            snapshot = try MCPRecordSnapshot.task(task, incidence: TaskLinkIncidence.capture(task.id, in: context,+                includePendingChanges: false)) { id in                 var comments = CommentService.descriptor(for: id)                 comments.includePendingChanges = false                 return try reads.comments(comments, context)
Transit/Transit/MCP/BatchWrites/MCPBatchTaskSchema.swift Changed +2 / -0
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskSchema.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskSchema.swiftindex 1c55fe9a..87a94a0f 100644--- a/Transit/Transit/MCP/BatchWrites/MCPBatchTaskSchema.swift+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchTaskSchema.swift@@ -19,6 +19,8 @@ nonisolated enum MCPBatchTaskSchema {             throw MCPResultBoundaryError.unsupportedEvidence         }         properties.removeValue(forKey: "displayId")+        properties.removeValue(forKey: "linkChanges")+        properties.removeValue(forKey: "endpointPreconditions")         var required = definition.inputSchema.required ?? []         if !required.contains("taskId") { required.append("taskId") }         return ArgumentShape(properties: properties, required: required)
Transit/Transit/MCP/BatchWrites/MCPBatchWritePolicy.swift Changed +23 / -2
diff --git a/Transit/Transit/MCP/BatchWrites/MCPBatchWritePolicy.swift b/Transit/Transit/MCP/BatchWrites/MCPBatchWritePolicy.swiftindex 80c4b51f..6d2c4b4f 100644--- a/Transit/Transit/MCP/BatchWrites/MCPBatchWritePolicy.swift+++ b/Transit/Transit/MCP/BatchWrites/MCPBatchWritePolicy.swift@@ -12,15 +12,36 @@ import SwiftData     }      let onPendingEditsStop: @MainActor () -> Void+    let makeCommitServices: (@MainActor (ModelContext) throws -> MCPWriteCommitServices)?+    let taskLinkCapability: TaskLinkWriteCapability?+    let afterTaskApply: MCPWriteCommand.AfterTaskApply?     let validateBeforeApply: @MainActor (MCPWriteCommand, ModelContext) throws -> Void +    /// Swift's forward matching can bind an unlabelled trailing closure to the+    /// optional factory. Preserve the existing two-argument validation API.+    init(validateBeforeApply: @escaping @MainActor (MCPWriteCommand, ModelContext) throws -> Void) {+        self.init(makeCommitServices: nil, onPendingEditsStop: {}, validateBeforeApply: validateBeforeApply)+    }++    init(makeCommitServices: @escaping @MainActor (ModelContext) throws -> MCPWriteCommitServices,+         validateBeforeApply: @escaping @MainActor (MCPWriteCommand, ModelContext) throws -> Void) {+        self.init(makeCommitServices: makeCommitServices, onPendingEditsStop: {},+                  validateBeforeApply: validateBeforeApply)+    }+     init(+        makeCommitServices: (@MainActor (ModelContext) throws -> MCPWriteCommitServices)? = nil,+        onPendingEditsStop: @escaping @MainActor () -> Void = {},+        afterTaskApply: MCPWriteCommand.AfterTaskApply? = nil,+        taskLinkCapability: TaskLinkWriteCapability? = nil,         validateBeforeApply: @escaping @MainActor (MCPWriteCommand, ModelContext) throws -> Void =-            MCPBatchWritePolicy.validateTaskIdentity,-        onPendingEditsStop: @escaping @MainActor () -> Void = {}+            MCPBatchWritePolicy.validateTaskIdentity     ) {+        self.taskLinkCapability = taskLinkCapability+        self.afterTaskApply = afterTaskApply         self.validateBeforeApply = validateBeforeApply         self.onPendingEditsStop = onPendingEditsStop+        self.makeCommitServices = makeCommitServices     }      private static func validateTaskIdentity(_ command: MCPWriteCommand, context: ModelContext) throws {
Transit/Transit/MCP/Links/TaskLinkQueryOptions.swift Changed +77 / -0
diff --git a/Transit/Transit/MCP/Links/TaskLinkQueryOptions.swift b/Transit/Transit/MCP/Links/TaskLinkQueryOptions.swiftnew file mode 100644index 00000000..1ec14fee--- /dev/null+++ b/Transit/Transit/MCP/Links/TaskLinkQueryOptions.swift@@ -0,0 +1,77 @@+#if os(macOS)+import Foundation++nonisolated struct TaskLinkQueryOptions: Sendable {+    static let keys: Set<String> = ["hasLinks", "linkType", "linkDirection", "linkTargetTaskId", "unblocked"]+    let hasLinks: Bool?+    let type: TaskLinkType?+    let direction: String?+    let target: UUID?+    let unblocked: Bool?++    @MainActor static func parse(_ args: [String: Any]) throws -> Self? {+        guard !keys.isDisjoint(with: args.keys) else { return nil }+        func boolean(_ key: String) throws -> Bool? {+            guard let raw = args[key] else { return nil }+            guard let value = IntentHelpers.parseBoolValue(raw) else {+                throw MCPTaskQueryError.invalid("\(key) must be a boolean")+            }+            return value+        }+        let type: TaskLinkType?+        if let raw = args["linkType"] {+            guard let name = raw as? String, let parsed = TaskLinkType(rawValue: name) else {+                throw MCPTaskQueryError.invalid("linkType must be a documented public link type")+            }+            type = parsed+        } else { type = nil }+        let direction: String?+        if let raw = args["linkDirection"] {+            guard let value = raw as? String, ["incoming", "outgoing"].contains(value),+                  type == .introducedBy || type == .duplicateOf else {+                throw MCPTaskQueryError.invalid("linkDirection requires introduced-by or duplicate-of")+            }+            direction = value+        } else { direction = nil }+        let target: UUID?+        if let raw = args["linkTargetTaskId"] {+            guard type != nil, let value = raw as? String, let id = UUID(uuidString: value) else {+                throw MCPTaskQueryError.invalid("linkTargetTaskId requires a linkType and valid UUID")+            }+            target = id+        } else { target = nil }+        return try Self(hasLinks: boolean("hasLinks"), type: type, direction: direction,+                        target: target, unblocked: boolean("unblocked"))+    }++    // Each public orientation is checked against raw stored incidence.+    // swiftlint:disable:next cyclomatic_complexity+    @MainActor func matches(_ id: UUID, graph: TaskLinkGraphView?, budget: TaskLinkGraphBudget) throws -> Bool {+        try budget.check()+        guard let graph else { throw MCPReadCaptureError.incoherentCapture }+        let rows = graph.incidence[id, default: []]+        if let hasLinks, hasLinks != !rows.isEmpty { return false }+        if let unblocked {+            let assessment = graph.assessment(for: id)+            guard assessment == (unblocked ? .unblocked : .blocked) else { return false }+        }+        guard let type else { return true }+        for row in rows {+            try budget.check()+            guard !graph.invalidOccurrences.contains(row.physicalKey) else { continue }+            let incoming = row.target == id+            let opposite = incoming ? row.source : row.target+            if let target, target != opposite { continue }+            switch type {+            case .blocks: if row.kind == "dependency" && !incoming { return true }+            case .blockedBy: if row.kind == "dependency" && incoming { return true }+            case .relatesTo: if row.kind == "association" { return true }+            case .introducedBy, .duplicateOf:+                let expected = type == .introducedBy ? "attribution" : "duplicate"+                if row.kind == expected && incoming == (direction == "incoming") { return true }+            }+        }+        return false+    }+}+#endif
Transit/Transit/MCP/Links/TaskLinkQueryProjection.swift Changed +59 / -0
diff --git a/Transit/Transit/MCP/Links/TaskLinkQueryProjection.swift b/Transit/Transit/MCP/Links/TaskLinkQueryProjection.swiftnew file mode 100644index 00000000..bc165f4e--- /dev/null+++ b/Transit/Transit/MCP/Links/TaskLinkQueryProjection.swift@@ -0,0 +1,59 @@+#if os(macOS)+import Foundation++/// Observation-only enrichment from the same frozen graph as the task record.+@MainActor enum TaskLinkQueryProjection {+    static func detail(_ id: UUID, graph: TaskLinkGraphView?, budget: TaskLinkGraphBudget) throws -> [String: Any] {+        try budget.check()+        guard let graph else {+            return ["graphCoverage": "unavailable", "links": NSNull(), "linkDiagnostics": NSNull(),+                "duplicateResolution": NSNull(), "blockerAssessment": ["assessment": "unavailable"]]+        }+        var links: [[String: Any]] = []+        for row in graph.incidence[id, default: []] {+            try budget.check()+            let incoming = row.target == id+            let opposite = incoming ? row.source : row.target+            let matches = graph.tasksById[opposite, default: []]+            let name: Any = matches.count == 1 ? matches[0].name : NSNull()+            let type: String+            switch row.kind {+            case "dependency": type = incoming ? "blocked-by" : "blocks"+            case "association": type = "relates-to"+            case "attribution": type = "introduced-by"+            case "duplicate": type = "duplicate-of"+            default: type = row.kind+            }+            var value: [String: Any] = ["edgeId": row.id.uuidString, "storedKind": row.kind, "type": type,+                "sourceTaskId": row.source.uuidString, "targetTaskId": row.target.uuidString,+                "oppositeTaskId": opposite.uuidString, "targetName": name,+                "direction": incoming ? "incoming" : "outgoing",+                "physicalIdentity": row.physicalKey.base64EncodedString(),+                "valid": !graph.invalidOccurrences.contains(row.physicalKey)]+            if graph.occurrencesById[row.id]?.count == 1,+               let revision = try? TaskLinkGraph.occurrenceRevision(row) { value["occurrenceRevision"] = revision }+            links.append(value)+        }+        let incidentIDs = Set(graph.incidence[id, default: []].map(\.id))+        var diagnostics: [[String: Any]] = []+        for diagnostic in graph.diagnostics {+            try budget.check()+            guard diagnostic.taskIds.contains(id) || diagnostic.edgeId.map(incidentIDs.contains) == true+            else { continue }+            var value: [String: Any] = ["code": diagnostic.code,+                "taskIds": diagnostic.taskIds.map(\.uuidString),+                "physicalIdentity": diagnostic.physicalKey.base64EncodedString()]+            value["edgeId"] = diagnostic.edgeId?.uuidString+            diagnostics.append(value)+        }+        let duplicate = try TaskLinkGraph.duplicateResolution(for: id, in: graph, budget: budget)+        let result: [String: Any] = ["graphCoverage": "available", "links": links, "linkDiagnostics": diagnostics,+            "duplicateResolution": ["path": duplicate.path.map(\.uuidString),+                "canonicalTaskId": duplicate.canonical?.uuidString as Any? ?? NSNull(),+                "diagnostic": duplicate.diagnostic as Any? ?? NSNull()],+            "blockerAssessment": ["assessment": graph.assessment(for: id).rawValue,+                                  "evaluatedAt": MCPRecordSnapshot.timestamp(graph.evaluationInstant)]]+        try budget.check(); return result+    }+}+#endif
Transit/Transit/MCP/Links/TaskLinkQuerySchema.swift Changed +35 / -0
diff --git a/Transit/Transit/MCP/Links/TaskLinkQuerySchema.swift b/Transit/Transit/MCP/Links/TaskLinkQuerySchema.swiftnew file mode 100644index 00000000..e89bac8e--- /dev/null+++ b/Transit/Transit/MCP/Links/TaskLinkQuerySchema.swift@@ -0,0 +1,35 @@+#if os(macOS)+import Foundation++nonisolated enum TaskLinkQuerySchema {+    static let properties: [String: JSONSchemaProperty] = [+        "hasLinks": .boolean("Recorded active incidence, including invalid physical occurrences"),+        "linkType": .stringEnum("Require a valid incident relation in this public orientation",+                                    values: TaskLinkType.allCases.map(\.rawValue)),+        "linkDirection": .stringEnum("Only introduced-by/duplicate-of; defaults outgoing; requires linkType",+                                         values: ["incoming", "outgoing"]),+        "linkTargetTaskId": .string("Opposite endpoint UUID; requires linkType; never follows duplicate aliases"),+        "unblocked": .boolean("True: certified unblocked; false: certified blocked; invalid/unavailable match neither")+    ]++    static let guidance = """+    Graph options apply conjunctively to ordinary list/displayId selection before ordering and pagination.+    UUID/display-ID batch selectors retain their existing no-filter contract. Reusable snapshot queries reject+    graph options. blocks is outgoing dependency; blocked-by is incoming dependency; relates-to is symmetric.+    Direction is supported only for introduced-by and duplicate-of. Type/target filters match valid occurrences;+    hasLinks includes recorded invalid rows. Only Done direct blockers are satisfied; Abandoned is blocked.+    Missing, ambiguous, cyclic or invalid blocker evidence certifies neither unblocked value. Duplicate paths do+    not redirect selection or flatten stored occurrences. Full detail includes links with edgeId, exact+    occurrenceRevision when identifiable, stored endpoints, public type, direction, saved opposite targetName+    and physicalIdentity; linkDiagnostics preserve available physical conflicts. duplicateResolution contains+    path, canonicalTaskId or null and diagnostic; blockerAssessment supplies assessment and evaluatedAt. All+    observation fields use the same frozen saved capture as the record; UI drafts are never returned. Current+    full revisions cover fields, all comments and active incidence (task-fields-comments-links-v1), including+    empty incidence. Labels, blocker status, transitive paths and removal retention are observation evidence+    outside that token. Pre-feature r1 tokens conflict on fresh writes even for no-link tasks. Omitted bodies do+    not imply empty incidence. Missing historic graph capture reports graphCoverage unavailable with null link+    observations; accepted historic receipt bytes and revisions remain immutable. Protection covers+    participating local writes, not independent imports or writers.+    """+}+#endif
Transit/Transit/MCP/MCPPortfolioCaptureCharge.swift Changed +4 / -0
diff --git a/Transit/Transit/MCP/MCPPortfolioCaptureCharge.swift b/Transit/Transit/MCP/MCPPortfolioCaptureCharge.swiftindex bf24ef62..8ceca431 100644--- a/Transit/Transit/MCP/MCPPortfolioCaptureCharge.swift+++ b/Transit/Transit/MCP/MCPPortfolioCaptureCharge.swift@@ -19,6 +19,10 @@ nonisolated enum MCPPortfolioCaptureCharge {         try records(view.tasks, operation: operation, count: &count, encode: task)         try records(view.milestones, operation: operation, count: &count, encode: milestone)         try records(view.comments, operation: operation, count: &count, encode: comment)+        if let graph = view.taskLinkGraph {+            try MCPPortfolioReadEncoding.check(operation)+            try add(graph.retainedBytes, to: &count)+        }         return count     } 
Transit/Transit/MCP/MCPTaskQueryRequest.swift Changed +6 / -4
diff --git a/Transit/Transit/MCP/MCPTaskQueryRequest.swift b/Transit/Transit/MCP/MCPTaskQueryRequest.swiftindex 36465ab9..a9a56045 100644--- a/Transit/Transit/MCP/MCPTaskQueryRequest.swift+++ b/Transit/Transit/MCP/MCPTaskQueryRequest.swift@@ -22,6 +22,7 @@ struct MCPTaskQueryRequest: Sendable {     let includeComments: Bool     let limit: Int     let selector: Selector+    var graphOptions: TaskLinkQueryOptions?      static let filterKeys: Set<String> = [         "project", "projectId", "status", "not_status", "unfinished", "type", "priority",@@ -39,9 +40,9 @@ struct MCPTaskQueryRequest: Sendable {                 throw MCPTaskQueryError(code: "INVALID_CURSOR", message: "Invalid cursor; start a new query")             }             return Self(readPolicy: policy, cursor: cursor, detailLevel: "summary",-                        includeComments: false, limit: 1, selector: .list)+                        includeComments: false, limit: 1, selector: .list, graphOptions: nil)         }-        let allowed = filterKeys.union([+        let allowed = filterKeys.union(TaskLinkQueryOptions.keys).union([             "detailLevel", "includeComments", "limit", "displayId", "taskIds", "displayIds", "readPolicy"         ])         guard Set(args.keys).isSubset(of: allowed) else {@@ -59,7 +60,7 @@ struct MCPTaskQueryRequest: Sendable {         let selectors = ["displayId", "taskIds", "displayIds"].filter { args[$0] != nil }         guard selectors.count <= 1 else { throw MCPTaskQueryError.invalid("Use only one task selector") }         if args["taskIds"] != nil || args["displayIds"] != nil {-            guard filterKeys.isDisjoint(with: args.keys) else {+            guard filterKeys.union(TaskLinkQueryOptions.keys).isDisjoint(with: args.keys) else {                 throw MCPTaskQueryError.invalid("Batch selectors cannot be combined with filters")             }         }@@ -86,7 +87,8 @@ struct MCPTaskQueryRequest: Sendable {             selector = .list         }         return Self(readPolicy: try policy(args["readPolicy"]), cursor: nil, detailLevel: detail,-                    includeComments: comments, limit: limit, selector: selector)+                    includeComments: comments, limit: limit, selector: selector,+                    graphOptions: try TaskLinkQueryOptions.parse(args))     }      private static func policy(_ raw: Any?) throws -> MCPReadPolicy? {
Transit/Transit/MCP/MCPToolDefinitions+Protected.swift Changed +49 / -0
diff --git a/Transit/Transit/MCP/MCPToolDefinitions+Protected.swift b/Transit/Transit/MCP/MCPToolDefinitions+Protected.swiftnew file mode 100644index 00000000..99cb4424--- /dev/null+++ b/Transit/Transit/MCP/MCPToolDefinitions+Protected.swift@@ -0,0 +1,49 @@+#if os(macOS)+import Foundation++extension MCPToolDefinitions {+    nonisolated private static let writeSafetyContract = """+        Requires a case-sensitive idempotencyKey matching [A-Za-z0-9._:-]{1,128}. \+        Retried identical arguments replay the original saved outcome for seven days across local-store restarts; \+        JSON object order is ignored and different payloads return IDEMPOTENCY_KEY_REUSED. \+        Results are JSON committed/rejected/in_progress/uncertain envelopes with saved records and r1 revisions. \+        Replay expiry is fixed; after it a retry may execute again. Uncertain outcomes require reconciliation; \+        never retry them with a fresh key. Revisions compare exact locally observed content, remain stable for no-ops \+        and restored content, and cannot detect edits not yet imported from CloudKit or prevent later sync conflicts. \+        Read a task or milestone first, write with its expectedRevision and a fresh key, then retry identical \+        arguments \+        with that key after a timeout. REVISION_CONFLICT returns the currentRecord and no effect; use a new key after \+        reviewing it. Keys are scoped to this local store and tool, independently of connection/session/request ID. \+        Cross-device deduplication and atomic batches are not provided.+        """++    nonisolated static func protected(_ definition: MCPToolDefinition) -> MCPToolDefinition {+        var properties = definition.inputSchema.properties ?? [:]+        var key = JSONSchemaProperty.string("Required retry key; UUID strings are suitable")+        key.pattern = "^[A-Za-z0-9._:-]{1,128}$"+        properties["idempotencyKey"] = key+        let hasLinks = ["create_task", "update_task"].contains(definition.name)+        if hasLinks {+            properties["linkChanges"] = TaskLinkWireSchema.changes(creating: definition.name == "create_task")+            properties["endpointPreconditions"] = TaskLinkWireSchema.endpoints+        }+        var required = definition.inputSchema.required ?? []+        required.append("idempotencyKey")+        if ["update_task", "update_task_status", "update_milestone", "delete_milestone"].contains(definition.name) {+            var revision = JSONSchemaProperty.string("Required target revision from the full read response")+            revision.pattern = "^r1:[0-9a-f]{64}$"+            properties["expectedRevision"] = revision+            required.append("expectedRevision")+        }+        var schema = JSONSchema.object(properties: properties, required: required)+        schema.additionalProperties = false+        return MCPToolDefinition(+            name: definition.name,+            description: definition.description + " " + writeSafetyContract ++                (hasLinks ? " " + TaskLinkWireSchema.description : ""),+            inputSchema: schema)+    }++}++#endif
Transit/Transit/MCP/MCPToolDefinitions.swift Changed +3 / -41
diff --git a/Transit/Transit/MCP/MCPToolDefinitions.swift b/Transit/Transit/MCP/MCPToolDefinitions.swiftindex af05412d..90362947 100644--- a/Transit/Transit/MCP/MCPToolDefinitions.swift+++ b/Transit/Transit/MCP/MCPToolDefinitions.swift@@ -182,10 +182,11 @@ extension MCPToolDefinitions {      nonisolated static let queryTasks = MCPToolDefinition(         name: "query_tasks",-        description: queryTasksDescription + "\n\n" + readExecutionDescription+        description: queryTasksDescription + "\n\n" + TaskLinkQuerySchema.guidance + "\n\n" + readExecutionDescription             + "\n\n" + MCPPortfolioToolDefinitions.snapshotTaskQueryDescription,         inputSchema: JSONSchema(type: "object", properties: nil, required: nil, oneOf: [-            JSONSchema(type: "object", properties: queryTaskProperties,+            JSONSchema(type: "object",+                       properties: queryTaskProperties.merging(TaskLinkQuerySchema.properties) { _, new in new },                        required: ["detailLevel", "includeComments", "limit"], additionalProperties: false),             MCPPortfolioToolDefinitions.reusableContinuationSchema,             MCPPortfolioToolDefinitions.snapshotTaskQueryInitialSchema@@ -358,43 +359,4 @@ extension MCPToolDefinitions {         )) } -extension MCPToolDefinitions {-    nonisolated private static let writeSafetyContract = """-        Requires a case-sensitive idempotencyKey matching [A-Za-z0-9._:-]{1,128}. \-        Retried identical arguments replay the original saved outcome for seven days across local-store restarts; \-        JSON object order is ignored and different payloads return IDEMPOTENCY_KEY_REUSED. \-        Results are JSON committed/rejected/in_progress/uncertain envelopes with saved records and r1 revisions. \-        Replay expiry is fixed; after it a retry may execute again. Uncertain outcomes require reconciliation; \-        never retry them with a fresh key. Revisions compare exact locally observed content, remain stable for no-ops \-        and restored content, and cannot detect edits not yet imported from CloudKit or prevent later sync conflicts. \-        Read a task or milestone first, write with its expectedRevision and a fresh key, then retry identical \-        arguments \-        with that key after a timeout. REVISION_CONFLICT returns the currentRecord and no effect; use a new key after \-        reviewing it. Keys are scoped to this local store and tool, independently of connection/session/request ID. \-        Cross-device deduplication and atomic batches are not provided.-        """--    nonisolated private static func protected(_ definition: MCPToolDefinition) -> MCPToolDefinition {-        var properties = definition.inputSchema.properties ?? [:]-        var key = JSONSchemaProperty.string("Required retry key; UUID strings are suitable")-        key.pattern = "^[A-Za-z0-9._:-]{1,128}$"-        properties["idempotencyKey"] = key-        var required = definition.inputSchema.required ?? []-        required.append("idempotencyKey")-        if ["update_task", "update_task_status", "update_milestone", "delete_milestone"].contains(definition.name) {-            var revision = JSONSchemaProperty.string("Required target revision from the full read response")-            revision.pattern = "^r1:[0-9a-f]{64}$"-            properties["expectedRevision"] = revision-            required.append("expectedRevision")-        }-        var schema = JSONSchema.object(properties: properties, required: required)-        schema.additionalProperties = false-        return MCPToolDefinition(-            name: definition.name,-            description: definition.description + " " + writeSafetyContract,-            inputSchema: schema)-    }--}- #endif
Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift Changed +43 / -252
diff --git a/Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift b/Transit/Transit/MCP/MCPToolHandler+TaskQuery.swiftindex be20b2f4..0688bcda 100644--- a/Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift+++ b/Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift@@ -1,5 +1,6 @@ #if os(macOS) import Foundation+import SwiftData  extension MCPToolHandler {     func handleQueryTasks(_ args: [String: Any]) -> MCPToolResult {@@ -29,106 +30,50 @@ extension MCPToolHandler {     }      private func queryResults(_ request: MCPTaskQueryRequest, args: [String: Any]) throws -> [[String: Any]] {-        let formatter = ISO8601DateFormatter()-        switch request.selector {-        case .taskIDs, .displayIDs:-            return try batchQueryResults(request, formatter: formatter)-        case .list, .single:-            guard let filters = try taskQueryFilters(args) else { return [] }-            let tasks: [TransitTask]-            switch request.selector {-            case .single(let displayId):-                do {-                    tasks = [try taskService.findByDisplayID(displayId)]-                } catch TaskService.Error.taskNotFound {-                    return []-                } catch TaskService.Error.duplicateDisplayID {-                    throw MCPTaskQueryError(code: "AMBIGUOUS_TASK_ID",-                                            message: duplicateTaskIdentifierMessage(displayId: displayId))-                } catch {-                    throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Lookup failed: \(error)")-                }-            default:-                do { tasks = try taskFetcher.fetchAllTasks() } catch {-                    throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Failed to fetch tasks: \(error)")+        let budget = TaskLinkGraphBudget()+        let capture = fallbackTaskCapture(request, args: args, budget: budget)+        let view = try MCPReadCaptureBuilder(container: taskService.savedReadContainer).capture(capture)+        let records = try MCPReadProjection.tasks(view, request: request, arguments: args, budget: budget)+        if request.detailLevel == "full" || request.includeComments {+            var checked: Set<UUID> = []+            for value in records {+                try budget.check()+                let record = value["task"] as? [String: Any] ?? value+                if let raw = record["taskId"] as? String, let id = UUID(uuidString: raw), checked.insert(id).inserted {+                    do { _ = try commentFetcher.fetchComments(for: id) } catch {+                        throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Failed to fetch comments: \(error)")+                    }                 }             }-            return try tasks.filter { filters.matches($0) }.sorted { $0.id.uuidString < $1.id.uuidString }-                .map { try queryTaskDictionary($0, request: request, formatter: formatter) }         }+        return records     } -    private func batchQueryResults(-        _ request: MCPTaskQueryRequest, formatter: ISO8601DateFormatter-    ) throws -> [[String: Any]] {-        let tasks: [TransitTask]-        do { tasks = try taskFetcher.fetchAllTasks() } catch {-            throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Failed to fetch tasks: \(error)")-        }-        let inputs: [(requested: [String: Any], key: String)]-        let index: [String: [TransitTask]]-        switch request.selector {-        case .taskIDs(let ids):-            inputs = ids.map { (["taskId": $0], UUID(uuidString: $0)!.uuidString) }-            index = Dictionary(grouping: tasks) { $0.id.uuidString }-        case .displayIDs(let ids):-            inputs = ids.map { (["displayId": $0], String($0)) }-            index = Dictionary(grouping: tasks.filter { $0.permanentDisplayId != nil }) {-                String($0.permanentDisplayId!)-            }-        default: return []-        }-        var serialized: [UUID: [String: Any]] = [:]-        return try inputs.enumerated().map { position, input in-            var outcome: [String: Any] = ["index": position, "requested": input.requested]-            let matches = index[input.key] ?? []-            if matches.count == 1, let task = matches.first {-                if serialized[task.id] == nil {-                    serialized[task.id] = try queryTaskDictionary(task, request: request, formatter: formatter)+    private func fallbackTaskCapture(_ request: MCPTaskQueryRequest, args: [String: Any],+                                     budget: TaskLinkGraphBudget) -> ReadCaptureRequest {+        let state = LegacyTaskQueryValidation()+        let fields = args.mapValues(AnyCodable.init)+        return ReadCaptureRequest(projectSelectors: nil,+            selection: .tasks(detail: request.detailLevel == "full" ? .fullRecord : .summary),+            completeness: .selectedRead, includeComments: request.includeComments,+            validateProjects: { [self] projects in+                let args = fields.mapValues(\.value)+                _ = try MCPReadProjection.projectSelector(args)+                try checkTaskQueryProjectStorage(args)+                state.project = try MCPReadProjection.projectIdentity(args, projects: projects)+                try MCPReadProjection.validateTaskScalars(args)+            }, validateMilestones: { [self] milestones in+                let args = fields.mapValues(\.value)+                try checkTaskQueryMilestoneStorage(args, project: state.project)+                state.filters = try MCPReadProjection.taskFilters(args, project: state.project, milestones: milestones)+                guard state.filters != nil else { return false }+                do { _ = try taskFetcher.fetchAllTasks() } catch {+                    throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Failed to fetch tasks: \(error)")                 }-                outcome["task"] = serialized[task.id]-            } else {-                let code = matches.isEmpty ? "TASK_NOT_FOUND" : "AMBIGUOUS_TASK_ID"-                let field = input.requested.keys.first ?? "identifier"-                let identifier = input.requested[field] ?? input.key-                let message = matches.isEmpty ? "No task matches \(field) \(identifier)"-                    : "Multiple tasks match \(field) \(identifier)"-                outcome["error"] = ["code": code, "message": message]-            }-            return outcome-        }-    }--    private func queryTaskDictionary(-        _ task: TransitTask, request: MCPTaskQueryRequest, formatter: ISO8601DateFormatter-    ) throws -> [String: Any] {-        let full = request.detailLevel == "full"-        var comments: [Comment] = []-        if full || request.includeComments {-            do { comments = try commentFetcher.fetchComments(for: task.id) } catch {-                throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Failed to fetch comments: \(error)")-            }-        }-        if full {-            let snapshot = try MCPRecordSnapshot.task(task) { _ in comments }-            var record = snapshot.record-            if !request.includeComments { record.removeValue(forKey: "comments") }-            if let metadata = record["metadata"] as? [String: String], metadata.isEmpty {-                record.removeValue(forKey: "metadata")-            }-            return record-        }-        var dict = IntentHelpers.taskToDict(task, formatter: formatter)-        if request.includeComments {-            dict["comments"] = comments.sorted {-                if $0.creationDate == $1.creationDate { return $0.id.uuidString < $1.id.uuidString }-                return $0.creationDate < $1.creationDate-            }.map { [-                "id": $0.id.uuidString, "authorName": $0.authorName, "content": $0.content,-                "isAgent": $0.isAgent, "creationDate": formatter.string(from: $0.creationDate)-            ] as [String: Any] }-        }-        return dict+                return true+            }, selectTaskBodies: { values in+                try MCPReadProjection.taskBodyKeys(values, request: request, filters: state.filters)+            }, taskLinkBudget: budget, taskLinkOptions: request.graphOptions)     }      func encodeQueryPages(@@ -157,164 +102,10 @@ extension MCPToolHandler {         return pages[0]     } -    private func projectQueryError(_ error: ProjectLookupError) -> MCPTaskQueryError {-        let code: String-        switch error {-        case .storageFailure: code = "QUERY_FAILED"-        case .ambiguous: code = "AMBIGUOUS_FILTER"-        default: code = "INVALID_INPUT"-        }-        return MCPTaskQueryError(code: code, message: IntentHelpers.mapProjectLookupError(error).hint)-    }--    // Preserve the established validation order and filter precedence.-    // swiftlint:disable:next cyclomatic_complexity function_body_length-    private func taskQueryFilters(_ args: [String: Any]) throws -> MCPQueryFilters? {-        // Reject malformed or non-string projectId when the key is present-        // [T-665, T-788].-        let parsedProjectId: UUID?-        switch parseProjectIdArgument(args) {-        case .failure(.message(let message)): throw MCPTaskQueryError.invalid(message)-        case .success(let parsed): parsedProjectId = parsed-        }-        // Reject non-string `project` filter [T-1116].-        if args["project"] != nil, !(args["project"] is String) {-            throw MCPTaskQueryError.invalid("project must be a string")-        }-        // Resolve a valid project ID to an existing project before filtering [T-1783].-        var projectFilter: UUID?-        var resolvedProject: Project?-        if let pid = parsedProjectId {-            // A valid UUID is still an invalid project filter when no matching-            // project exists. Resolve it before applying the in-memory filter so-            // MCP matches the project-name and QueryTasksIntent contracts.-            switch projectService.findProject(id: pid) {-            case .success(let found):-                resolvedProject = found-                projectFilter = found.id-            case .failure(let err): throw projectQueryError(err)-            }-        } else if let name = args["project"] as? String,-                  !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {-            switch projectService.findProject(id: nil, name: name) {-            case .success(let found):-                resolvedProject = found-                projectFilter = found.id-            case .failure(let err): throw projectQueryError(err)-            }-        }--        // Validate every remaining filter before resolving a milestone. A no-match or-        // storage failure must not let a malformed filter look like a valid empty result.-        // This also preserves validation when displayId would otherwise return early. [T-1608]-        // Reject non-integer milestoneDisplayId when key is present [T-613].-        if args["milestoneDisplayId"] != nil, IntentHelpers.parseIntValue(args["milestoneDisplayId"]) == nil {-            throw MCPTaskQueryError.invalid("milestoneDisplayId must be an integer")-        }-        // Reject non-string `milestone` name filter [T-1266]. Without this guard a-        // numeric/boolean/array milestone falls through the `as? String` cast below-        // to the "no milestone filter" branch, returning every task unfiltered.-        if args["milestone"] != nil, !(args["milestone"] is String) {-            throw MCPTaskQueryError.invalid("milestone must be a string")-        }-        // Validate enum filters before building MCPQueryFilters [T-732].-        if let error = validateEnumFilter(args, key: "status", type: TaskStatus.self) {-            throw MCPTaskQueryError.invalid(error.content.first?.text ?? "Invalid filter")-        }-        if let error = validateEnumFilter(args, key: "not_status", type: TaskStatus.self) {-            throw MCPTaskQueryError.invalid(error.content.first?.text ?? "Invalid filter")-        }-        // type is a single-value filter (schema declares a string enum; read back as-        // args["type"] as? String). Reject arrays so they aren't silently dropped. [T-1404]-        if let error = validateEnumFilter(args, key: "type", type: TaskType.self, allowArray: false) {-            throw MCPTaskQueryError.invalid(error.content.first?.text ?? "Invalid filter")-        }-        // priority is a multi-value filter (schema declares an array, mirroring status).-        if let error = validateEnumFilter(args, key: "priority", type: TaskPriority.self, allowArray: true) {-            throw MCPTaskQueryError.invalid(error.content.first?.text ?? "Invalid filter")-        }-        // Reject a present-but-non-boolean `unfinished` flag [T-1095]. A plain-        // `as? Bool` would silently coerce "true"/1/null to false, returning-        // done/abandoned tasks even though the caller requested unfinished-only.-        if let unfinishedArg = args["unfinished"], IntentHelpers.parseBoolValue(unfinishedArg) == nil {-            throw MCPTaskQueryError.invalid("unfinished must be a boolean")-        }-        // Reject non-string `search` filter [T-1156]. A present non-string value must not be-        // silently dropped by `as? String`, which would broaden results instead of erroring.-        if args["search"] != nil, !(args["search"] is String) {-            throw MCPTaskQueryError.invalid("search must be a string")-        }-        // Reject non-integer displayId before a milestone no-match or failure can return early [T-634].-        if args["displayId"] != nil, IntentHelpers.parseIntValue(args["displayId"]) == nil {-            throw MCPTaskQueryError.invalid("displayId must be an integer")-        }--        // Resolve milestone filter.-        var milestoneFilter: Set<UUID>?-        if let milestoneDisplayId = IntentHelpers.parseIntValue(args["milestoneDisplayId"]) {-            do {-                milestoneFilter = [try milestoneDisplayIDFinder.findByDisplayID(milestoneDisplayId).id]-            } catch MilestoneService.Error.milestoneNotFound {-                return nil-            } catch MilestoneService.Error.duplicateDisplayID {-                throw MCPTaskQueryError(-                    code: "AMBIGUOUS_FILTER",-                    message: "Duplicate milestone identifier detected for displayId \(milestoneDisplayId)"-                )-            } catch {-                throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Failed to look up milestone: \(error)")-            }-        } else if let milestoneName = args["milestone"] as? String,-                  !milestoneName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {-            if let projectFilter {-                // Scoped to a single project — at most one milestone matches.-                guard let project = resolvedProject else {-                    return nil-                }-                do {-                    guard let milestone = try milestoneService.findByName(milestoneName, in: project) else {-                        return nil-                    }-                    milestoneFilter = [milestone.id]-                } catch MilestoneService.Error.ambiguousName {-                    throw MCPTaskQueryError(code: "AMBIGUOUS_FILTER", message:-                        "Multiple milestones named '\(milestoneName)' exist in project '\(project.name)'"-                    )-                } catch {-                    throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Failed to look up milestone: \(error)")-                }-            } else {-                // No project filter — collect ALL milestones with this name across projects.-                // A storage failure must remain distinct from a valid no-match response. [T-1608]-                let allMilestones: [Milestone]-                do {-                    allMilestones = try milestoneFetcher.fetchAllMilestones()-                } catch {-                    throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Failed to fetch milestones: \(error)")-                }-                let matchingIds = Set(-                    allMilestones-                        .filter {-                            MilestoneNamePolicy.normalized($0.name)-                                == MilestoneNamePolicy.normalized(milestoneName)-                        }-                        .map(\.id)-                )-                if matchingIds.isEmpty {-                    return nil-                }-                milestoneFilter = matchingIds-            }-        }--        let search = (args["search"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)-        let filters = MCPQueryFilters.from(-            args: args, type: args["type"] as? String, projectId: projectFilter,-            search: search?.isEmpty == true ? nil : search,-            milestoneIds: milestoneFilter-        )+} -        return filters-    }+@MainActor private final class LegacyTaskQueryValidation {+    var project: ReadProjectIdentity?+    var filters: MCPQueryFilters? } #endif
Transit/Transit/MCP/MCPToolHandler+TaskQueryFailureChecks.swift Changed +48 / -0
diff --git a/Transit/Transit/MCP/MCPToolHandler+TaskQueryFailureChecks.swift b/Transit/Transit/MCP/MCPToolHandler+TaskQueryFailureChecks.swiftnew file mode 100644index 00000000..b47ff7f8--- /dev/null+++ b/Transit/Transit/MCP/MCPToolHandler+TaskQueryFailureChecks.swift@@ -0,0 +1,48 @@+#if os(macOS)+import Foundation+import SwiftData++extension MCPToolHandler {+    /// Retain injected storage-error surfaces only. Successful live lookup+    /// values and semantic no-match/ambiguity outcomes never select saved rows.+    func checkTaskQueryProjectStorage(_ args: [String: Any]) throws {+        let result: Result<Project, ProjectLookupError>?+        if let raw = args["projectId"] as? String, let id = UUID(uuidString: raw) {+            result = projectService.findProject(id: id)+        } else if let name = args["project"] as? String, !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+            result = projectService.findProject(id: nil, name: name)+        } else { result = nil }+        if let result, case .failure(.storageFailure(let hint)) = result {+            throw MCPTaskQueryError(code: "QUERY_FAILED", message: hint)+        }+    }++    func checkTaskQueryMilestoneStorage(_ args: [String: Any], project: ReadProjectIdentity?) throws {+        if let id = IntentHelpers.parseIntValue(args["milestoneDisplayId"]) {+            do { _ = try milestoneDisplayIDFinder.findByDisplayID(id) } catch is MilestoneService.Error {+                // Saved projection owns identity and missing-record validation.+            } catch { throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Failed to look up milestone: \(error)") }+            return+        }+        guard let name = args["milestone"] as? String,+              !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }+        guard let id = project?.id else {+            do { _ = try milestoneFetcher.fetchAllMilestones() } catch {+                throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Failed to fetch milestones: \(error)")+            }+            return+        }+        let context = ModelContext(taskService.savedReadContainer)+        context.autosaveEnabled = false+        var descriptor = FetchDescriptor<Project>(predicate: #Predicate { $0.id == id })+        descriptor.includePendingChanges = false+        descriptor.fetchLimit = 2+        let matches = try context.fetch(descriptor)+        guard matches.count == 1, let project = matches.first else { return }+        do { _ = try milestoneService.findByName(name, in: project) } catch is MilestoneService.Error {+            // Discard hook's semantic outcomes; use the original saved capture.+        } catch { throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Failed to look up milestone: \(error)") }+    }++}+#endif
Transit/Transit/MCP/MCPToolHandler.swift Changed +9 / -2
diff --git a/Transit/Transit/MCP/MCPToolHandler.swift b/Transit/Transit/MCP/MCPToolHandler.swiftindex 1dd995b2..5748b59d 100644--- a/Transit/Transit/MCP/MCPToolHandler.swift+++ b/Transit/Transit/MCP/MCPToolHandler.swift@@ -29,6 +29,7 @@ final class MCPToolHandler {     private let writeCoordinator: MCPWriteCoordinator?      // Batch provider injection only; Task14 binds dispatch after real-route RED.+    let taskLinkWriteAdapter: TaskLinkWriteAdapter?     let batchContainer: ModelContainer?     let batchResultEncoder: MCPResultProviderSelection.EncodeOutcome? @@ -84,6 +85,7 @@ final class MCPToolHandler {         reusableSnapshots: MCPReusableSnapshotStore? = nil,         maintenanceReassignmentEncoder: (@Sendable (ReassignmentResult) throws -> String)? = nil,         batchContainer: ModelContainer? = nil,+        taskLinkWriteAdapter: TaskLinkWriteAdapter? = nil,         batchResultEncoder: MCPResultProviderSelection.EncodeOutcome? = nil     ) {         self.taskService = taskService@@ -115,6 +117,7 @@ final class MCPToolHandler {             return try MCPReusableSnapshotStore(domain: domain)         }         self.writeCoordinator = writeCoordinator+        self.taskLinkWriteAdapter = taskLinkWriteAdapter         self.batchContainer = batchContainer         self.batchResultEncoder = batchResultEncoder         self.maintenanceReassignmentEncoder = maintenanceReassignmentEncoder@@ -744,7 +747,9 @@ extension MCPToolHandler {         tool: String, arguments: [String: Any], batchPolicy: MCPBatchWritePolicy? = nil     ) async -> MCPToolResult {         if let writeCoordinator {-            return await writeCoordinator.execute(tool: tool, arguments: arguments, batchPolicy: batchPolicy)+            let covered = ["create_task", "update_task", "update_task_status", "add_comment"].contains(tool)+            let policy = batchPolicy ?? (covered ? taskLinkWriteAdapter?.policy() : nil)+            return await writeCoordinator.execute(tool: tool, arguments: arguments, batchPolicy: policy)         }         do {             let command = try MCPWriteCommand.validate(tool: tool, arguments: arguments)@@ -770,7 +775,9 @@ extension MCPToolHandler {      func executeBatchItem(_ item: MCPBatchTaskRequest.Item) async throws -> MCPBatchTaskCoordinator.Execution {         var pendingEditsStop = false-        let policy = MCPBatchWritePolicy(onPendingEditsStop: { pendingEditsStop = true })+        let stop: @MainActor () -> Void = { pendingEditsStop = true }+        let policy = taskLinkWriteAdapter?.policy(onPendingEditsStop: stop)+            ?? MCPBatchWritePolicy(onPendingEditsStop: stop)         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 {
Transit/Transit/MCP/MCPTypes.swift Changed +4 / -2
diff --git a/Transit/Transit/MCP/MCPTypes.swift b/Transit/Transit/MCP/MCPTypes.swiftindex fcc769f5..3ab6068e 100644--- a/Transit/Transit/MCP/MCPTypes.swift+++ b/Transit/Transit/MCP/MCPTypes.swift@@ -232,9 +232,10 @@ nonisolated struct JSONSchema: Encodable, Sendable { nonisolated struct JSONSchemaItems: Encodable, Sendable {     let type: String?     let enumValues: [String]?+    var oneOf: [JSONSchema]?      nonisolated enum CodingKeys: String, CodingKey {-        case type+        case type, oneOf         case enumValues = "enum"     } }@@ -249,9 +250,10 @@ nonisolated struct JSONSchemaProperty: Encodable, Sendable {     var maximum: Int?     var const: Bool?     var defaultValue: String?+    var maxItems: Int?      nonisolated enum CodingKeys: String, CodingKey {-        case type, description, items, pattern, minimum, maximum, const+        case type, description, items, pattern, minimum, maximum, const, maxItems         case enumValues = "enum"         case defaultValue = "default"     }
Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swift Changed +43 / -38
diff --git a/Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swift b/Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swiftindex a5636696..33556c07 100644--- a/Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swift+++ b/Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swift@@ -71,28 +71,31 @@ final class MCPReadCaptureBuilder: MCPReadCaptureSource {         }         isCapturing = true         defer { isCapturing = false; keyCache.removeAll(keepingCapacity: false) }+        try request.taskLinkBudget?.check()         let initialGeneration = generation()         let before = try watermark()         let context = ModelContext(container)         context.autosaveEnabled = false-        let copied = try copy(request, in: context)+        let instant = ContinuousClock.now+        let evaluationInstant = Date()+        let copied = try copy(request, in: context, evaluationInstant: evaluationInstant)         let after = try watermark()         guard initialGeneration == generation(), before?.token == after?.token,               before?.storeIdentifier == after?.storeIdentifier else {             throw MCPReadCaptureError.incoherentCapture         }-        let instant = ContinuousClock.now         let view = CapturedReadView(             completeness: request.completeness, captureScope: copied.scope,-            metadata: metadata(Date(), MCPReadCaptureBoundary(+            metadata: metadata(evaluationInstant, MCPReadCaptureBoundary(                 historyStoreIdentifier: after?.storeIdentifier, generation: initialGeneration,                 stablePersistentHistory: fence == .persistentHistory)), createdAt: instant,             retentionDeadline: instant + .seconds(300), projects: copied.projects,-            tasks: copied.tasks, milestones: copied.milestones, comments: copied.comments)+            tasks: copied.tasks, milestones: copied.milestones, comments: copied.comments,+            taskLinkGraph: copied.taskLinkGraph)         if view.completeness == .completePortfolio { try MCPReadCaptureValidation.validateReusableCapture(view) }+        try request.taskLinkBudget?.check()         return view     }-     private func watermark() throws -> DefaultHistoryTransaction? {         guard fence == .persistentHistory else { return nil }         guard container.configurations.count == 1 else { throw MCPReadCaptureError.incoherentCapture }@@ -112,7 +115,9 @@ final class MCPReadCaptureBuilder: MCPReadCaptureSource {                   try context.fetchCount(FetchDescriptor<Milestone>()) == 0,                   try context.fetchCount(FetchDescriptor<Comment>()) == 0,                   try context.fetchCount(FetchDescriptor<SyncHeartbeat>()) == 0,-                  try context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0 else {+                  try context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0,+                  try context.fetchCount(FetchDescriptor<TaskLinkOccurrence>()) == 0,+                  try context.fetchCount(FetchDescriptor<TaskLinkRemovalEvidence>()) == 0 else {                 throw MCPReadCaptureError.incoherentCapture             }             return nil@@ -120,24 +125,26 @@ final class MCPReadCaptureBuilder: MCPReadCaptureSource {             throw MCPReadCaptureError.incoherentCapture         }     }-     private struct Copied {         let scope: ReadCaptureScope         let projects: [ReadProject]         let tasks: [ReadTask]         let milestones: [ReadMilestone]         let comments: [ReadCommentEvidence]+        let taskLinkGraph: TaskLinkGraphView?     }--    private func copy(_ request: ReadCaptureRequest, in context: ModelContext) throws -> Copied {+    private func copy(+        _ request: ReadCaptureRequest, in context: ModelContext, evaluationInstant: Date+    ) throws -> Copied {         do {             let projects = try context.fetch(FetchDescriptor<Project>())             try request.validateProjects?(projects.map { ReadProjectIdentity(id: $0.id, name: $0.name) })             let selected = try resolve(request.projectSelectors, projects: projects)             let selectedKeys = try Set(selected.map(key))             try afterProjects()-            let (allTasks, allMilestones) = try fetchEntities(request, in: context)-            let needsTasks = neededEntities(request.selection).0+            let entities = try fetchEntities(request, in: context)+            let (allTasks, allMilestones) = (entities.tasks, entities.milestones)+            let graph = try TaskLinkCaptureIntegration.graph(request, in: context, entities, at: evaluationInstant)             let tasks = try allTasks.filter { task in                 guard request.projectSelectors != nil else { return true }                 return try task.project.map { selectedKeys.contains(try key($0)) } ?? false@@ -146,7 +153,7 @@ final class MCPReadCaptureBuilder: MCPReadCaptureSource {                 guard request.projectSelectors != nil else { return true }                 return try milestone.project.map { selectedKeys.contains(try key($0)) } ?? false             }-            let bodyKeys = try request.selectTaskBodies?(tasks.map(taskSelectionValue)) ?? Set(tasks.map(key))+            let bodyKeys = try request.taskBodyKeys(tasks.map(taskSelectionValue), graph: graph)             let milestoneBodyKeys = try milestoneBodyKeys(request, all: allMilestones, scoped: milestones)             let bodyTasks = try tasks.filter { bodyKeys.contains(try key($0)) }             let full = fullRecordSelection(request.selection)@@ -154,7 +161,7 @@ final class MCPReadCaptureBuilder: MCPReadCaptureSource {                 throw MCPReadCaptureError.incoherentCapture             }             let comments = try commentEvidence(request, context: context, bodyTasks: bodyTasks,-                                               needed: needsTasks && (full || request.includeComments))+                                               needed: full || request.includeComments)             let includedComments = commentsForScope(comments, request: request, tasks: bodyTasks)             let commentIndex = try indexComments(includedComments)             // Freeze identity closure separately; it never changes the declared selected scope.@@ -164,15 +171,16 @@ final class MCPReadCaptureBuilder: MCPReadCaptureSource {             return try Copied(scope: scope, projects: projects.map(projectValue),                               tasks: copyTaskValues(request.completeness == .completePortfolio ? allTasks : tasks,                                   selectedKeys: bodyKeys, comments: commentIndex,-                                  full: full, includeComments: request.includeComments),+                                  full: full, includeComments: request.includeComments,+                                  graph: graph, budget: request.taskLinkBudget),                               milestones: (request.completeness == .completePortfolio                                   ? allMilestones : milestones).map {                                       try milestoneValue($0, canonical: milestoneBodyKeys.contains(try key($0)))                                   },-                              comments: includedComments.map(commentValue))+                              comments: includedComments.map(commentValue), taskLinkGraph: graph)         } catch let error as MCPTaskQueryError {             throw error-        } catch let error as MCPReadCaptureError {+        } catch let error where error is TaskLinkGraphError || error is MCPReadCaptureError {             throw error         } catch is MCPCanonicalJSON.Error {             throw MCPReadCaptureError.serializationFailure@@ -180,16 +188,6 @@ final class MCPReadCaptureBuilder: MCPReadCaptureSource {             throw MCPReadCaptureError.storageFailure         }     }--    private func neededEntities(_ selection: ReadCaptureSelection) -> (Bool, Bool) {-        switch selection {-        case .projects: (false, false)-        case .milestones: (false, true)-        case .projectCatalog: (true, true)-        case .tasks, .portfolio: (true, true)-        }-    }-     private func resolve(_ selectors: [ReadProjectSelector]?, projects: [Project]) throws -> [Project] {         guard let selectors else { return projects }         return try selectors.map { selector in@@ -204,7 +202,6 @@ final class MCPReadCaptureBuilder: MCPReadCaptureSource {             return match         }     }-     private func keyOrder(_ lhs: LocalRecordKey, _ rhs: LocalRecordKey) -> Bool {         lhs.encodedIdentifier.lexicographicallyPrecedes(rhs.encodedIdentifier)     }@@ -236,13 +233,18 @@ final class MCPReadCaptureBuilder: MCPReadCaptureSource {                                 selectedRecordJSON: json(MCPRecordSnapshot.comment(comment).record))     } +    // Explicit frozen graph evidence accompanies the existing task/comment projection controls.+    // swiftlint:disable:next function_parameter_count     private func taskValue(-        _ task: TransitTask, comments: TaskComments, full: Bool, includeComments: Bool, identityOnly: Bool+        _ task: TransitTask, comments: TaskComments, full: Bool, includeComments: Bool,+        identityOnly: Bool, graph: TaskLinkGraphView?     ) throws -> ReadTask {         let coveredComments = comments.canonical         let taskKey = try key(task)         let ownedComments = comments.owned-        let snapshot = full && !identityOnly ? try MCPRecordSnapshot.task(task) { _ in coveredComments } : nil+        let snapshot = full && !identityOnly+            ? try MCPRecordSnapshot.task(task, incidence: graph.map { $0.incidence[task.id, default: []] },+                                         budget: comments.budget) { _ in coveredComments } : nil         var noComments = snapshot?.record         noComments?.removeValue(forKey: "comments")         var selected = noComments ?? ["taskId": task.id.uuidString, "name": task.name,@@ -300,7 +302,8 @@ private extension MCPReadCaptureBuilder {                                  bodyTasks: [TransitTask], needed: Bool) throws -> [Comment] {         // A selected empty result needs no comments. Complete portfolio still requires         // the full orphan/comment diagnostic domain, including an empty task domain.-        guard needed, request.completeness == .completePortfolio || !bodyTasks.isEmpty else { return [] }+        guard request.selection.requiredEntities.0 && needed,+              request.completeness == .completePortfolio || !bodyTasks.isEmpty else { return [] }         return try fetchComments(context)     } @@ -332,16 +335,16 @@ private extension MCPReadCaptureBuilder {     }      func fetchEntities(_ request: ReadCaptureRequest, in context: ModelContext)-        throws -> ([TransitTask], [Milestone]) {-        let (needsTasks, needsMilestones) = neededEntities(request.selection)+        throws -> ReadCaptureFetchedEntities {+        let (needsTasks, needsMilestones) = request.selection.requiredEntities         let allMilestones = needsMilestones ? try fetchMilestones(context) : []         let needsTaskValues = try request.validateMilestones?(allMilestones.map {             milestoneIdentity($0)         }) ?? needsTasks         let allTasks = needsTasks && needsTaskValues ? try fetchTasks(context) : []-        return (allTasks, allMilestones)+        return ReadCaptureFetchedEntities(tasks: allTasks, milestones: allMilestones,+                                          tasksCaptured: needsTasks && needsTaskValues)     }-     func commentsForScope(_ comments: [Comment], request: ReadCaptureRequest, tasks: [TransitTask]) -> [Comment] {         if request.completeness == .completePortfolio && request.projectSelectors == nil { return comments }         let ids = Set(tasks.map(\.id))@@ -350,14 +353,16 @@ private extension MCPReadCaptureBuilder {         }     } +    // swiftlint:disable:next function_parameter_count     private func copyTaskValues(_ tasks: [TransitTask], selectedKeys: Set<LocalRecordKey>, comments: CommentIndex,-                                full: Bool, includeComments: Bool) throws -> [ReadTask] {+                                full: Bool, includeComments: Bool, graph: TaskLinkGraphView?,+                                budget: TaskLinkGraphBudget?) throws -> [ReadTask] {         try tasks.map { task in             let taskKey = try key(task)             return try taskValue(task, comments: TaskComments(canonical: comments.canonical[task.id] ?? [],-                                                            owned: comments.physical[taskKey] ?? []),+                                                            owned: comments.physical[taskKey] ?? [], budget: budget),                                  full: full, includeComments: includeComments,-                                 identityOnly: !selectedKeys.contains(taskKey))+                                 identityOnly: !selectedKeys.contains(taskKey), graph: graph)         }     } @@ -382,7 +387,7 @@ private extension MCPReadCaptureBuilder {     private struct TaskComments {         let canonical: [Comment]         let owned: [Comment]+        let budget: TaskLinkGraphBudget?     }- } #endif
Transit/Transit/MCP/Reads/MCPReadCaptureTypes.swift Changed +41 / -1
diff --git a/Transit/Transit/MCP/Reads/MCPReadCaptureTypes.swift b/Transit/Transit/MCP/Reads/MCPReadCaptureTypes.swiftindex 996dd72a..ab257ffc 100644--- a/Transit/Transit/MCP/Reads/MCPReadCaptureTypes.swift+++ b/Transit/Transit/MCP/Reads/MCPReadCaptureTypes.swift@@ -29,6 +29,25 @@ nonisolated struct CapturedReadView: Sendable {     let tasks: [ReadTask]     let milestones: [ReadMilestone]     let comments: [ReadCommentEvidence]+    /// Nil is explicit missing coverage for legacy/provider fixtures, never empty incidence.+    let taskLinkGraph: TaskLinkGraphView?++    // A capture retains one declared scope and its complete immutable value payload.+    init(completeness: CaptureCompleteness, captureScope: ReadCaptureScope, metadata: ReadCaptureMetadata,+         createdAt: ContinuousClock.Instant, retentionDeadline: ContinuousClock.Instant,+         projects: [ReadProject], tasks: [ReadTask], milestones: [ReadMilestone], comments: [ReadCommentEvidence],+         taskLinkGraph: TaskLinkGraphView? = nil) {+        self.completeness = completeness+        self.captureScope = captureScope+        self.metadata = metadata+        self.createdAt = createdAt+        self.retentionDeadline = retentionDeadline+        self.projects = projects+        self.tasks = tasks+        self.milestones = milestones+        self.comments = comments+        self.taskLinkGraph = taskLinkGraph+    } }  nonisolated struct ReadProject: Sendable {@@ -129,6 +148,14 @@ nonisolated enum ReadCaptureSelection: Sendable {     case tasks(detail: ReadTaskCaptureDetail)     /// Requires completePortfolio and full revision/comment identity evidence.     case portfolio++    var requiredEntities: (Bool, Bool) {+        switch self {+        case .projects: (false, false)+        case .milestones: (false, true)+        case .projectCatalog, .tasks, .portfolio: (true, true)+        }+    } }  nonisolated struct ReadProjectIdentity: Sendable {@@ -175,6 +202,8 @@ nonisolated struct ReadCaptureRequest: Sendable {     let completeness: CaptureCompleteness     /// Output preference only; fullRecord/portfolio still capture canonical comment coverage.     let includeComments: Bool+    let taskLinkBudget: TaskLinkGraphBudget?+    let taskLinkOptions: TaskLinkQueryOptions?     /// Runs inside the fence before dependent entity fetches; no relationship values escape.     let validateProjects: (@MainActor @Sendable ([ReadProjectIdentity]) throws -> Void)? @@ -190,16 +219,27 @@ nonisolated struct ReadCaptureRequest: Sendable {          validateProjects: (@MainActor @Sendable ([ReadProjectIdentity]) throws -> Void)? = nil,          validateMilestones: (@MainActor @Sendable ([ReadMilestoneIdentity]) throws -> Bool)? = nil,          selectTaskBodies: ReadTaskBodySelection? = nil,-         selectMilestoneBodies: ReadMilestoneBodySelection? = nil) {+         selectMilestoneBodies: ReadMilestoneBodySelection? = nil,+         taskLinkBudget: TaskLinkGraphBudget? = nil, taskLinkOptions: TaskLinkQueryOptions? = nil) {         self.projectSelectors = projectSelectors         self.selection = selection         self.completeness = completeness         self.includeComments = includeComments+        self.taskLinkBudget = taskLinkBudget+        self.taskLinkOptions = taskLinkOptions         self.validateProjects = validateProjects         self.validateMilestones = validateMilestones         self.selectTaskBodies = selectTaskBodies         self.selectMilestoneBodies = selectMilestoneBodies     }++    func withTaskLinkBudget(_ budget: TaskLinkGraphBudget) -> ReadCaptureRequest {+        ReadCaptureRequest(projectSelectors: projectSelectors, selection: selection, completeness: completeness,+            includeComments: includeComments, validateProjects: validateProjects,+            validateMilestones: validateMilestones,+            selectTaskBodies: selectTaskBodies, selectMilestoneBodies: selectMilestoneBodies, taskLinkBudget: budget,+            taskLinkOptions: taskLinkOptions)+    } }  /// Local fence evidence only. This is not proof that a particular CloudKit import became visible.
Transit/Transit/MCP/Reads/MCPReadProjection+ProjectSelector.swift Changed +21 / -0
diff --git a/Transit/Transit/MCP/Reads/MCPReadProjection+ProjectSelector.swift b/Transit/Transit/MCP/Reads/MCPReadProjection+ProjectSelector.swiftnew file mode 100644index 00000000..6059320f--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadProjection+ProjectSelector.swift@@ -0,0 +1,21 @@+#if os(macOS)+import Foundation++extension MCPReadProjection {+    static func projectSelector(_ args: [String: Any],+                                validateIgnoredName: Bool = true) throws -> (UUID?, String?) {+        let id: UUID?+        if let raw = args["projectId"] {+            guard let text = raw as? String, let parsed = UUID(uuidString: text) else {+                throw MCPTaskQueryError.invalid("Invalid projectId: expected a UUID string")+            }+            id = parsed+        } else { id = nil }+        if id == nil || validateIgnoredName, args["project"] != nil, !(args["project"] is String) {+            throw MCPTaskQueryError.invalid("project must be a string")+        }+        let name = (args["project"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)+        return (id, name)+    }+}+#endif
Transit/Transit/MCP/Reads/MCPReadProjection.swift Changed +20 / -19
diff --git a/Transit/Transit/MCP/Reads/MCPReadProjection.swift b/Transit/Transit/MCP/Reads/MCPReadProjection.swiftindex b49f0f08..79fe0c98 100644--- a/Transit/Transit/MCP/Reads/MCPReadProjection.swift+++ b/Transit/Transit/MCP/Reads/MCPReadProjection.swift@@ -4,24 +4,31 @@ import Foundation /// Pure projection of a saved value capture. No service lookup, fetch, save or publication. enum MCPReadProjection {     static func tasks(_ view: CapturedReadView, request: MCPTaskQueryRequest,-                      arguments: [String: Any]) throws -> [[String: Any]] {+                      arguments: [String: Any],+                      budget: TaskLinkGraphBudget = TaskLinkGraphBudget()) throws -> [[String: Any]] {         let available = scopedTasks(view)         switch request.selector {         case .taskIDs(let ids):             return try batch(view, request: request, inputs: ids.map {                 (["taskId": $0], UUID(uuidString: $0)!.uuidString)             },-                             index: Dictionary(grouping: available) { $0.id.uuidString })+                             index: Dictionary(grouping: available) { $0.id.uuidString }, budget: budget)         case .displayIDs(let ids):             return try batch(view, request: request, inputs: ids.map { (["displayId": $0], String($0)) },                 index: Dictionary(grouping: available.filter { $0.permanentDisplayId != nil }) {                     String($0.permanentDisplayId!)-                })+                }, budget: budget)         case .list, .single:             guard let filters = try filters(arguments, view: view) else { return [] }-            let keys = try taskBodyKeys(available.map(selectionValue), request: request, filters: filters)+            let selected = try taskBodyKeys(available.map(selectionValue), request: request, filters: filters)+            let keys = try Set(available.filter { task in+                try budget.check()+                guard selected.contains(task.physicalKey) else { return false }+                return try request.graphOptions?.matches(task.id, graph: view.taskLinkGraph, budget: budget) ?? true+            }.map(\.physicalKey))             return try available.filter { keys.contains($0.physicalKey) }-                .sorted { $0.id.uuidString < $1.id.uuidString }.map { try task($0, view: view, request: request) }+                .sorted { $0.id.uuidString < $1.id.uuidString }+                .map { try task($0, view: view, request: request, budget: budget) }         }     } @@ -33,14 +40,15 @@ enum MCPReadProjection {      private static func batch(_ view: CapturedReadView, request: MCPTaskQueryRequest,                               inputs: [(requested: [String: Any], key: String)],-                              index: [String: [ReadTask]]) throws -> [[String: Any]] {+                              index: [String: [ReadTask]], budget: TaskLinkGraphBudget) throws -> [[String: Any]] {         var serialized: [LocalRecordKey: [String: Any]] = [:]         return try inputs.enumerated().map { position, input in+            try budget.check()             var outcome: [String: Any] = ["index": position, "requested": input.requested]             let matches = index[input.key] ?? []             if matches.count == 1, let record = matches.first {                 if serialized[record.physicalKey] == nil {-                    serialized[record.physicalKey] = try task(record, view: view, request: request)+                    serialized[record.physicalKey] = try task(record, view: view, request: request, budget: budget)                 }                 outcome["task"] = serialized[record.physicalKey]             } else {@@ -55,7 +63,8 @@ enum MCPReadProjection {     }      static func task(_ task: ReadTask, view: CapturedReadView,-                     request: MCPTaskQueryRequest) throws -> [String: Any] {+                     request: MCPTaskQueryRequest,+                     budget: TaskLinkGraphBudget = TaskLinkGraphBudget()) throws -> [String: Any] {         if request.detailLevel == "full" {             guard task.revision != nil, let bytes = task.fullRecordWithoutCommentsJSON else {                 throw MCPReadCaptureError.incoherentCapture@@ -68,6 +77,8 @@ enum MCPReadProjection {                 }                 record["comments"] = try JSONSerialization.jsonObject(with: comments)             }+            let detail = try TaskLinkQueryProjection.detail(task.id, graph: view.taskLinkGraph, budget: budget)+            record.merge(detail) { _, new in new }             if (record["metadata"] as? [String: String])?.isEmpty == true { record.removeValue(forKey: "metadata") }             return record         }@@ -114,17 +125,7 @@ enum MCPReadProjection {      static func projectIdentity(_ args: [String: Any], projects: [ReadProjectIdentity],                                 validateIgnoredName: Bool = true) throws -> ReadProjectIdentity? {-        let id: UUID?-        if let raw = args["projectId"] {-            guard let text = raw as? String, let parsed = UUID(uuidString: text) else {-                throw MCPTaskQueryError.invalid("Invalid projectId: expected a UUID string")-            }-            id = parsed-        } else { id = nil }-        if id == nil || validateIgnoredName, args["project"] != nil, !(args["project"] is String) {-            throw MCPTaskQueryError.invalid("project must be a string")-        }-        let name = (args["project"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)+        let (id, name) = try projectSelector(args, validateIgnoredName: validateIgnoredName)         guard id != nil || name?.isEmpty == false else { return nil }         let matches = projects.filter {             if let id { return $0.id == id }
Transit/Transit/MCP/Reads/MCPReadService+CaptureRequest.swift Changed +1 / -1
diff --git a/Transit/Transit/MCP/Reads/MCPReadService+CaptureRequest.swift b/Transit/Transit/MCP/Reads/MCPReadService+CaptureRequest.swiftindex b6e6fdec..53be8eaf 100644--- a/Transit/Transit/MCP/Reads/MCPReadService+CaptureRequest.swift+++ b/Transit/Transit/MCP/Reads/MCPReadService+CaptureRequest.swift@@ -47,7 +47,7 @@ extension MCPReadService {                     guard tool == "query_milestones" else { return [] }                     return try MCPReadProjection.milestoneBodyKeys(values, arguments: fields.mapValues(\.value),                         projectID: state.project?.id)-                })+                }, taskLinkOptions: query?.graphOptions)     }      private final class ValidationState {
Transit/Transit/MCP/Reads/MCPReadService.swift Changed +11 / -5
diff --git a/Transit/Transit/MCP/Reads/MCPReadService.swift b/Transit/Transit/MCP/Reads/MCPReadService.swiftindex 22b13afd..23d96b3a 100644--- a/Transit/Transit/MCP/Reads/MCPReadService.swift+++ b/Transit/Transit/MCP/Reads/MCPReadService.swift@@ -105,7 +105,9 @@ final class MCPReadService: MCPReadCapturedPreparing {         let captured = capsule.view         let results: [[String: Any]]         if let query {-            results = try MCPReadProjection.tasks(captured, request: query, arguments: arguments)+            results = try MCPReadProjection.tasks(captured, request: query, arguments: arguments,+                budget: TaskLinkGraphBudget(deadline: try MCPPortfolioReadEncoding.publicationDeadline(operation),+                    checkpoint: { try MCPPortfolioReadEncoding.check(operation) }))         } else {             let checkpoint = {                 guard operation.shouldContinue() else { throw ReadExecutionError.timeout }@@ -170,7 +172,11 @@ final class MCPReadService: MCPReadCapturedPreparing {         guard operation.shouldContinue() else { throw ReadExecutionError.timeout }         let captureStarted = ContinuousClock.now         let view: CapturedReadView-        do { view = try source.capture(request) } catch {+        let cutoff = try MCPPortfolioReadEncoding.publicationDeadline(operation)+        let coveredRequest = request.withTaskLinkBudget(TaskLinkGraphBudget(deadline: cutoff, checkpoint: {+            try MCPPortfolioReadEncoding.check(operation)+        }))+        do { view = try source.capture(coveredRequest) } catch {             operation.recordDiagnostic(.capture, startedAt: captureStarted, outcome: .failure)             throw error         }@@ -187,7 +193,7 @@ final class MCPReadService: MCPReadCapturedPreparing {             freshness: freshness, read: ReadExecutionMetadata(policy: policy, refreshOutcome: outcome, budgetMs: 5_000))         return CapturedReadView(completeness: view.completeness, captureScope: view.captureScope, metadata: metadata,             createdAt: view.createdAt, retentionDeadline: view.retentionDeadline, projects: view.projects,-            tasks: view.tasks, milestones: view.milestones, comments: view.comments)+            tasks: view.tasks, milestones: view.milestones, comments: view.comments, taskLinkGraph: view.taskLinkGraph)     }      func jsonText(_ value: Any) throws -> String {@@ -212,12 +218,12 @@ final class MCPReadService: MCPReadCapturedPreparing {             category = .incoherentCapture; code = failureCode; message = "Saved capture could not be proved coherent"         case MCPReadCaptureError.serializationFailure:             category = .serializationFailure; code = failureCode; message = "Read serialization failed"-        case MCPResultPreparationError.retentionCapacity:+        case MCPResultPreparationError.retentionCapacity, TaskLinkGraphError.capacityExceeded:             category = nil; code = "QUERY_CAPACITY_EXCEEDED"             message = "Query capacity exceeded; reduce scope/comments or retry after expiry"         case PublicationRejection.busy:             category = .busy; code = "READ_BUSY"; message = "Read publication changed; retry the request"-        case ReadExecutionError.timeout:+        case ReadExecutionError.timeout, TaskLinkGraphError.deadlineExceeded:             category = .timeout; code = "READ_TIMEOUT"; message = "Read exceeded its original admission budget"         default:             category = .storageFailure; code = failureCode; message = "Saved read storage failed"
Transit/Transit/MCP/Reads/TaskLinkCaptureIntegration.swift Changed +41 / -0
diff --git a/Transit/Transit/MCP/Reads/TaskLinkCaptureIntegration.swift b/Transit/Transit/MCP/Reads/TaskLinkCaptureIntegration.swiftnew file mode 100644index 00000000..0066e626--- /dev/null+++ b/Transit/Transit/MCP/Reads/TaskLinkCaptureIntegration.swift@@ -0,0 +1,41 @@+#if os(macOS)+import Foundation+import SwiftData++@MainActor struct ReadCaptureFetchedEntities {+    let tasks: [TransitTask]+    let milestones: [Milestone]+    let tasksCaptured: Bool+}++@MainActor+enum TaskLinkCaptureIntegration {+    static func graph(+        _ request: ReadCaptureRequest, in context: ModelContext,+        _ entities: ReadCaptureFetchedEntities, at instant: Date+    ) throws -> TaskLinkGraphView? {+        switch request.selection {+        case .tasks, .portfolio:+            guard entities.tasksCaptured else { return nil }+            return try TaskLinkService.graph(in: context, capturedTasks: entities.tasks, evaluationInstant: instant,+                                             budget: request.taskLinkBudget ?? TaskLinkGraphBudget())+        case .projects, .projectCatalog, .milestones: return nil+        }+    }+}+extension ReadCaptureRequest {+    @MainActor+    func taskBodyKeys(_ values: [ReadTaskSelectionValue], graph: TaskLinkGraphView?) throws -> Set<LocalRecordKey> {+        let keys = try selectTaskBodies?(values) ?? Set(values.map(\.physicalKey))+        guard let options = taskLinkOptions else { return keys }+        let budget = taskLinkBudget ?? TaskLinkGraphBudget()+        return try Set(values.compactMap { task in+            try budget.check()+            guard keys.contains(task.physicalKey), try options.matches(task.id, graph: graph, budget: budget)+            else { return nil }+            return task.physicalKey+        })+    }++}+#endif
Transit/Transit/MCP/Results/MCPResultClassification.swift Changed +1 / -0
diff --git a/Transit/Transit/MCP/Results/MCPResultClassification.swift b/Transit/Transit/MCP/Results/MCPResultClassification.swiftindex 17c03249..6ae6b673 100644--- a/Transit/Transit/MCP/Results/MCPResultClassification.swift+++ b/Transit/Transit/MCP/Results/MCPResultClassification.swift@@ -88,6 +88,7 @@ nonisolated struct MCPResultClassification {         "AMBIGUOUS_MILESTONE": .ambiguousIdentity, "AMBIGUOUS_FILTER": .ambiguousIdentity,         "DUPLICATE_MILESTONE_NAME": .ambiguousIdentity, "DUPLICATE_PROJECT_NAME": .ambiguousIdentity,         "DUPLICATE_TASK_IDENTIFIER": .ambiguousIdentity, "MILESTONE_NOT_OPEN": .invalidInput,+        "LINK_REPAIR_UNAVAILABLE": .notFound, "LINK_GRAPH_INVALID": .invalidInput,         "REVISION_CONFLICT": .revisionConflict, "IDEMPOTENCY_KEY_REUSED": .keyConflict,         "PERSISTENCE_UNAVAILABLE": .storageFailure, "QUERY_FAILED": .storageFailure,         "READ_BUSY": .admissionBusy, "QUERY_UNAVAILABLE": .admissionBusy,
Transit/Transit/MCP/TaskLinkWireSchema.swift Changed +64 / -0
diff --git a/Transit/Transit/MCP/TaskLinkWireSchema.swift b/Transit/Transit/MCP/TaskLinkWireSchema.swiftnew file mode 100644index 00000000..52ee573a--- /dev/null+++ b/Transit/Transit/MCP/TaskLinkWireSchema.swift@@ -0,0 +1,64 @@+#if os(macOS)+import Foundation++nonisolated enum TaskLinkWireSchema {+    static let description = """+        Standalone task links accept at most 50 linkChanges directives. Add with action:add, exact type \+        blocks/blocked-by/relates-to/introduced-by/duplicate-of and targetTaskId UUID; remove with action:remove, \+        edgeId UUID and occurrenceRevision l1 token. Creation permits additions only. Endpoint preconditions are \+        unique taskId/expectedRevision r1 pairs for precisely other existing endpoints whose incidence changes; \+        no extra/source guards. Update always requires the source revision, including already-present no-ops. \+        Omission leaves links unchanged. Exact removal evidence permits original-selector no-op for seven days; \+        after expiry repair is unavailable. Same logical remove/add requires separate requests; duplicate retarget \+        may remove the old target and add a different target. Directions: blocks is outgoing dependency; blocked-by \+        incoming; relates-to symmetric; introduced-by and duplicate-of point from source to target. No redirection, \+        merge, status change or imported-writer fence. Only participating local coordinator writes share the owned \+        save; CloudKit imports and independent writers can later invalidate graph evidence. mutate_tasks \+        rejects linkChanges and endpointPreconditions before item acceptance.+        """++    static func changes(creating: Bool) -> JSONSchemaProperty {+        let add = closed(["action": .stringEnum("Add an occurrence", values: ["add"]),+                          "type": .stringEnum("Exact public relationship type",+                                              values: TaskLinkType.allCases.map(\.rawValue)),+                          "targetTaskId": uuid("Unambiguous saved target UUID")])+        let remove = closed(["action": .stringEnum("Remove an exact incident occurrence", values: ["remove"]),+                             "edgeId": uuid("Unique physical occurrence UUID"),+                             "occurrenceRevision": token("Exact immutable occurrence token", prefix: "l1")])+        let items = JSONSchemaItems(type: "object", enumValues: nil,+                                   oneOf: creating ? [add] : [add, remove])+        var property = JSONSchemaProperty(type: "array", description: description, enumValues: nil, items: items)+        property.maxItems = 50+        return property+    }++    static var endpoints: JSONSchemaProperty {+        let shape = closed(["taskId": uuid("Other existing affected endpoint UUID"),+                            "expectedRevision": token("Current graph-covered task token", prefix: "r1")])+        let items = JSONSchemaItems(type: "object", enumValues: nil, oneOf: [shape])+        var property = JSONSchemaProperty(type: "array",+                                          description: "Precisely other affected endpoints; no duplicates",+                                          enumValues: nil, items: items)+        property.maxItems = 50+        return property+    }++    private static func closed(_ properties: [String: JSONSchemaProperty]) -> JSONSchema {+        var schema = JSONSchema.object(properties: properties, required: properties.keys.sorted())+        schema.additionalProperties = false+        return schema+    }++    private static func uuid(_ description: String) -> JSONSchemaProperty {+        var field = JSONSchemaProperty.string(description)+        field.pattern = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"+        return field+    }++    private static func token(_ description: String, prefix: String) -> JSONSchemaProperty {+        var field = JSONSchemaProperty.string(description)+        field.pattern = "^" + prefix + ":[0-9a-f]{64}$"+        return field+    }+}+#endif
Transit/Transit/MCP/Writes/MCPRecordSnapshot.swift Changed +12 / -3
diff --git a/Transit/Transit/MCP/Writes/MCPRecordSnapshot.swift b/Transit/Transit/MCP/Writes/MCPRecordSnapshot.swiftindex dcfbbd7c..2efda89e 100644--- a/Transit/Transit/MCP/Writes/MCPRecordSnapshot.swift+++ b/Transit/Transit/MCP/Writes/MCPRecordSnapshot.swift@@ -73,14 +73,17 @@ struct MCPRecordSnapshot {     }      static func task(_ task: TransitTask, in context: ModelContext) throws -> Self {-        try Self.task(task) { try context.fetch(CommentService.descriptor(for: $0)) }+        try Self.task(task, incidence: TaskLinkIncidence.capture(task.id, in: context)) {+            try context.fetch(CommentService.descriptor(for: $0))+        }     } -    static func task(_ task: TransitTask, fetchComments: (UUID) throws -> [Comment]) throws -> Self {+    static func task(_ task: TransitTask, incidence: [TaskLinkOccurrenceValue]?,+                     budget: TaskLinkGraphBudget? = nil, fetchComments: (UUID) throws -> [Comment]) throws -> Self {         let comments = try fetchComments(task.id).sorted {             ($0.creationDate, $0.id.uuidString) < ($1.creationDate, $1.id.uuidString)         }.map { try Self.comment($0) }-        let fields: [String: Any] = [+        var fields: [String: Any] = [             "id": MCPRecordRevision.uuid(task.id), "name": task.name,             "taskDescription": task.taskDescription as Any? ?? NSNull(),             "permanentDisplayId": task.permanentDisplayId as Any? ?? NSNull(),@@ -94,6 +97,10 @@ struct MCPRecordSnapshot {             "milestoneId": MCPRecordRevision.uuid(task.milestone?.id),             "comments": comments.sorted { $0.entityID.uuidString < $1.entityID.uuidString }.map(\.coveredFields)         ]+        if let incidence {+            fields["linkContract"] = "task-links-v1"+            fields["incidentLinks"] = try TaskLinkIncidence.canonical(incidence, incidentTo: task.id, budget: budget)+        }         var record: [String: Any] = [             "taskId": task.id.uuidString, "name": task.name, "status": task.statusRawValue,             "type": task.typeRawValue, "priority": task.priority.rawValue,@@ -102,6 +109,8 @@ struct MCPRecordSnapshot {             "description": task.taskDescription as Any? ?? NSNull(), "metadata": task.metadata,             "comments": comments.map(\.record)         ]+        record["graphCoverage"] = incidence == nil ? "unavailable" : "available"+        record["revisionCoverage"] = incidence == nil ? "task-fields-comments-v1" : "task-fields-comments-links-v1"         record["displayId"] = task.permanentDisplayId         record["projectId"] = task.project?.id.uuidString         record["projectName"] = task.project?.name
Transit/Transit/MCP/Writes/MCPWriteCommand.swift Changed +22 / -11
diff --git a/Transit/Transit/MCP/Writes/MCPWriteCommand.swift b/Transit/Transit/MCP/Writes/MCPWriteCommand.swiftindex 12268c7f..04a8ffea 100644--- a/Transit/Transit/MCP/Writes/MCPWriteCommand.swift+++ b/Transit/Transit/MCP/Writes/MCPWriteCommand.swift@@ -12,7 +12,7 @@ struct MCPWriteCommandServices { }  enum PreparedMCPWrite {-    case taskCreation(TaskService.PreparedCreation)+    case taskCreation(TaskService.PreparedCreation, UUID)     case milestoneCreation(MilestoneService.PreparedCreation)     case task(UUID)     case milestone(UUID)@@ -20,6 +20,8 @@ enum PreparedMCPWrite { }  struct MCPWriteCommand {+    typealias AfterTaskApply = @MainActor (MCPWriteCommand, TransitTask, MCPWriteCommandServices) throws -> Void+     static let protectedTools: Set<String> = [         "create_task", "create_project", "create_milestone", "add_comment",         "update_task", "update_task_status", "update_milestone", "delete_milestone"@@ -30,6 +32,7 @@ struct MCPWriteCommand {     let tool: String     let key: String     let arguments: [String: Any]+    var hasLinkInput: Bool { arguments["linkChanges"] != nil || arguments["endpointPreconditions"] != nil }     var expectedRevision: String? { arguments["expectedRevision"] as? String }      static func validate(tool: String, arguments: [String: Any]) throws -> Self {@@ -50,7 +53,7 @@ struct MCPWriteCommand {         }         let usesProjectID = ["create_task", "create_milestone"].contains(tool)             && (arguments["projectId"] as? String).flatMap(UUID.init(uuidString:)) != nil-        for (field, value) in arguments where !safetyFields.contains(field) {+        for (field, value) in arguments where !safetyFields.union(TaskLinkWireRequest.fields).contains(field) {             if field == "project", usesProjectID { continue }             try validateValue(value, field: field, schema: properties[field]!)         }@@ -72,6 +75,7 @@ struct MCPWriteCommand {                 throw MCPWriteFailure("INVALID_INPUT", "\(field) must be a valid UUID string")             }         }+        _ = try TaskLinkWireRequest.parse(tool: tool, arguments: arguments)         return Self(tool: tool, key: key, arguments: arguments)     } @@ -93,7 +97,8 @@ struct MCPWriteCommand {         }     } -    func prepare(using services: MCPWriteCommandServices) async throws -> PreparedMCPWrite {+    func prepare(using services: MCPWriteCommandServices,+                 newTaskID: @MainActor () -> UUID = UUID.init) async throws -> PreparedMCPWrite {         try Task.checkCancellation()         switch tool {         case "create_task":@@ -103,12 +108,12 @@ struct MCPWriteCommand {             }             let priority = try taskPriority()             let milestone = try assignedMilestone(project: project, using: services)-            return .taskCreation(-                try await services.tasks.prepareTaskCreation(+            let creation = try await services.tasks.prepareTaskCreation(                     name: try string("name"), description: arguments["description"] as? String,                     type: type, project: project, metadata: IntentHelpers.stringMetadata(from: arguments["metadata"]),                     priority: priority, milestone: milestone-                ))+                )+            return .taskCreation(creation, newTaskID())         case "create_milestone":             return .milestoneCreation(                 try await services.milestones.prepareMilestoneCreation(@@ -128,11 +133,13 @@ struct MCPWriteCommand {         }     } -    func apply(_ prepared: PreparedMCPWrite, using services: MCPWriteCommandServices) throws -> [String: Any] {+    func apply(_ prepared: PreparedMCPWrite, using services: MCPWriteCommandServices,+               afterTaskApply: AfterTaskApply? = nil) throws -> [String: Any] {         try Task.checkCancellation()         switch prepared {-        case .taskCreation(let creation):-            let task = try services.tasks.applyTaskCreation(creation)+        case .taskCreation(let creation, let id):+            let task = try services.tasks.applyTaskCreation(creation, taskID: id)+            try afterTaskApply?(self, task, services)             return try saved(MCPRecordSnapshot.task(task, in: services.context))         case .milestoneCreation(let creation):             let milestone = try services.milestones.applyMilestoneCreation(creation)@@ -149,12 +156,13 @@ struct MCPWriteCommand {                 gitRepo: arguments["gitRepo"] as? String, colorHex: raw, save: false             )             return try saved(MCPRecordSnapshot.project(project))-        case .task(let id): return try applyTask(id, using: services)+        case .task(let id): return try applyTask(id, using: services, afterTaskApply: afterTaskApply)         case .milestone(let id): return try applyMilestone(id, using: services)         }     } -    private func applyTask(_ id: UUID, using services: MCPWriteCommandServices) throws -> [String: Any] {+    private func applyTask(_ id: UUID, using services: MCPWriteCommandServices,+                           afterTaskApply: AfterTaskApply?) throws -> [String: Any] {         let task = try services.tasks.findByID(id)         if expectedRevision != nil { try check(MCPRecordSnapshot.task(task, in: services.context)) }         if tool == "add_comment" {@@ -162,6 +170,7 @@ struct MCPWriteCommand {                 to: task, content: try string("content"),                 authorName: try string("authorName"),                 isAgent: true, save: nil)+            try afterTaskApply?(self, task, services)             return try saved(MCPRecordSnapshot.comment(comment))         }         if tool == "update_task" {@@ -171,6 +180,7 @@ struct MCPWriteCommand {             try TaskUpdateValidator.apply(                 update, to: task, taskService: services.tasks,                 milestoneService: services.milestones)+            try afterTaskApply?(self, task, services)             return try saved(MCPRecordSnapshot.task(task, in: services.context))         }         let validation = try MCPTaskMutationValidation.status(@@ -184,6 +194,7 @@ struct MCPWriteCommand {             comment: arguments["comment"] as? String,             commentAuthor: arguments["authorName"] as? String,             commentService: services.comments, save: false)+        try afterTaskApply?(self, task, services)         var result = try saved(MCPRecordSnapshot.task(task, in: services.context))         result["comment"] = try comment.map { try MCPRecordSnapshot.comment($0).record } as Any? ?? NSNull()         return result
Transit/Transit/MCP/Writes/MCPWriteCommitServices.swift Changed +57 / -0
diff --git a/Transit/Transit/MCP/Writes/MCPWriteCommitServices.swift b/Transit/Transit/MCP/Writes/MCPWriteCommitServices.swiftnew file mode 100644index 00000000..435fcad2--- /dev/null+++ b/Transit/Transit/MCP/Writes/MCPWriteCommitServices.swift@@ -0,0 +1,57 @@+#if os(macOS)+import SwiftData++/// Sealed construction proves all four service contexts without exposing their+/// private context/fetcher fields or accepting arbitrary service instances.+@MainActor struct MCPWriteCommitServices {+    private let storedServices: MCPWriteCommandServices+    var context: ModelContext { storedServices.context }+    var services: MCPWriteCommandServices { storedServices }++    init(context: ModelContext, taskAllocator: DisplayIDAllocator, milestoneAllocator: DisplayIDAllocator) {+        storedServices = MCPWriteCommandServices(+            tasks: TaskService(modelContext: context, displayIDAllocator: taskAllocator),+            projects: ProjectService(modelContext: context), comments: CommentService(modelContext: context),+            milestones: MilestoneService(modelContext: context, displayIDAllocator: milestoneAllocator),+            context: context)+    }+}++/// Retained only for one synchronous validation/apply/result-save phase.+@MainActor struct MCPWriteCommitScope {+    let services: MCPWriteCommandServices+    let receipts: MCPWriteReceiptStore+    var context: ModelContext { services.context }++    init(shared: MCPWriteCommandServices, scopeID: String, policy: MCPBatchWritePolicy?) throws {+        if let factory = policy?.makeCommitServices {+            guard !shared.context.hasChanges else { throw MCPWriteFailure("OUTCOME_UNCERTAIN", "Pending UI edits") }+            let context = ModelContext(shared.context.container)+            context.autosaveEnabled = false+            let wrapper = try factory(context)+            guard wrapper.context === context, !context.hasChanges, !context.autosaveEnabled,+                  !shared.context.hasChanges else {+                throw MCPWriteFailure("OUTCOME_UNCERTAIN", "Unable to establish a clean owned commit scope")+            }+            services = wrapper.services+        } else {+            services = shared+        }+        receipts = MCPWriteReceiptStore(context: services.context, scopeID: scopeID)+    }++    func receipt(for guardRecord: MCPLocalReservation) throws -> MCPWriteReceipt {+        guard let receipt = try receipts.lookup(tool: guardRecord.tool, key: guardRecord.key),+              Self.matches(receipt, guardRecord: guardRecord) else {+            throw MCPWriteFailure("OUTCOME_UNCERTAIN", "Accepted receipt evidence is unavailable")+        }+        return receipt+    }++    static func matches(_ receipt: MCPWriteReceipt, guardRecord: MCPLocalReservation) -> Bool {+        receipt.id == guardRecord.receiptID && receipt.requestJSON == guardRecord.requestJSON+            && receipt.formatVersion == guardRecord.formatVersion && receipt.localScopeID == guardRecord.scopeID+            && receipt.tool == guardRecord.tool && receipt.key == guardRecord.key+    }+}+#endif
Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift Changed +92 / -33
diff --git a/Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift b/Transit/Transit/MCP/Writes/MCPWriteCoordinator.swiftindex 11931b16..bfa48da5 100644--- a/Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift+++ b/Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift@@ -1,4 +1,6 @@ #if os(macOS)+// Private retry state and its synchronous commit/recovery phases stay together.+// swiftlint:disable file_length import Foundation import SwiftData @@ -12,6 +14,7 @@ import SwiftData     private let clock: @MainActor () -> Date     private let save: @MainActor (ModelContext, SaveStage) throws -> Void     private let encode: @MainActor ([String: Any]) throws -> String+    private let newTaskID: @MainActor () -> UUID     private let preparationHook: @MainActor (MCPWriteCommand) async throws -> Void     private let recoveryHook: @MainActor () throws -> Void     private let persistence: PersistenceAvailability@@ -25,6 +28,7 @@ import SwiftData         clock: @escaping @MainActor () -> Date = Date.init,         save: @escaping @MainActor (ModelContext, SaveStage) throws -> Void = { context, _ in try context.save() },         encode: @escaping @MainActor ([String: Any]) throws -> String = MCPWriteOutcome.encode,+        newTaskID: @escaping @MainActor () -> UUID = UUID.init,         preparationHook: @escaping @MainActor (MCPWriteCommand) async throws -> Void = { _ in },         recoveryHook: @escaping @MainActor () throws -> Void = {}     ) {@@ -34,6 +38,7 @@ import SwiftData         self.clock = clock         self.save = save         self.encode = encode+        self.newTaskID = newTaskID         self.preparationHook = preparationHook         self.recoveryHook = recoveryHook         if persistence.isFallbackStorageActive {@@ -103,7 +108,7 @@ 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 {+        if (batchPolicy != nil || command.hasLinkInput) && services.context.hasChanges {             return inspectRetainedWhileDirty(                 command, payload: payload, reservations: reservations, receipts: receipts,                 now: clock(), batchPolicy: batchPolicy)@@ -117,14 +122,15 @@ import SwiftData extension MCPWriteCoordinator {     fileprivate func existingOutcome(         _ command: MCPWriteCommand, payload: String,-        reservations: MCPLocalReservationStore, receipts: MCPWriteReceiptStore+        reservations: MCPLocalReservationStore, receipts: MCPWriteReceiptStore,+        batchPolicy: MCPBatchWritePolicy?     ) -> MCPToolResult? {         let tool = command.tool         do {             if let guardRecord = try reservations.lookup(tool: tool, key: command.key) {                 if guardRecord.expiresAt.map({ $0 <= clock() }) != true {                     guard guardRecord.requestJSON == payload else { return reused(command) }-                    return recover(command, guardRecord: guardRecord)+                    return recover(command, guardRecord: guardRecord, batchPolicy: batchPolicy)                 }             }             if let receipt = try receipts.lookup(tool: tool, key: command.key, durable: true) {@@ -133,7 +139,7 @@ extension MCPWriteCoordinator {                     let repaired = try reservations.reserve(                         tool: tool, key: command.key, requestJSON: payload,                         formatVersion: receipt.formatVersion, receiptID: receipt.id)-                    return recover(command, guardRecord: repaired)+                    return recover(command, guardRecord: repaired, batchPolicy: batchPolicy)                 }             }         } catch {@@ -180,15 +186,21 @@ extension MCPWriteCoordinator {         reservations: MCPLocalReservationStore, receipts: MCPWriteReceiptStore,         batchPolicy: MCPBatchWritePolicy?     ) -> Acceptance {-        if batchPolicy != nil && services.context.hasChanges {+        if (batchPolicy != nil || command.hasLinkInput) && 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) {+        if let existing = existingOutcome(command, payload: payload, reservations: reservations, receipts: receipts,+                                          batchPolicy: batchPolicy) {             return .result(existing)         }+        if command.hasLinkInput && batchPolicy?.taskLinkCapability == nil {+            return .result(transient(command,+                .init("PERSISTENCE_UNAVAILABLE", "Typed-link owned plan/apply policy is not installed"),+                accepted: false))+        }         do {             if services.context.hasChanges { try save(services.context, .baseline) }         } catch {@@ -223,7 +235,7 @@ extension MCPWriteCoordinator {             services.context.safeRollback()             return .result(rejectBeforeDomain(                     command, guardRecord: guardRecord,-                    failure: .init("INTERNAL_ERROR", "Unable to save request acceptance")))+                    failure: .init("INTERNAL_ERROR", "Unable to save request acceptance"), batchPolicy: batchPolicy))         }         return .ready(guardRecord, receipt)     }@@ -236,14 +248,14 @@ extension MCPWriteCoordinator {         let prepared: PreparedMCPWrite         do {             try await preparationHook(command)-            if batchPolicy != nil && services.context.hasChanges {+            if (batchPolicy != nil || command.hasLinkInput) && services.context.hasChanges {                 return dirtyUnavailable(command, accepted: true, batchPolicy: batchPolicy)             }-            prepared = try await command.prepare(using: services)+            prepared = try await command.prepare(using: services, newTaskID: newTaskID)             try Task.checkCancellation()         } catch {             // Return before a rejection phase can save or roll back UI edits.-            if batchPolicy != nil && services.context.hasChanges {+            if (batchPolicy != nil || command.hasLinkInput) && services.context.hasChanges {                 return dirtyUnavailable(command, accepted: true, batchPolicy: batchPolicy)             }             // Validate a fresh scope after suspension, before retaining rejection.@@ -251,11 +263,16 @@ extension MCPWriteCoordinator {                 return try reservations.withValidatedBindings {                     try reservations.validateBinding(guardRecord)                     if services.context.hasChanges { try save(services.context, .baseline) }-                    return completeRejection(command, receipt: receipt, failure: MCPWriteFailure.from(error))+                    if batchPolicy?.makeCommitServices != nil {+                        return rejectInOwnedScope(command, guardRecord: guardRecord,+                                                  failure: MCPWriteFailure.from(error), batchPolicy: batchPolicy)+                    }+                    return completeRejection(command, receipt: receipt, failure: MCPWriteFailure.from(error),+                                             guardRecord: guardRecord)                 }             } catch { return uncertain(command) }         }-        if batchPolicy != nil && services.context.hasChanges {+        if (batchPolicy != nil || command.hasLinkInput) && services.context.hasChanges {             return dirtyUnavailable(command, accepted: true, batchPolicy: batchPolicy)         }         do {@@ -274,22 +291,31 @@ extension MCPWriteCoordinator {         _ command: MCPWriteCommand, prepared: PreparedMCPWrite,         receipt: MCPWriteReceipt, guardRecord: MCPLocalReservation, batchPolicy: MCPBatchWritePolicy?     ) -> MCPToolResult {-        let context = services.context+        let scope: MCPWriteCommitScope+        let scopedReceipt: MCPWriteReceipt+        do {+            scope = try MCPWriteCommitScope(shared: services, scopeID: guardRecord.scopeID, policy: batchPolicy)+            scopedReceipt = batchPolicy?.makeCommitServices == nil ? receipt : try scope.receipt(for: guardRecord)+            if let retained = replay(scopedReceipt) { return retained }+        } catch { return uncertain(command) }+        let context = scope.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)+            try batchPolicy?.taskLinkCapability?.validatePrepared(command, prepared, scope.services)+            var envelope = try command.apply(+                prepared, using: scope.services, afterTaskApply: batchPolicy?.afterTaskApply)             envelope["contractVersion"] = 1             envelope["tool"] = command.tool             envelope["idempotencyKey"] = command.key             envelope["outcome"] = "committed"             envelope["accepted"] = true-            let result = try stageTerminal(receipt, envelope: envelope, rejected: false)+            let result = try stageTerminal(scopedReceipt, envelope: envelope, rejected: false)             try save(context, .commit)             // Failed expiry repair never downgrades a committed domain/result.-            try? reservations?.recordExpiry(guardRecord, expiresAt: receipt.expiresAt!)+            try? reservations?.recordExpiry(guardRecord, expiresAt: scopedReceipt.expiresAt!)             return result         } catch {             let failure = MCPWriteFailure.from(error)@@ -298,24 +324,24 @@ extension MCPWriteCoordinator {             do {                 try recoveryHook()                 guard let durable = try receipts?.lookup(tool: command.tool, key: command.key, durable: true),-                    durable.id == guardRecord.receiptID+                    MCPWriteCommitScope.matches(durable, guardRecord: guardRecord)                 else { return uncertain(command) }                 if let result = replay(durable) { return result }                 // The disk probe establishes that durable accepted means the                 // domain/result transaction did not commit.-                guard let live = try receipts?.lookup(tool: command.tool, key: command.key) else {-                    return uncertain(command)-                }-                return completeRejection(command, receipt: live, failure: failure)+                let live = try scope.receipt(for: guardRecord)+                return completeRejection(command, receipt: live, failure: failure,+                                         guardRecord: guardRecord, scope: scope)             } catch { return uncertain(command) }         }     } -    fileprivate func recover(_ command: MCPWriteCommand, guardRecord: MCPLocalReservation) -> MCPToolResult {+    fileprivate func recover(_ command: MCPWriteCommand, guardRecord: MCPLocalReservation,+                             batchPolicy: MCPBatchWritePolicy?) -> MCPToolResult {         do {             try recoveryHook()             guard let receipt = try receipts?.lookup(tool: command.tool, key: command.key, durable: true),-                receipt.id == guardRecord.receiptID, receipt.requestJSON == guardRecord.requestJSON+                MCPWriteCommitScope.matches(receipt, guardRecord: guardRecord)             else {                 return uncertain(command)             }@@ -325,54 +351,76 @@ extension MCPWriteCoordinator {                 }                 return result             }+            if batchPolicy?.makeCommitServices != nil {+                return rejectInOwnedScope(command, guardRecord: guardRecord,+                    failure: .init("INTERRUPTED_BEFORE_COMMIT", "Accepted operation did not commit"),+                    batchPolicy: batchPolicy)+            }             guard let live = try receipts?.lookup(tool: command.tool, key: command.key) else {                 return uncertain(command)             }             if services.context.hasChanges { try save(services.context, .baseline) }             return completeRejection(                 command, receipt: live,-                failure: .init("INTERRUPTED_BEFORE_COMMIT", "Accepted operation did not commit"))+                failure: .init("INTERRUPTED_BEFORE_COMMIT", "Accepted operation did not commit"),+                guardRecord: guardRecord)         } catch { return uncertain(command) }     }      fileprivate func rejectBeforeDomain(         _ command: MCPWriteCommand, guardRecord: MCPLocalReservation,-        failure: MCPWriteFailure+        failure: MCPWriteFailure, batchPolicy: MCPBatchWritePolicy?     ) -> MCPToolResult {         do {             try recoveryHook()-            if let durable = try receipts?.lookup(tool: command.tool, key: command.key, durable: true),-                let result = replay(durable) {-                return result+            if let durable = try receipts?.lookup(tool: command.tool, key: command.key, durable: true) {+                guard MCPWriteCommitScope.matches(durable, guardRecord: guardRecord) else { return uncertain(command) }+                if let result = replay(durable) { return result }+            }+            if batchPolicy?.makeCommitServices != nil {+                let scope = try MCPWriteCommitScope(shared: services, scopeID: guardRecord.scopeID, policy: batchPolicy)+                let live: MCPWriteReceipt+                if try scope.receipts.lookup(tool: command.tool, key: command.key) != nil {+                    live = try scope.receipt(for: guardRecord)+                } else {+                    // This branch is reached only after acceptance save failed,+                    // before preparation/domain apply; genuine absence is proven.+                    live = try scope.receipts.insert(guardRecord, acceptedAt: clock())+                }+                return completeRejection(command, receipt: live, failure: failure,+                                         guardRecord: guardRecord, scope: scope)             }             guard let receipts else { return uncertain(command) }             let live =                 try receipts.lookup(tool: command.tool, key: command.key)                 ?? receipts.insert(guardRecord, acceptedAt: clock())-            return completeRejection(command, receipt: live, failure: failure)+            return completeRejection(command, receipt: live, failure: failure, guardRecord: guardRecord)         } catch { return uncertain(command) }     }      fileprivate func completeRejection(         _ command: MCPWriteCommand, receipt: MCPWriteReceipt,-        failure: MCPWriteFailure+        failure: MCPWriteFailure, guardRecord: MCPLocalReservation, scope: MCPWriteCommitScope? = nil     ) -> MCPToolResult {+        guard MCPWriteCommitScope.matches(receipt, guardRecord: guardRecord) else { return uncertain(command) }         let envelope = MCPWriteOutcome.failure(             tool: command.tool, key: command.key, failure: failure, accepted: true)+        let context = scope?.context ?? services.context         do {             let result = try stageTerminal(receipt, envelope: envelope, rejected: true)-            try save(services.context, .rejection)+            try save(context, .rejection)             if let binding = try? reservations?.lookup(tool: command.tool, key: command.key),                 let expiry = receipt.expiresAt {                 try? reservations?.recordExpiry(binding, expiresAt: expiry)             }             return result         } catch {-            for model in services.context.insertedModelsArray { services.context.delete(model) }-            services.context.safeRollback()+            for model in context.insertedModelsArray { context.delete(model) }+            context.safeRollback()             do {                 try recoveryHook()                 if let durable = try receipts?.lookup(tool: command.tool, key: command.key, durable: true),+                    MCPWriteCommitScope.matches(durable, guardRecord: guardRecord),                     let result = replay(durable) {                     return result                 }@@ -381,6 +429,17 @@ extension MCPWriteCoordinator {         }     } +    private func rejectInOwnedScope(_ command: MCPWriteCommand, guardRecord: MCPLocalReservation,+                                    failure: MCPWriteFailure, batchPolicy: MCPBatchWritePolicy?) -> MCPToolResult {+        do {+            let scope = try MCPWriteCommitScope(shared: services, scopeID: guardRecord.scopeID, policy: batchPolicy)+            let receipt = try scope.receipt(for: guardRecord)+            if let retained = replay(receipt) { return retained }+            return completeRejection(command, receipt: receipt, failure: failure,+                                     guardRecord: guardRecord, scope: scope)+        } catch { return uncertain(command) }+    }+     fileprivate func stageTerminal(_ receipt: MCPWriteReceipt, envelope: [String: Any], rejected: Bool) throws         -> MCPToolResult {         let completed = clock()
Transit/Transit/MCP/Writes/TaskLinkIncidence.swift Changed +35 / -0
diff --git a/Transit/Transit/MCP/Writes/TaskLinkIncidence.swift b/Transit/Transit/MCP/Writes/TaskLinkIncidence.swiftnew file mode 100644index 00000000..d4f1bab1--- /dev/null+++ b/Transit/Transit/MCP/Writes/TaskLinkIncidence.swift@@ -0,0 +1,35 @@+import Foundation+import SwiftData++/// Every incident physical occurrence participates, including malformed imports+/// and repeated identical tuples. Removal evidence and opposite labels do not.+@MainActor enum TaskLinkIncidence {+    static func capture(_ id: UUID, in context: ModelContext,+                        includePendingChanges: Bool = true) throws -> [TaskLinkOccurrenceValue] {+        var descriptor = FetchDescriptor<TaskLinkOccurrence>(predicate: #Predicate {+            $0.sourceTaskID == id || $0.targetTaskID == id+        })+        descriptor.includePendingChanges = includePendingChanges+        return try context.fetch(descriptor).map {+            TaskLinkOccurrenceValue(physicalKey: Data(), id: $0.id, kind: $0.kindRawValue,+                                    source: $0.sourceTaskID, target: $0.targetTaskID, createdAt: $0.createdAt)+        }+    }++    static func canonical(_ rows: [TaskLinkOccurrenceValue], incidentTo id: UUID,+                          budget: TaskLinkGraphBudget? = nil) throws -> [[String: Any]] {+        try budget?.check()+        let canonical = try rows.filter { row in+            try budget?.check()+            return row.source == id || row.target == id+        }.map { row in+            try budget?.check()+            let fields: [String: Any] = ["edgeId": MCPRecordRevision.uuid(row.id), "kind": row.kind,+                "sourceTaskId": MCPRecordRevision.uuid(row.source),+                "targetTaskId": MCPRecordRevision.uuid(row.target)]+            return (try MCPCanonicalJSON.encode(fields), fields)+        }.sorted { $0.0 < $1.0 }.map(\.1)+        try budget?.check()+        return canonical+    }+}
Transit/Transit/MCP/Writes/TaskLinkOwnedApply.swift Changed +48 / -0
diff --git a/Transit/Transit/MCP/Writes/TaskLinkOwnedApply.swift b/Transit/Transit/MCP/Writes/TaskLinkOwnedApply.swiftnew file mode 100644index 00000000..161f319f--- /dev/null+++ b/Transit/Transit/MCP/Writes/TaskLinkOwnedApply.swift@@ -0,0 +1,48 @@+#if os(macOS)+import Foundation+import SwiftData++@MainActor enum TaskLinkOwnedApply {+    /// Deletes only a freshly revalidated physical identity/immutable tuple.+    /// Evidence is a separate same-store insertion, never a platform tombstone.+    static func apply(_ plan: TaskLinkPlan, in context: ModelContext, instant: Date,+                      budget: TaskLinkGraphBudget) throws {+        for value in plan.removals {+            try budget.check()+            let id = value.id+            var descriptor = FetchDescriptor<TaskLinkOccurrence>(predicate: #Predicate { $0.id == id })+            descriptor.fetchLimit = 2+            let rows = try context.fetch(descriptor)+            let identity = try JSONDecoder().decode(PersistentIdentifier.self, from: value.physicalKey)+            guard rows.count == 1, let row = rows.first, row.persistentModelID == identity,+                  row.kindRawValue == value.kind, row.sourceTaskID == value.source, row.targetTaskID == value.target,+                  sameDate(row.createdAt, value.createdAt)+            else { throw MCPWriteFailure("LINK_REPAIR_UNAVAILABLE", "Exact occurrence changed before owned deletion") }+            let evidenceID = UUID()+            guard try context.fetchCount(FetchDescriptor<TaskLinkRemovalEvidence>(predicate: #Predicate {+                $0.id == evidenceID+            })) == 0 else { throw MCPWriteFailure("DUPLICATE_TASK_IDENTIFIER", "New removal identity conflicts") }+            let evidence = TaskLinkRemovalEvidence(id: evidenceID, edgeId: value.id, kindRawValue: value.kind,+                sourceTaskID: value.source, targetTaskID: value.target, createdAt: value.createdAt,+                occurrenceRevision: try TaskLinkGraph.occurrenceRevision(value), removedAt: instant)+            context.delete(row)+            context.insert(evidence)+        }+        for addition in plan.additions {+            try budget.check()+            let id = UUID()+            let existing = try context.fetchCount(+                FetchDescriptor<TaskLinkOccurrence>(predicate: #Predicate { $0.id == id }))+            guard existing == 0+            else { throw MCPWriteFailure("DUPLICATE_TASK_IDENTIFIER", "New occurrence identity conflicts") }+            context.insert(TaskLinkOccurrence(id: id, kindRawValue: addition.relation.kind,+                sourceTaskID: addition.relation.source, targetTaskID: addition.relation.target, createdAt: instant))+        }+        try budget.check()+    }++    private static func sameDate(_ left: Date, _ right: Date) -> Bool {+        left.timeIntervalSinceReferenceDate.bitPattern == right.timeIntervalSinceReferenceDate.bitPattern+    }+}+#endif
Transit/Transit/MCP/Writes/TaskLinkOwnedPlan.swift Changed +111 / -0
diff --git a/Transit/Transit/MCP/Writes/TaskLinkOwnedPlan.swift b/Transit/Transit/MCP/Writes/TaskLinkOwnedPlan.swiftnew file mode 100644index 00000000..055eb8d9--- /dev/null+++ b/Transit/Transit/MCP/Writes/TaskLinkOwnedPlan.swift@@ -0,0 +1,111 @@+#if os(macOS)+import Foundation+import SwiftData++/// One synchronous operation. Independent store/import writers remain outside+/// this coordination contract; no saved predicate fence is claimed.+@MainActor final class TaskLinkOwnedPlan {+    private var context: ModelContext?+    private var sourceID: UUID?+    private var plan: TaskLinkPlan?+    private var budget = TaskLinkGraphBudget()+    private var instant = Date()++    func validate(_ command: MCPWriteCommand, prepared: PreparedMCPWrite,+                  services: MCPWriteCommandServices) throws {+        guard context == nil, !services.context.hasChanges, !services.context.autosaveEnabled else {+            throw MCPWriteFailure("OUTCOME_UNCERTAIN", "Unable to establish owned graph validation")+        }+        context = services.context+        budget = TaskLinkGraphBudget()+        instant = Date()+        guard let source = try validateSource(command, prepared: prepared, in: services.context) else { return }+        let (id, creating) = source+        sourceID = id+        let requestValue = try TaskLinkWireRequest.parse(tool: command.tool, arguments: command.arguments)+        guard let request = requestValue else { return }+        guard !request.changes.isEmpty else {+            guard request.endpointPreconditions.isEmpty else {+                throw MCPWriteFailure("INVALID_INPUT", "No link changes require no endpoint guards")+            }+            return+        }+        do {+            var graph = try TaskLinkService.graph(in: services.context, evaluationInstant: instant, budget: budget)+            if let creating {+                let virtual = TaskLinkTaskValue(physicalKey: Data(("prepared:" + id.uuidString).utf8),+                                               id: id, name: creating.name, status: TaskStatus.idea.rawValue)+                graph = try TaskLinkGraph.project(tasks: graph.tasks + [virtual], occurrences: graph.occurrences,+                    removalEvidence: graph.removalEvidence, evaluationInstant: instant, budget: budget)+            }+            var revisions: [UUID: String] = [:]+            for endpoint in request.endpointPreconditions.keys {+                try budget.check()+                let snapshot = try endpointSnapshot(endpoint, in: services.context)+                revisions[endpoint] = snapshot.revision+                guard request.endpointPreconditions[endpoint] == snapshot.revision else {+                    throw MCPWriteFailure("REVISION_CONFLICT", "Endpoint content changed",+                                          currentRecord: snapshot.record)+                }+            }+            plan = try TaskLinkPlan.validate(delta: request.changes, source: id,+                preconditions: request.endpointPreconditions, revisions: revisions, savedGraph: graph, budget: budget)+        } catch {+            let failure = TaskLinkWriteFailure.map(error)+            if failure.code == "REVISION_CONFLICT", failure.currentRecord == nil, creating == nil {+                let current = try endpointSnapshot(id, in: services.context)+                throw MCPWriteFailure(failure.code, failure.message, currentRecord: current.record)+            }+            throw failure+        }+    }++    func apply(_ command: MCPWriteCommand, task: TransitTask, services: MCPWriteCommandServices) throws {+        guard services.context === context, task.modelContext === context, task.id == sourceID else {+            throw MCPWriteFailure("OUTCOME_UNCERTAIN", "Owned graph plan/context identity changed")+        }+        guard let plan else { return }+        try budget.check()+        try TaskLinkOwnedApply.apply(plan, in: services.context, instant: instant, budget: budget)+        self.plan = nil+    }++    private func validateSource(_ command: MCPWriteCommand, prepared: PreparedMCPWrite,+                                in context: ModelContext) throws -> (UUID, TaskService.PreparedCreation?)? {+        let creating: TaskService.PreparedCreation?+        let id: UUID+        switch prepared {+        case let .taskCreation(creation, identity): id = identity; creating = creation+        case let .task(identity): id = identity; creating = nil+        default: return nil+        }+        var descriptor = FetchDescriptor<TransitTask>(predicate: #Predicate { $0.id == id })+        descriptor.fetchLimit = 2+        descriptor.includePendingChanges = false+        let rows = try context.fetch(descriptor)+        if creating != nil {+            guard rows.isEmpty else {+                throw MCPWriteFailure("DUPLICATE_TASK_IDENTIFIER", "Prepared task UUID already exists")+            }+        } else {+            let snapshot = try endpointSnapshot(id, in: context)+            if let expected = command.expectedRevision, expected != snapshot.revision {+                throw MCPWriteFailure("REVISION_CONFLICT", "Task content changed", currentRecord: snapshot.record)+            }+        }+        return (id, creating)+    }++    private func endpointSnapshot(_ id: UUID, in context: ModelContext) throws -> MCPRecordSnapshot {+        var descriptor = FetchDescriptor<TransitTask>(predicate: #Predicate { $0.id == id })+        descriptor.fetchLimit = 2+        descriptor.includePendingChanges = false+        let rows = try context.fetch(descriptor)+        guard rows.count == 1, let task = rows.first else {+            throw MCPWriteFailure(rows.isEmpty ? "TASK_NOT_FOUND" : "DUPLICATE_TASK_IDENTIFIER",+                                  "Affected endpoint is unavailable or ambiguous")+        }+        return try MCPRecordSnapshot.task(task, in: context)+    }+}+#endif
Transit/Transit/MCP/Writes/TaskLinkWireRequest.swift Changed +74 / -0
diff --git a/Transit/Transit/MCP/Writes/TaskLinkWireRequest.swift b/Transit/Transit/MCP/Writes/TaskLinkWireRequest.swiftnew file mode 100644index 00000000..6c8c0056--- /dev/null+++ b/Transit/Transit/MCP/Writes/TaskLinkWireRequest.swift@@ -0,0 +1,74 @@+#if os(macOS)+import Foundation++/// Shape validation has no store access. Semantic references and exact selector+/// evidence remain domain validation after durable replay and acceptance.+@MainActor struct TaskLinkWireRequest {+    static let fields: Set<String> = ["linkChanges", "endpointPreconditions"]+    let changes: [TaskLinkChange]+    let endpointPreconditions: [UUID: String]++    static func parse(tool: String, arguments: [String: Any]) throws -> Self? {+        guard arguments["linkChanges"] != nil || arguments["endpointPreconditions"] != nil else { return nil }+        guard ["create_task", "update_task"].contains(tool) else { throw invalid() }+        let raw = try objects(arguments["linkChanges"])+        let source = (arguments["taskId"] as? String).flatMap(UUID.init(uuidString:))+        var changes: [TaskLinkChange] = []+        var removals: Set<UUID> = []+        var additions: Set<String> = []+        for fields in raw {+            let change = try directive(fields, creating: tool == "create_task", source: source)+            switch change {+            case let .add(type, target):+                guard additions.insert(type.rawValue + ":" + target.uuidString).inserted else { throw invalid() }+            case let .remove(id, _):+                guard removals.insert(id).inserted else { throw invalid() }+            }+            changes.append(change)+        }+        var guards: [UUID: String] = [:]+        for fields in try objects(arguments["endpointPreconditions"]) {+            guard Set(fields.keys) == ["taskId", "expectedRevision"],+                  let id = uuid(fields["taskId"]), id != source,+                  let revision = fields["expectedRevision"] as? String, token(revision, prefix: "r1"),+                  guards.updateValue(revision, forKey: id) == nil else { throw invalid() }+        }+        return Self(changes: changes, endpointPreconditions: guards)+    }++    private static func directive(_ fields: [String: Any], creating: Bool, source: UUID?) throws -> TaskLinkChange {+        switch fields["action"] as? String {+        case "add":+            guard Set(fields.keys) == ["action", "type", "targetTaskId"],+                  let rawType = fields["type"] as? String, let type = TaskLinkType(rawValue: rawType),+                  let target = uuid(fields["targetTaskId"]), target != source else { throw invalid() }+            return .add(type: type, target: target)+        case "remove":+            guard !creating, Set(fields.keys) == ["action", "edgeId", "occurrenceRevision"],+                  let edge = uuid(fields["edgeId"]), let revision = fields["occurrenceRevision"] as? String,+                  token(revision, prefix: "l1") else { throw invalid() }+            return .remove(edgeId: edge, occurrenceRevision: revision)+        default: throw invalid()+        }+    }++    private static func objects(_ value: Any?) throws -> [[String: Any]] {+        guard let value else { return [] }+        guard let objects = value as? [[String: Any]], objects.count <= 50 else { throw invalid() }+        return objects+    }++    private static func uuid(_ value: Any?) -> UUID? {+        (value as? String).flatMap(UUID.init(uuidString:))+    }++    private static func token(_ value: String, prefix: String) -> Bool {+        let pattern = "^" + prefix + ":[0-9a-f]{64}$"+        return value.range(of: pattern, options: .regularExpression) == value.startIndex..<value.endIndex+    }++    private static func invalid() -> MCPWriteFailure {+        MCPWriteFailure("INVALID_INPUT", "Invalid typed-link directive or endpoint precondition")+    }+}+#endif
Transit/Transit/MCP/Writes/TaskLinkWriteAdapter.swift Changed +43 / -0
diff --git a/Transit/Transit/MCP/Writes/TaskLinkWriteAdapter.swift b/Transit/Transit/MCP/Writes/TaskLinkWriteAdapter.swiftnew file mode 100644index 00000000..c93be7f1--- /dev/null+++ b/Transit/Transit/MCP/Writes/TaskLinkWriteAdapter.swift@@ -0,0 +1,43 @@+#if os(macOS)+import Foundation+import SwiftData++/// Only this feature adapter can mint capability. It binds full saved validation+/// and exact owned apply to one operation's services and prepared identity.+@MainActor struct TaskLinkWriteCapability {+    let validatePrepared: (MCPWriteCommand, PreparedMCPWrite, MCPWriteCommandServices) throws -> Void+    fileprivate init(+        _ validation: @escaping (MCPWriteCommand, PreparedMCPWrite, MCPWriteCommandServices) throws -> Void+    ) {+        validatePrepared = validation+    }+}++@MainActor final class TaskLinkWriteAdapter {+    private let taskAllocator: DisplayIDAllocator+    private let milestoneAllocator: DisplayIDAllocator++    init(taskAllocator: DisplayIDAllocator, milestoneAllocator: DisplayIDAllocator) {+        self.taskAllocator = taskAllocator+        self.milestoneAllocator = milestoneAllocator+    }++    /// A new plan holder for each standalone request/per-item batch operation;+    /// no plan survives an await, result replay or the owned commit phase.+    func policy(onPendingEditsStop: @escaping @MainActor () -> Void = {}) -> MCPBatchWritePolicy {+        let owned = TaskLinkOwnedPlan()+        return MCPBatchWritePolicy(makeCommitServices: { [taskAllocator, milestoneAllocator] context in+            MCPWriteCommitServices(context: context, taskAllocator: taskAllocator,+                                   milestoneAllocator: milestoneAllocator)+        }, onPendingEditsStop: onPendingEditsStop, afterTaskApply: { command, task, services in+            try owned.apply(command, task: task, services: services)+        }, taskLinkCapability: TaskLinkWriteCapability { command, prepared, services in+            try owned.validate(command, prepared: prepared, services: services)+        }, validateBeforeApply: { _, context in+            guard !context.hasChanges && !context.autosaveEnabled else {+                throw MCPWriteFailure("OUTCOME_UNCERTAIN", "Saved graph validation requires a clean owned context")+            }+        })+    }+}+#endif
Transit/Transit/MCP/Writes/TaskLinkWriteFailure.swift Changed +21 / -0
diff --git a/Transit/Transit/MCP/Writes/TaskLinkWriteFailure.swift b/Transit/Transit/MCP/Writes/TaskLinkWriteFailure.swiftnew file mode 100644index 00000000..18e58944--- /dev/null+++ b/Transit/Transit/MCP/Writes/TaskLinkWriteFailure.swift@@ -0,0 +1,21 @@+#if os(macOS)+import Foundation++@MainActor enum TaskLinkWriteFailure {+    static func map(_ error: any Error) -> MCPWriteFailure {+        if let failure = error as? MCPWriteFailure { return failure }+        guard let graph = error as? TaskLinkGraphError else { return MCPWriteFailure.from(error) }+        switch graph {+        case .missingSource: return .init("TASK_NOT_FOUND", "Saved source task is unavailable")+        case .ambiguousIdentity: return .init("DUPLICATE_TASK_IDENTIFIER", "Task identity is ambiguous")+        case .revisionConflict: return .init("REVISION_CONFLICT", "Affected endpoint content changed")+        case .repairUnavailable: return .init("LINK_REPAIR_UNAVAILABLE", "Exact selector is unavailable or expired")+        case .invalidOccurrence: return .init("REVISION_CONFLICT", "Exact immutable occurrence evidence changed")+        case .invalidDelta, .endpointPreconditions: return .init("INVALID_INPUT", "Link directives/guards contradict")+        case .invalidGraph: return .init("LINK_GRAPH_INVALID", "Proposed affected graph cannot be certified")+        case .deadlineExceeded, .capacityExceeded:+            return .init("PERSISTENCE_UNAVAILABLE", "Complete saved graph evidence exceeded its operation budget")+        }+    }+}+#endif
Transit/Transit/Models/TaskLinkOccurrence.swift Changed +22 / -0
diff --git a/Transit/Transit/Models/TaskLinkOccurrence.swift b/Transit/Transit/Models/TaskLinkOccurrence.swiftnew file mode 100644index 00000000..8e429883--- /dev/null+++ b/Transit/Transit/Models/TaskLinkOccurrence.swift@@ -0,0 +1,22 @@+import Foundation+import SwiftData++/// One active physical occurrence. Scalar endpoints preserve dangling and+/// ambiguous imported evidence without task relationships or delete cascades.+/// Storage defaults support additive schema compatibility, not graph validity.+@Model+final class TaskLinkOccurrence {+    private(set) var id: UUID = UUID()+    private(set) var kindRawValue: String = ""+    private(set) var sourceTaskID: UUID = UUID()+    private(set) var targetTaskID: UUID = UUID()+    private(set) var createdAt: Date = Date()++    init(id: UUID, kindRawValue: String, sourceTaskID: UUID, targetTaskID: UUID, createdAt: Date) {+        self.id = id+        self.kindRawValue = kindRawValue+        self.sourceTaskID = sourceTaskID+        self.targetTaskID = targetTaskID+        self.createdAt = createdAt+    }+}
Transit/Transit/Models/TaskLinkRemovalEvidence.swift Changed +29 / -0
diff --git a/Transit/Transit/Models/TaskLinkRemovalEvidence.swift b/Transit/Transit/Models/TaskLinkRemovalEvidence.swiftnew file mode 100644index 00000000..7ba6caa4--- /dev/null+++ b/Transit/Transit/Models/TaskLinkRemovalEvidence.swift@@ -0,0 +1,29 @@+import Foundation+import SwiftData++/// Bounded exact-removal recognition stored separately from the deleted active+/// occurrence. Expiry never changes active incidence or platform sync history.+/// Raw immutable values preserve malformed imports for later diagnostics.+@Model+final class TaskLinkRemovalEvidence {+    private(set) var id: UUID = UUID()+    private(set) var edgeId: UUID = UUID()+    private(set) var kindRawValue: String = ""+    private(set) var sourceTaskID: UUID = UUID()+    private(set) var targetTaskID: UUID = UUID()+    private(set) var createdAt: Date = Date()+    private(set) var occurrenceRevision: String = ""+    private(set) var removedAt: Date = Date()++    init(id: UUID, edgeId: UUID, kindRawValue: String, sourceTaskID: UUID, targetTaskID: UUID,+         createdAt: Date, occurrenceRevision: String, removedAt: Date) {+        self.id = id+        self.edgeId = edgeId+        self.kindRawValue = kindRawValue+        self.sourceTaskID = sourceTaskID+        self.targetTaskID = targetTaskID+        self.createdAt = createdAt+        self.occurrenceRevision = occurrenceRevision+        self.removedAt = removedAt+    }+}
Transit/Transit/Services/TaskLinks/TaskLinkEvidenceMaintenance.swift Changed +78 / -0
diff --git a/Transit/Transit/Services/TaskLinks/TaskLinkEvidenceMaintenance.swift b/Transit/Transit/Services/TaskLinks/TaskLinkEvidenceMaintenance.swiftnew file mode 100644index 00000000..3870b06e--- /dev/null+++ b/Transit/Transit/Services/TaskLinks/TaskLinkEvidenceMaintenance.swift@@ -0,0 +1,78 @@+import Foundation+import SwiftData++@MainActor enum TaskLinkEvidenceMaintenance {+    /// Startup alone invokes maintenance; unit/UI memory hosts stay inactive.+    static func atStartup(container: ModelContainer, mode: AppPersistencePolicy.Mode,+                          persistence: PersistenceAvailability) {+        guard !mode.usesMemoryStore, !persistence.isFallbackStorageActive else { return }+        _ = try? cleanup(container: container, instant: Date(), limit: 128, budget: TaskLinkGraphBudget())+    }++    /// At most 512 candidates scanned and 128 deletions in one startup pass.+    /// Unsafe evidence remains untouched; this is not a remote sync safety horizon.+    static func cleanup(container: ModelContainer, instant: Date, limit: Int,+                        budget: TaskLinkGraphBudget) throws -> Int {+        try budget.check()+        guard instant.timeIntervalSinceReferenceDate.isFinite, (1...128).contains(limit) else {+            throw TaskLinkGraphError.invalidDelta+        }+        let context = ModelContext(container)+        context.autosaveEnabled = false+        let cutoff = instant.addingTimeInterval(-TaskLinkGraph.evidenceLifetime)+        var descriptor = FetchDescriptor<TaskLinkRemovalEvidence>(+            predicate: #Predicate { $0.removedAt <= cutoff }, sortBy: [SortDescriptor(\.removedAt)])+        descriptor.fetchLimit = min(512, limit * 4)+        descriptor.includePendingChanges = false+        let candidates = try context.fetch(descriptor)+        var removed = 0, bytes = 0+        do {+            for candidate in candidates {+                try budget.check()+                if removed == limit { break }+                bytes += candidate.kindRawValue.utf8.count + candidate.occurrenceRevision.utf8.count + 160+                guard bytes <= budget.maximumBytes else { throw TaskLinkGraphError.capacityExceeded }+                guard try eligible(candidate, instant: instant, budget: budget) else { continue }+                let id = candidate.id+                var exact = FetchDescriptor<TaskLinkRemovalEvidence>(predicate: #Predicate { $0.id == id })+                exact.fetchLimit = 2+                exact.includePendingChanges = false+                let rows = try context.fetch(exact)+                try budget.check()+                guard rows.count == 1, let fresh = rows.first,+                      fresh.persistentModelID == candidate.persistentModelID,+                      sameTuple(fresh, candidate), try eligible(fresh, instant: instant, budget: budget)+                else { continue }+                context.delete(fresh)+                removed += 1+            }+            try budget.check()+            if removed > 0 { try context.save() }+            return removed+        } catch {+            context.safeRollback()+            throw error+        }+    }++    private static func eligible(_ row: TaskLinkRemovalEvidence, instant: Date,+                                 budget: TaskLinkGraphBudget) throws -> Bool {+        try budget.check()+        let elapsed = instant.timeIntervalSince(row.removedAt)+        guard elapsed.isFinite, elapsed >= TaskLinkGraph.evidenceLifetime,+              row.createdAt.timeIntervalSinceReferenceDate.isFinite else { return false }+        let original = TaskLinkOccurrenceValue(physicalKey: Data(), id: row.edgeId, kind: row.kindRawValue,+            source: row.sourceTaskID, target: row.targetTaskID, createdAt: row.createdAt)+        return (try? TaskLinkGraph.occurrenceRevision(original)) == row.occurrenceRevision+    }++    private static func sameTuple(_ left: TaskLinkRemovalEvidence, _ right: TaskLinkRemovalEvidence) -> Bool {+        left.id == right.id && left.edgeId == right.edgeId && left.kindRawValue == right.kindRawValue+            && left.sourceTaskID == right.sourceTaskID && left.targetTaskID == right.targetTaskID+            && left.createdAt.timeIntervalSinceReferenceDate.bitPattern+                == right.createdAt.timeIntervalSinceReferenceDate.bitPattern+            && left.removedAt.timeIntervalSinceReferenceDate.bitPattern+                == right.removedAt.timeIntervalSinceReferenceDate.bitPattern+            && left.occurrenceRevision == right.occurrenceRevision+    }+}
Transit/Transit/Services/TaskLinks/TaskLinkGraph.swift Changed +147 / -0
diff --git a/Transit/Transit/Services/TaskLinks/TaskLinkGraph.swift b/Transit/Transit/Services/TaskLinks/TaskLinkGraph.swiftnew file mode 100644index 00000000..c9cc2f99--- /dev/null+++ b/Transit/Transit/Services/TaskLinks/TaskLinkGraph.swift@@ -0,0 +1,147 @@+import Foundation+import CryptoKit++/// Projects frozen values. No model access, saves, alias redirection or repair.+enum TaskLinkGraph {+    static let knownStatuses: Set<String> = [+        "idea", "planning", "spec", "ready-for-implementation", "in-progress", "ready-for-review", "done", "abandoned"+    ]+    static let storedKinds: Set<String> = ["dependency", "association", "attribution", "duplicate"]+    static let evidenceLifetime: TimeInterval = 7 * 24 * 60 * 60++    static func occurrenceRevision(_ row: TaskLinkOccurrenceValue) throws -> String {+        let fields: [String: Any] = ["id": row.id.uuidString.lowercased(), "kind": row.kind,+            "source": row.source.uuidString.lowercased(), "target": row.target.uuidString.lowercased(),+            "createdAt": try MCPRecordRevision.exactDate(row.createdAt)]+        let canonical = try MCPCanonicalJSON.encode(fields)+        return "l1:" + SHA256.hash(data: Data(canonical.utf8)).map { String(format: "%02x", $0) }.joined()+    }++    static func relation(_ row: TaskLinkOccurrenceValue) -> TaskLinkRelation {+        if row.kind == "association" {+            return TaskLinkType.relatesTo.normalized(source: row.source, target: row.target)+        }+        return TaskLinkRelation(kind: row.kind, source: row.source, target: row.target)+    }++    static func project(+        tasks: [TaskLinkTaskValue], occurrences: [TaskLinkOccurrenceValue],+        removalEvidence: [TaskLinkRemovalValue], evaluationInstant: Date,+        budget: TaskLinkGraphBudget = TaskLinkGraphBudget()+    ) throws -> TaskLinkGraphView {+        var state = try TaskLinkGraphIndex(tasks: tasks, occurrences: occurrences,+                                          evidence: removalEvidence, instant: evaluationInstant, budget: budget)+        try state.diagnoseOccurrences(budget: budget)+        let cyclic = try cycleMembers(tasks: state.tasksById, occurrences: occurrences, budget: budget)+        for id in cyclic {+            try budget.check()+            state.diagnostics.append(TaskLinkDiagnostic(code: "dependency_cycle", taskIds: [id],+                                                        edgeId: nil, physicalKey: Data()))+        }+        let duplicateCycles = try cycleMembers(tasks: state.tasksById, occurrences: occurrences,+                                               kind: "duplicate", budget: budget)+        for id in duplicateCycles {+            try budget.check()+            state.diagnostics.append(TaskLinkDiagnostic(code: "duplicate_cycle", taskIds: [id],+                                                        edgeId: nil, physicalKey: Data()))+        }+        var blockers: [UUID: TaskLinkBlockerAssessment] = [:]+        for (id, matches) in state.tasksById {+            try budget.check()+            blockers[id] = try state.assessment(id: id, matches: matches, cyclic: cyclic, budget: budget)+        }+        try state.diagnostics.sort {+            try budget.check()+            let left = ($0.code, $0.taskIds.map(\.uuidString).joined(), $0.edgeId?.uuidString ?? "")+            let right = ($1.code, $1.taskIds.map(\.uuidString).joined(), $1.edgeId?.uuidString ?? "")+            return left == right ? $0.physicalKey.lexicographicallyPrecedes($1.physicalKey) : left < right+        }+        try budget.check()+        let view = TaskLinkGraphView(tasks: tasks, occurrences: occurrences, removalEvidence: removalEvidence,+            evaluationInstant: evaluationInstant, tasksById: state.tasksById, occurrencesById: state.edgesById,+            incidence: state.incidence, diagnostics: state.diagnostics, cyclicTasks: cyclic, blockers: blockers,+            retainedBytes: state.retainedBytes, invalidOccurrences: state.invalidOccurrences,+            recognizedRemovals: state.recognizedRemovals)+        return try view.withRetainedBytes(TaskLinkGraphCharge.bytes(view, budget: budget))+    }++    // Iterative Kosaraju. Every structurally resolvable physical dependency is retained.+    // Both traversals are iterative to bound stack use on large imported graphs.+    // swiftlint:disable:next cyclomatic_complexity+    static func cycleMembers(+        tasks: [UUID: [TaskLinkTaskValue]], occurrences: [TaskLinkOccurrenceValue],+        kind: String = "dependency", budget: TaskLinkGraphBudget+    ) throws -> Set<UUID> {+        var adjacency: [UUID: [UUID]] = [:], reverse: [UUID: [UUID]] = [:]+        for edge in occurrences {+            try budget.check()+            guard edge.kind == kind, tasks[edge.source]?.count == 1, tasks[edge.target]?.count == 1 else {+                continue+            }+            adjacency[edge.source, default: []].append(edge.target)+            reverse[edge.target, default: []].append(edge.source)+        }+        var visited: Set<UUID> = [], ordered: [UUID] = []+        for id in tasks.keys {+            try budget.check()+            guard visited.insert(id).inserted else { continue }+            var stack: [(UUID, Int)] = [(id, 0)]+            while let (node, offset) = stack.last {+                try budget.check()+                let neighbors = adjacency[node, default: []]+                if offset == neighbors.count { ordered.append(node); stack.removeLast(); continue }+                stack[stack.count - 1].1 += 1+                let next = neighbors[offset]+                if visited.insert(next).inserted { stack.append((next, 0)) }+            }+        }+        visited.removeAll(keepingCapacity: true)+        var cyclic: Set<UUID> = []+        for id in ordered.reversed() {+            try budget.check()+            guard visited.insert(id).inserted else { continue }+            var stack = [id], component: [UUID] = []+            while let node = stack.popLast() {+                try budget.check()+                component.append(node)+                for next in reverse[node, default: []] {+                    try budget.check()+                    if visited.insert(next).inserted { stack.append(next) }+                }+            }+            if component.count > 1 || adjacency[id, default: []].contains(id) { cyclic.formUnion(component) }+        }+        return cyclic+    }++    static func duplicateResolution(+        for id: UUID, in view: TaskLinkGraphView, budget: TaskLinkGraphBudget = TaskLinkGraphBudget()+    ) throws -> TaskLinkDuplicateResolution {+        var current = id, path: [UUID] = [], visited: Set<UUID> = []+        while true {+            try budget.check()+            guard visited.insert(current).inserted else {+                return TaskLinkDuplicateResolution(path: path + [current], canonical: nil,+                                                   diagnostic: "duplicate_cycle")+            }+            path.append(current)+            guard let matches = view.tasksById[current], matches.count == 1 else {+                return TaskLinkDuplicateResolution(path: path, canonical: nil,+                    diagnostic: view.tasksById[current] == nil ? "missing_endpoint" : "ambiguous_endpoint")+            }+            let edges = try view.incidence[current, default: []].filter {+                try budget.check(); return $0.kind == "duplicate" && $0.source == current+            }+            guard edges.count <= 1 else {+                return TaskLinkDuplicateResolution(path: path, canonical: nil, diagnostic: "duplicate_cardinality")+            }+            guard let edge = edges.first else {+                return TaskLinkDuplicateResolution(path: path, canonical: current, diagnostic: nil)+            }+            guard !view.invalidOccurrences.contains(edge.physicalKey) else {+                return TaskLinkDuplicateResolution(path: path, canonical: nil, diagnostic: "invalid_occurrence")+            }+            current = edge.target+        }+    }+}
Transit/Transit/Services/TaskLinks/TaskLinkGraphCharge.swift Changed +87 / -0
diff --git a/Transit/Transit/Services/TaskLinks/TaskLinkGraphCharge.swift b/Transit/Transit/Services/TaskLinks/TaskLinkGraphCharge.swiftnew file mode 100644index 00000000..c75fc16c--- /dev/null+++ b/Transit/Transit/Services/TaskLinks/TaskLinkGraphCharge.swift@@ -0,0 +1,87 @@+import Foundation++/// Logical encoded backing bytes, including every retained index and derived value.+/// This follows the shared read retention contract; it is not a heap-size estimate.+nonisolated enum TaskLinkGraphCharge {+    static func bytes(_ view: TaskLinkGraphView, budget: TaskLinkGraphBudget) throws -> Int {+        try budget.check()+        var count = try encode(["evaluationInstant": bits(view.evaluationInstant), "tasks": [], "occurrences": [],+            "removalEvidence": [], "tasksById": [], "occurrencesById": [], "incidence": [],+            "recognizedRemovals": [], "diagnostics": [], "cyclicTasks": [],+            "invalidOccurrences": [], "blockers": []]).count+        try records(view.tasks, count: &count, budget: budget, value: task)+        try records(view.occurrences, count: &count, budget: budget, value: occurrence)+        try records(view.removalEvidence, count: &count, budget: budget, value: removal)+        try index(view.tasksById, count: &count, budget: budget, key: { $0.physicalKey })+        try index(view.occurrencesById, count: &count, budget: budget, key: { $0.physicalKey })+        try index(view.incidence, count: &count, budget: budget, key: { $0.physicalKey })+        try index(view.recognizedRemovals, count: &count, budget: budget, key: { $0.physicalKey })+        try records(view.diagnostics, count: &count, budget: budget) {+            ["code": $0.code, "taskIds": $0.taskIds.map(\.uuidString),+             "edgeId": $0.edgeId?.uuidString as Any? ?? NSNull(), "physicalKey": $0.physicalKey.base64EncodedString()]+        }+        for id in view.cyclicTasks {+            try budget.check(); try add(try encode(id.uuidString).count + 1, to: &count, budget)+        }+        for key in view.invalidOccurrences {+            try budget.check(); try add(try encode(key.base64EncodedString()).count + 1, to: &count, budget)+        }+        for (id, assessment) in view.blockers {+            try budget.check()+            try add(try encode([id.uuidString, assessment.rawValue]).count + 1, to: &count, budget)+        }+        try budget.check()+        return count+    }++    private static func records<Value>(+        _ values: [Value], count: inout Int, budget: TaskLinkGraphBudget, value: (Value) -> [String: Any]+    ) throws {+        try add(values.count + 2, to: &count, budget)+        for row in values { try budget.check(); try add(try encode(value(row)).count, to: &count, budget) }+    }++    private static func index<Value>(+        _ index: [UUID: [Value]], count: inout Int, budget: TaskLinkGraphBudget, key: (Value) -> Data+    ) throws {+        try add(index.count + 2, to: &count, budget)+        for (id, rows) in index {+            try budget.check()+            var keys: [String] = []+            for row in rows { try budget.check(); keys.append(key(row).base64EncodedString()) }+            try add(try encode(["id": id.uuidString, "physicalKeys": keys]).count, to: &count, budget)+        }+    }++    private static func add(_ bytes: Int, to count: inout Int, _ budget: TaskLinkGraphBudget) throws {+        let (sum, overflow) = count.addingReportingOverflow(bytes)+        guard !overflow, sum <= budget.maximumBytes else { throw TaskLinkGraphError.capacityExceeded }+        count = sum+    }++    private static func encode(_ value: Any) throws -> Data {+        try JSONSerialization.data(withJSONObject: value, options: [.fragmentsAllowed, .sortedKeys])+    }++    /// Raw date bits retain even malformed imports without silently converting them to null/default dates.+    private static func bits(_ date: Date) -> String {+        String(date.timeIntervalSinceReferenceDate.bitPattern, radix: 16)+    }++    private static func task(_ row: TaskLinkTaskValue) -> [String: Any] {+        ["physicalKey": row.physicalKey.base64EncodedString(), "id": row.id.uuidString,+         "name": row.name, "status": row.status]+    }++    private static func occurrence(_ row: TaskLinkOccurrenceValue) -> [String: Any] {+        ["physicalKey": row.physicalKey.base64EncodedString(), "id": row.id.uuidString, "kind": row.kind,+         "source": row.source.uuidString, "target": row.target.uuidString, "createdAt": bits(row.createdAt)]+    }++    private static func removal(_ row: TaskLinkRemovalValue) -> [String: Any] {+        ["physicalKey": row.physicalKey.base64EncodedString(), "id": row.id.uuidString, "edgeId": row.edgeId.uuidString,+         "kind": row.kind, "source": row.source.uuidString, "target": row.target.uuidString,+         "createdAt": bits(row.createdAt), "occurrenceRevision": row.occurrenceRevision,+         "removedAt": bits(row.removedAt)]+    }+}
Transit/Transit/Services/TaskLinks/TaskLinkGraphIndex.swift Changed +128 / -0
diff --git a/Transit/Transit/Services/TaskLinks/TaskLinkGraphIndex.swift b/Transit/Transit/Services/TaskLinks/TaskLinkGraphIndex.swiftnew file mode 100644index 00000000..6b7d3147--- /dev/null+++ b/Transit/Transit/Services/TaskLinks/TaskLinkGraphIndex.swift@@ -0,0 +1,128 @@+import Foundation++/// Per-projection indices retain multiplicity instead of choosing arbitrary matches.+struct TaskLinkGraphIndex {+    var tasksById: [UUID: [TaskLinkTaskValue]] = [:]+    var edgesById: [UUID: [TaskLinkOccurrenceValue]] = [:]+    var incidence: [UUID: [TaskLinkOccurrenceValue]] = [:]+    var equivalents: [TaskLinkRelation: [TaskLinkOccurrenceValue]] = [:]+    var availableRemovals: [UUID: [TaskLinkRemovalValue]] = [:]+    var recognizedRemovals: [UUID: [TaskLinkRemovalValue]] = [:]+    var diagnostics: [TaskLinkDiagnostic] = []+    var invalidOccurrences: Set<Data> = []+    var retainedBytes = 0++    init(tasks: [TaskLinkTaskValue], occurrences: [TaskLinkOccurrenceValue], evidence: [TaskLinkRemovalValue],+         instant: Date, budget: TaskLinkGraphBudget) throws {+        try budget.check()+        for task in tasks {+            try budget.check()+            tasksById[task.id, default: []].append(task)+            retainedBytes += task.physicalKey.count + task.name.utf8.count + task.status.utf8.count + 16+            guard retainedBytes <= budget.maximumBytes else { throw TaskLinkGraphError.capacityExceeded }+        }+        for edge in occurrences {+            try budget.check()+            edgesById[edge.id, default: []].append(edge)+            incidence[edge.source, default: []].append(edge)+            if edge.target != edge.source { incidence[edge.target, default: []].append(edge) }+            equivalents[TaskLinkGraph.relation(edge), default: []].append(edge)+            retainedBytes += edge.physicalKey.count + edge.kind.utf8.count + 56+            guard retainedBytes <= budget.maximumBytes else { throw TaskLinkGraphError.capacityExceeded }+        }+        try recognize(evidence, instant: instant, budget: budget)+        guard retainedBytes <= budget.maximumBytes else { throw TaskLinkGraphError.capacityExceeded }+    }++    private mutating func recognize(+        _ evidence: [TaskLinkRemovalValue], instant: Date, budget: TaskLinkGraphBudget+    ) throws {+        var ids: [UUID: Int] = [:]+        for row in evidence { try budget.check(); ids[row.id, default: 0] += 1 }+        for row in evidence {+            try budget.check()+            retainedBytes += row.physicalKey.count + row.kind.utf8.count + row.occurrenceRevision.utf8.count + 88+            guard retainedBytes <= budget.maximumBytes else { throw TaskLinkGraphError.capacityExceeded }+            let elapsed = instant.timeIntervalSince(row.removedAt)+            let datesValid = elapsed.isFinite && elapsed >= 0+                && row.createdAt.timeIntervalSinceReferenceDate.isFinite+            if datesValid, elapsed >= TaskLinkGraph.evidenceLifetime { continue }+            availableRemovals[row.edgeId, default: []].append(row)+            let original = TaskLinkOccurrenceValue(physicalKey: row.physicalKey, id: row.edgeId,+                kind: row.kind, source: row.source, target: row.target, createdAt: row.createdAt)+            let valid = ids[row.id] == 1 && elapsed.isFinite && elapsed >= 0+                && row.createdAt.timeIntervalSinceReferenceDate.isFinite+                && (try? TaskLinkGraph.occurrenceRevision(original)) == row.occurrenceRevision+            if valid { recognizedRemovals[row.edgeId, default: []].append(row) } else {+                diagnostics.append(TaskLinkDiagnostic(code: "invalid_removal_evidence",+                                                      taskIds: [row.source, row.target],+                                                      edgeId: row.edgeId, physicalKey: row.physicalKey))+            }+        }+    }++    mutating func diagnoseOccurrences(budget: TaskLinkGraphBudget) throws {+        for edges in edgesById.values {+            for edge in edges {+                try budget.check()+                try diagnose(edge, budget: budget)+            }+        }+        for (id, matches) in tasksById where matches.count != 1 {+            try budget.check()+            diagnostics.append(TaskLinkDiagnostic(code: "ambiguous_endpoint", taskIds: [id],+                                                  edgeId: nil, physicalKey: Data()))+        }+        for (id, edges) in incidence {+            try budget.check()+            let duplicates = try edges.filter { try budget.check(); return $0.kind == "duplicate" && $0.source == id }+            if duplicates.count > 1 {+                for edge in duplicates { try budget.check(); add("duplicate_cardinality", edge: edge) }+            }+        }+    }++    private mutating func diagnose(_ edge: TaskLinkOccurrenceValue, budget: TaskLinkGraphBudget) throws {+        for id in [edge.source, edge.target] {+            if tasksById[id] == nil { add("missing_endpoint", edge: edge) } else if tasksById[id]?.count != 1 {+                add("ambiguous_endpoint", edge: edge)+            }+        }+        if edge.source == edge.target { add("self_link", edge: edge) }+        if !TaskLinkGraph.storedKinds.contains(edge.kind) { add("unknown_kind", edge: edge) }+        if !edge.createdAt.timeIntervalSinceReferenceDate.isFinite { add("malformed_date", edge: edge) }+        if edgesById[edge.id]?.count != 1 { add("occurrence_identity_collision", edge: edge) }+        if equivalents[TaskLinkGraph.relation(edge)]?.count != 1 {+            add("equivalent_occurrences", edge: edge)+        }+        if let removed = availableRemovals[edge.id], try removed.contains(where: {+            try budget.check()+            return $0.kind == edge.kind && $0.source == edge.source && $0.target == edge.target+                && $0.createdAt == edge.createdAt+        }) { add("active_removal_conflict", edge: edge) }+    }++    private mutating func add(_ code: String, edge: TaskLinkOccurrenceValue) {+        invalidOccurrences.insert(edge.physicalKey)+        diagnostics.append(TaskLinkDiagnostic(code: code, taskIds: [edge.source, edge.target],+                                              edgeId: edge.id, physicalKey: edge.physicalKey))+    }++    func assessment(+        id: UUID, matches: [TaskLinkTaskValue], cyclic: Set<UUID>, budget: TaskLinkGraphBudget+    ) throws -> TaskLinkBlockerAssessment {+        try budget.check()+        guard matches.count == 1, !cyclic.contains(id) else {+            return .invalid+        }+        var blocked = false+        for edge in incidence[id, default: []] {+            try budget.check()+            guard edge.kind == "dependency", edge.target == id else { continue }+            guard !invalidOccurrences.contains(edge.physicalKey), let source = tasksById[edge.source]?.first,+                  TaskLinkGraph.knownStatuses.contains(source.status) else { return .invalid }+            if source.status != "done" { blocked = true }+        }+        return blocked ? .blocked : .unblocked+    }+}
Transit/Transit/Services/TaskLinks/TaskLinkGraphValues.swift Changed +119 / -0
diff --git a/Transit/Transit/Services/TaskLinks/TaskLinkGraphValues.swift b/Transit/Transit/Services/TaskLinks/TaskLinkGraphValues.swiftnew file mode 100644index 00000000..adf98f4e--- /dev/null+++ b/Transit/Transit/Services/TaskLinks/TaskLinkGraphValues.swift@@ -0,0 +1,119 @@+import Foundation++/// Physical identity is independent of the imported domain UUID.+nonisolated struct TaskLinkTaskValue: Equatable, Sendable {+    let physicalKey: Data+    let id: UUID+    let name: String+    let status: String+}++nonisolated struct TaskLinkOccurrenceValue: Equatable, Sendable {+    let physicalKey: Data+    let id: UUID+    let kind: String+    let source: UUID+    let target: UUID+    let createdAt: Date+}++nonisolated struct TaskLinkRemovalValue: Equatable, Sendable {+    let physicalKey: Data+    let id: UUID+    let edgeId: UUID+    let kind: String+    let source: UUID+    let target: UUID+    let createdAt: Date+    let occurrenceRevision: String+    let removedAt: Date+}++nonisolated enum TaskLinkType: String, CaseIterable, Sendable {+    case blocks, blockedBy = "blocked-by", relatesTo = "relates-to"+    case introducedBy = "introduced-by", duplicateOf = "duplicate-of"++    func normalized(source: UUID, target: UUID) -> TaskLinkRelation {+        switch self {+        case .blocks: TaskLinkRelation(kind: "dependency", source: source, target: target)+        case .blockedBy: TaskLinkRelation(kind: "dependency", source: target, target: source)+        case .relatesTo:+            TaskLinkRelation(kind: "association",+                             source: source.uuidString < target.uuidString ? source : target,+                             target: source.uuidString < target.uuidString ? target : source)+        case .introducedBy: TaskLinkRelation(kind: "attribution", source: source, target: target)+        case .duplicateOf: TaskLinkRelation(kind: "duplicate", source: source, target: target)+        }+    }+}++nonisolated struct TaskLinkRelation: Hashable, Sendable {+    let kind: String+    let source: UUID+    let target: UUID+}++nonisolated enum TaskLinkBlockerAssessment: String, Sendable {+    case unblocked, blocked, invalid, unavailable+}++nonisolated struct TaskLinkDiagnostic: Equatable, Sendable {+    let code: String+    let taskIds: [UUID]+    let edgeId: UUID?+    let physicalKey: Data+}++nonisolated struct TaskLinkDuplicateResolution: Equatable, Sendable {+    let path: [UUID]+    let canonical: UUID?+    let diagnostic: String?+}++nonisolated struct TaskLinkGraphBudget: Sendable {+    let deadline: ContinuousClock.Instant+    let maximumBytes: Int+    let checkpoint: (@Sendable () throws -> Void)?++    init(deadline: ContinuousClock.Instant = .now.advanced(by: .seconds(5)),+         maximumBytes: Int = 16 * 1_024 * 1_024, checkpoint: (@Sendable () throws -> Void)? = nil) {+        self.deadline = deadline+        self.maximumBytes = maximumBytes+        self.checkpoint = checkpoint+    }++    func check() throws {+        guard ContinuousClock.now < deadline else { throw TaskLinkGraphError.deadlineExceeded }+        try checkpoint?()+    }+}++nonisolated enum TaskLinkGraphError: Error {+    case deadlineExceeded, capacityExceeded, invalidDelta, missingSource, ambiguousIdentity+    case invalidOccurrence, repairUnavailable, revisionConflict, invalidGraph, endpointPreconditions+}++nonisolated struct TaskLinkGraphView: Sendable {+    let tasks: [TaskLinkTaskValue]+    let occurrences: [TaskLinkOccurrenceValue]+    let removalEvidence: [TaskLinkRemovalValue]+    let evaluationInstant: Date+    let tasksById: [UUID: [TaskLinkTaskValue]]+    let occurrencesById: [UUID: [TaskLinkOccurrenceValue]]+    let incidence: [UUID: [TaskLinkOccurrenceValue]]+    let diagnostics: [TaskLinkDiagnostic]+    let cyclicTasks: Set<UUID>+    let blockers: [UUID: TaskLinkBlockerAssessment]+    let retainedBytes: Int+    let invalidOccurrences: Set<Data>+    let recognizedRemovals: [UUID: [TaskLinkRemovalValue]]++    func withRetainedBytes(_ bytes: Int) -> TaskLinkGraphView {+        TaskLinkGraphView(tasks: tasks, occurrences: occurrences, removalEvidence: removalEvidence,+            evaluationInstant: evaluationInstant, tasksById: tasksById, occurrencesById: occurrencesById,+            incidence: incidence, diagnostics: diagnostics, cyclicTasks: cyclicTasks, blockers: blockers,+            retainedBytes: bytes, invalidOccurrences: invalidOccurrences, recognizedRemovals: recognizedRemovals)+    }++    func assessment(for id: UUID) -> TaskLinkBlockerAssessment { blockers[id] ?? .unavailable }+}
Transit/Transit/Services/TaskLinks/TaskLinkNativeDetailState.swift Changed +39 / -0
diff --git a/Transit/Transit/Services/TaskLinks/TaskLinkNativeDetailState.swift b/Transit/Transit/Services/TaskLinks/TaskLinkNativeDetailState.swiftnew file mode 100644index 00000000..593fedb7--- /dev/null+++ b/Transit/Transit/Services/TaskLinks/TaskLinkNativeDetailState.swift@@ -0,0 +1,39 @@+import Foundation+import Observation++/// Value-only native observation; selected identity and generation own publication.+@MainActor @Observable final class TaskLinkNativeDetailState {+    private(set) var sourceID: UUID?+    private(set) var detail: TaskLinkSavedDetail?+    private(set) var problem: String?+    private var generation: UInt64 = 0++    func refresh(source: UUID, debounce: Duration = .zero,+                 provider: @escaping @MainActor (UUID) async throws -> TaskLinkSavedDetail) async {+        await refresh(source: source, wait: {+            if debounce > .zero { try await Task.sleep(for: debounce) }+        }, provider: provider)+    }++    /// Waiting belongs after invalidation, so an earlier capture cannot publish+    /// during a notification burst. The provider still captures the complete saved graph.+    func refresh(source: UUID, wait: @escaping @MainActor () async throws -> Void,+                 provider: @escaping @MainActor (UUID) async throws -> TaskLinkSavedDetail) async {+        guard !Task.isCancelled else { return }+        sourceID = source+        generation &+= 1+        let accepted = generation+        detail = nil+        problem = nil+        do {+            try await wait()+            guard !Task.isCancelled, generation == accepted, sourceID == source else { return }+            let observation = try await provider(source)+            guard !Task.isCancelled, generation == accepted, sourceID == source else { return }+            detail = observation+        } catch {+            guard !Task.isCancelled, generation == accepted, sourceID == source else { return }+            problem = "Saved relationships are unavailable until this task can be uniquely resolved."+        }+    }+}
Transit/Transit/Services/TaskLinks/TaskLinkNativeLabels.swift Changed +13 / -0
diff --git a/Transit/Transit/Services/TaskLinks/TaskLinkNativeLabels.swift b/Transit/Transit/Services/TaskLinks/TaskLinkNativeLabels.swiftnew file mode 100644index 00000000..6497b61e--- /dev/null+++ b/Transit/Transit/Services/TaskLinks/TaskLinkNativeLabels.swift@@ -0,0 +1,13 @@+/// Relationship wording is relative to the selected endpoint; raw stored kinds+/// stay in the graph and unknown kinds never acquire a recognized meaning.+nonisolated enum TaskLinkNativeLabels {+    static func title(kind: String, incoming: Bool) -> String {+        switch kind {+        case "dependency": incoming ? "Blocked by" : "Blocks"+        case "association": "Relates to"+        case "attribution": incoming ? "Introduces" : "Introduced by"+        case "duplicate": incoming ? "Duplicated by" : "Duplicate of"+        default: "Unknown relation"+        }+    }+}
Transit/Transit/Services/TaskLinks/TaskLinkNavigationResolver.swift Changed +20 / -0
diff --git a/Transit/Transit/Services/TaskLinks/TaskLinkNavigationResolver.swift b/Transit/Transit/Services/TaskLinks/TaskLinkNavigationResolver.swiftnew file mode 100644index 00000000..33e0eed5--- /dev/null+++ b/Transit/Transit/Services/TaskLinks/TaskLinkNavigationResolver.swift@@ -0,0 +1,20 @@+import Foundation+import SwiftData++/// Shared by click and window resolution. No first-match UUID navigation.+@MainActor enum TaskLinkNavigationResolver {+    static func resolve(_ id: UUID, in context: ModelContext) throws -> TransitTask? {+        let saved = ModelContext(context.container)+        saved.autosaveEnabled = false+        var descriptor = FetchDescriptor<TransitTask>(predicate: #Predicate { $0.id == id })+        descriptor.fetchLimit = 2+        descriptor.includePendingChanges = false+        let matches = try saved.fetch(descriptor)+        guard matches.count == 1, let identity = matches.first?.persistentModelID else { return nil }+        // Return a model owned by the caller's retained navigation context.+        guard let task = context.model(for: identity) as? TransitTask, task.id == id, !task.isDeleted else {+            return nil+        }+        return task+    }+}
Transit/Transit/Services/TaskLinks/TaskLinkPlan.swift Changed +145 / -0
diff --git a/Transit/Transit/Services/TaskLinks/TaskLinkPlan.swift b/Transit/Transit/Services/TaskLinks/TaskLinkPlan.swiftnew file mode 100644index 00000000..cfc0e4f5--- /dev/null+++ b/Transit/Transit/Services/TaskLinks/TaskLinkPlan.swift@@ -0,0 +1,145 @@+import Foundation++nonisolated enum TaskLinkChange: Equatable, Sendable {+    case add(type: TaskLinkType, target: UUID)+    case remove(edgeId: UUID, occurrenceRevision: String)+}++nonisolated struct TaskLinkPlannedAddition: Equatable, Sendable {+    let relation: TaskLinkRelation+}++nonisolated struct TaskLinkPlan: Sendable {+    let removals: [TaskLinkOccurrenceValue]+    let additions: [TaskLinkPlannedAddition]+    let affectedEndpoints: Set<UUID>+    var isNoOp: Bool { removals.isEmpty && additions.isEmpty }+}++extension TaskLinkPlan {+    /// Reference/selector validation runs after replay/key acceptance. Source revision+    /// is enforced by the ordinary task command before applying this plan.+    @MainActor+    // Selector cases share one exact affected-endpoint accumulator.+    // swiftlint:disable:next cyclomatic_complexity function_body_length+    static func validate(+        delta: [TaskLinkChange], source: UUID, preconditions: [UUID: String],+        revisions: [UUID: String], savedGraph: TaskLinkGraphView,+        budget: TaskLinkGraphBudget = TaskLinkGraphBudget()+    ) throws -> TaskLinkPlan {+        guard delta.count <= 50 else { throw TaskLinkGraphError.invalidDelta }+        guard savedGraph.tasksById[source]?.count == 1 else { throw TaskLinkGraphError.missingSource }+        var removals: [TaskLinkOccurrenceValue] = [], additions: [TaskLinkPlannedAddition] = []+        var affected: Set<UUID> = [], selected: Set<UUID> = []+        var removedRelations: Set<TaskLinkRelation> = []+        for change in delta {+            try budget.check()+            switch change {+            case let .remove(edgeId, revision):+                guard selected.insert(edgeId).inserted else { throw TaskLinkGraphError.invalidDelta }+                if let rows = savedGraph.occurrencesById[edgeId] {+                    guard rows.count == 1, let row = rows.first, row.source == source || row.target == source,+                          try TaskLinkGraph.occurrenceRevision(row) == revision else {+                        throw TaskLinkGraphError.invalidOccurrence+                    }+                    removals.append(row)+                    removedRelations.insert(TaskLinkGraph.relation(row))+                    let opposite = row.source == source ? row.target : row.source+                    if opposite != source {+                        try registerEndpoint(opposite, graph: savedGraph, affected: &affected, requireExisting: false)+                    }+                } else {+                    guard let rows = savedGraph.recognizedRemovals[edgeId], rows.count == 1,+                          let row = rows.first, row.source == source || row.target == source,+                          row.occurrenceRevision == revision else { throw TaskLinkGraphError.repairUnavailable }+                    removedRelations.insert(TaskLinkGraph.relation(TaskLinkOccurrenceValue(+                        physicalKey: row.physicalKey, id: row.edgeId, kind: row.kind, source: row.source,+                        target: row.target, createdAt: row.createdAt)))+                }+            case let .add(type, target):+                guard target != source else { throw TaskLinkGraphError.invalidGraph }+                let relation = type.normalized(source: source, target: target)+                let existing = try savedGraph.incidence[source, default: []].filter {+                    try budget.check()+                    return TaskLinkGraph.relation($0) == relation+                }+                if !existing.isEmpty {+                    guard existing.count == 1, let row = existing.first,+                          !savedGraph.invalidOccurrences.contains(row.physicalKey) else {+                        throw TaskLinkGraphError.invalidGraph+                    }+                    continue+                }+                guard !additions.contains(where: { $0.relation == relation }) else {+                    throw TaskLinkGraphError.invalidDelta+                }+                try registerEndpoint(target, graph: savedGraph, affected: &affected, requireExisting: true)+                additions.append(TaskLinkPlannedAddition(relation: relation))+            }+        }+        for change in delta {+            try budget.check()+            if case let .add(type, target) = change,+               removedRelations.contains(type.normalized(source: source, target: target)) {+                throw TaskLinkGraphError.invalidDelta+            }+        }+        guard Set(preconditions.keys) == affected else { throw TaskLinkGraphError.endpointPreconditions }+        for id in affected {+            try budget.check()+            guard let current = revisions[id], preconditions[id] == current else {+                throw TaskLinkGraphError.revisionConflict+            }+        }+        let plan = TaskLinkPlan(removals: removals, additions: additions, affectedEndpoints: affected)+        if delta.contains(where: { if case .add = $0 { true } else { false } }) {+            try validateProposed(plan, source: source, graph: savedGraph, budget: budget)+        }+        return plan+    }++    @MainActor+    private static func validateProposed(+        _ plan: TaskLinkPlan, source: UUID, graph: TaskLinkGraphView, budget: TaskLinkGraphBudget+    ) throws {+        let removed = Set(plan.removals.map(\.physicalKey))+        var rows = try graph.occurrences.filter { try budget.check(); return !removed.contains($0.physicalKey) }+        for addition in plan.additions {+            try budget.check()+            // Ephemeral validation identities never leave this pure proposed graph or enter the store.+            let id = UUID(), relation = addition.relation+            rows.append(TaskLinkOccurrenceValue(physicalKey: Data(id.uuidString.utf8), id: id,+                kind: relation.kind, source: relation.source, target: relation.target,+                createdAt: graph.evaluationInstant))+        }+        let proposed = try TaskLinkGraph.project(tasks: graph.tasks, occurrences: rows,+            removalEvidence: graph.removalEvidence, evaluationInstant: graph.evaluationInstant, budget: budget)+        let touched = plan.affectedEndpoints.union([source])+        for id in touched {+            try budget.check()+            guard proposed.assessment(for: id) != .invalid,+                  try TaskLinkGraph.duplicateResolution(for: id, in: proposed, budget: budget).diagnostic == nil else {+                throw TaskLinkGraphError.invalidGraph+            }+        }+        for diagnostic in proposed.diagnostics {+            try budget.check()+            // Unmatched malformed removal rows cannot authorize a retry; unrelated active incidence stays valid.+            if diagnostic.code != "invalid_removal_evidence", !Set(diagnostic.taskIds).isDisjoint(with: touched) {+                throw TaskLinkGraphError.invalidGraph+            }+        }+    }++    @MainActor+    private static func registerEndpoint(+        _ id: UUID, graph: TaskLinkGraphView, affected: inout Set<UUID>, requireExisting: Bool+    ) throws {+        guard let matches = graph.tasksById[id] else {+            if requireExisting { throw TaskLinkGraphError.invalidGraph }+            return+        }+        guard matches.count == 1 else { throw TaskLinkGraphError.ambiguousIdentity }+        affected.insert(id)+    }+}
Transit/Transit/Services/TaskLinks/TaskLinkService.swift Changed +78 / -0
diff --git a/Transit/Transit/Services/TaskLinks/TaskLinkService.swift b/Transit/Transit/Services/TaskLinks/TaskLinkService.swiftnew file mode 100644index 00000000..4be7359b--- /dev/null+++ b/Transit/Transit/Services/TaskLinks/TaskLinkService.swift@@ -0,0 +1,78 @@+import Foundation+import SwiftData++nonisolated struct TaskLinkSavedDetail: Sendable {+    let source: TaskLinkTaskValue+    let graph: TaskLinkGraphView+    let duplicateResolution: TaskLinkDuplicateResolution+}++/// Saved-only adapters never borrow UI models or save during read/preview.+@MainActor+final class TaskLinkService {+    private let container: ModelContainer++    init(container: ModelContainer) { self.container = container }++    /// A separate bounded owned context; never called by read, preview or graph apply.+    func cleanupExpiredEvidence(evaluationInstant: Date = Date(), limit: Int = 128,+                                budget: TaskLinkGraphBudget = TaskLinkGraphBudget()) throws -> Int {+        try TaskLinkEvidenceMaintenance.cleanup(container: container, instant: evaluationInstant,+                                               limit: limit, budget: budget)+    }++    func savedGraph(budget: TaskLinkGraphBudget = TaskLinkGraphBudget()) throws -> TaskLinkGraphView {+        let context = ModelContext(container)+        context.autosaveEnabled = false+        return try Self.graph(in: context, budget: budget)+    }++    func savedDetail(+        for source: UUID, budget: TaskLinkGraphBudget = TaskLinkGraphBudget()+    ) throws -> TaskLinkSavedDetail {+        let graph = try savedGraph(budget: budget)+        guard let matches = graph.tasksById[source], matches.count == 1, let task = matches.first else {+            throw TaskLinkGraphError.ambiguousIdentity+        }+        return try TaskLinkSavedDetail(source: task, graph: graph,+            duplicateResolution: TaskLinkGraph.duplicateResolution(for: source, in: graph, budget: budget))+    }++    /// The caller supplies a clean, fresh owned context for write validation.+    /// Capture uses the same context as the existing read fence when integrated there.+    static func graph(+        in context: ModelContext, capturedTasks: [TransitTask]? = nil, evaluationInstant: Date = Date(),+        budget: TaskLinkGraphBudget = TaskLinkGraphBudget()+    ) throws -> TaskLinkGraphView {+        try budget.check()+        var taskFetch = FetchDescriptor<TransitTask>()+        taskFetch.includePendingChanges = false+        var edgeFetch = FetchDescriptor<TaskLinkOccurrence>()+        edgeFetch.includePendingChanges = false+        var removalFetch = FetchDescriptor<TaskLinkRemovalEvidence>()+        removalFetch.includePendingChanges = false+        let population = try capturedTasks ?? context.fetch(taskFetch)+        let tasks = try population.map { task in+            try budget.check()+            return try TaskLinkTaskValue(physicalKey: key(task), id: task.id, name: task.name,+                                         status: task.statusRawValue)+        }+        let edges = try context.fetch(edgeFetch).map { row in+            try budget.check()+            return try TaskLinkOccurrenceValue(physicalKey: key(row), id: row.id, kind: row.kindRawValue,+                source: row.sourceTaskID, target: row.targetTaskID, createdAt: row.createdAt)+        }+        let removals = try context.fetch(removalFetch).map { row in+            try budget.check()+            return try TaskLinkRemovalValue(physicalKey: key(row), id: row.id, edgeId: row.edgeId,+                kind: row.kindRawValue, source: row.sourceTaskID, target: row.targetTaskID, createdAt: row.createdAt,+                occurrenceRevision: row.occurrenceRevision, removedAt: row.removedAt)+        }+        return try TaskLinkGraph.project(tasks: tasks, occurrences: edges, removalEvidence: removals,+                                         evaluationInstant: evaluationInstant, budget: budget)+    }++    private static func key(_ model: some PersistentModel) throws -> Data {+        try JSONEncoder().encode(model.persistentModelID)+    }+}
Transit/Transit/Services/TaskService.swift Changed +4 / -3
diff --git a/Transit/Transit/Services/TaskService.swift b/Transit/Transit/Services/TaskService.swiftindex 0c37e278..55fe4e92 100644--- a/Transit/Transit/Services/TaskService.swift+++ b/Transit/Transit/Services/TaskService.swift@@ -1,12 +1,12 @@ import Foundation import SwiftData- /// Coordinates task creation, status changes, and lookups. Uses StatusEngine /// for all status transitions and DisplayIDAllocator for display ID assignment. @MainActor @Observable final class TaskService {-     private let modelContext: ModelContext+    /// Read adapters create their own saved-only context; UI models never escape this seam.+    var savedReadContainer: ModelContainer { modelContext.container }     private let displayIDAllocator: DisplayIDAllocator     private let createSave: (ModelContext) throws -> Void     private let statusSave: (ModelContext) throws -> Void@@ -371,7 +371,7 @@ extension TaskService {     /// Re-resolves pinned UUIDs and validates immediately before inserting. No suspension or save by default.     @discardableResult     func applyTaskCreation(-        _ prepared: PreparedCreation,+        _ prepared: PreparedCreation, taskID: UUID? = nil,         save: ((ModelContext) throws -> Void)? = nil     ) throws -> TransitTask {         try Task.checkCancellation()@@ -391,6 +391,7 @@ extension TaskService {             name: prepared.name, description: prepared.description, type: prepared.type,             project: project, displayID: prepared.displayID, metadata: prepared.metadata, priority: prepared.priority         )+        if let taskID { task.id = taskID }         StatusEngine.initializeNewTask(task)         task.milestone = milestone         try modelContext.insertOrDelete(task, save: save ?? { _ in })
Transit/Transit/TransitApp.swift Changed +8 / -3
diff --git a/Transit/Transit/TransitApp.swift b/Transit/Transit/TransitApp.swiftindex 7f9b2108..59faf96d 100644--- a/Transit/Transit/TransitApp.swift+++ b/Transit/Transit/TransitApp.swift@@ -5,7 +5,6 @@ import SwiftUI #if os(iOS) import UIKit #endif- @main struct TransitApp: App { @@ -50,7 +49,8 @@ struct TransitApp: App {         self.syncManager = syncManager          let schema = Schema([-            Project.self, TransitTask.self, Comment.self, Milestone.self, SyncHeartbeat.self, MCPWriteReceipt.self+            Project.self, TransitTask.self, Comment.self, Milestone.self, SyncHeartbeat.self, MCPWriteReceipt.self,+            TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self         ])         let config: ModelConfiguration         if mode != .production {@@ -89,6 +89,7 @@ struct TransitApp: App {         }          let context = container.mainContext+        TaskLinkEvidenceMaintenance.atStartup(container: container, mode: mode, persistence: persistence)         let allocators = AppDisplayIDAllocators.make(mode: mode, syncActive: cloudSyncActive)         let allocator = allocators.tasks         self.displayIDAllocator = allocator@@ -169,7 +170,8 @@ struct TransitApp: App {             commentService: commentService, milestoneService: milestoneService,             maintenanceService: maintenanceService, settings: mcpSettings,             persistence: persistence, taskQuerySnapshots: reads.snapshots, writeCoordinator: writeCoordinator,-            readService: reads, readCoordinator: readCoordinator, batchContainer: container+            readService: reads, readCoordinator: readCoordinator, batchContainer: container,+            taskLinkWriteAdapter: TaskLinkWriteAdapter(taskAllocator: allocator, milestoneAllocator: milestoneAllocator)         )         self.mcpServer = MCPServer(toolHandler: mcpToolHandler, readCoordinator: readCoordinator)         #endif@@ -288,6 +290,9 @@ struct TransitApp: App {         #endif     } +}++extension TransitApp {     // MARK: - Shared Environment      private func withCoreEnvironments<V: View>(_ view: V) -> some View {
Transit/Transit/UITestScenario.swift Changed +29 / -0
diff --git a/Transit/Transit/UITestScenario.swift b/Transit/Transit/UITestScenario.swiftindex e35c162c..28444eef 100644--- a/Transit/Transit/UITestScenario.swift+++ b/Transit/Transit/UITestScenario.swift@@ -5,6 +5,8 @@ enum UITestScenario: String {     case empty     case board     case duplicateDisplayIds+    case taskLinks+    case taskLinksAmbiguous      // swiftlint:disable:next function_body_length     func seed(into ctx: ModelContext) {@@ -14,6 +16,9 @@ enum UITestScenario: String {         case .duplicateDisplayIds:             seedDuplicateDisplayIds(into: ctx)             return+        case .taskLinks, .taskLinksAmbiguous:+            seedTaskLinks(into: ctx, ambiguous: self == .taskLinksAmbiguous)+            return         case .board:             break         }@@ -74,6 +79,30 @@ enum UITestScenario: String {         betaReview.milestone = betaV1     } +    private func seedTaskLinks(into context: ModelContext, ambiguous: Bool) {+        let project = Project(name: "Relationships", description: "Synthetic relationship UI fixture",+                              gitRepo: nil, colorHex: "#0A84FF")+        context.insert(project)+        let source = TransitTask(name: "Linked Source", type: .feature, project: project, displayID: .permanent(1))+        source.id = UUID(uuidString: "00000000-0000-0000-0000-000000173401")!+        source.statusRawValue = TaskStatus.inProgress.rawValue+        let target = TransitTask(name: "Linked Target", type: .feature, project: project, displayID: .permanent(2))+        target.id = UUID(uuidString: "00000000-0000-0000-0000-000000173402")!+        context.insert(source)+        context.insert(target)+        context.insert(TaskLinkOccurrence(id: UUID(), kindRawValue: "association", sourceTaskID: source.id,+                                          targetTaskID: target.id, createdAt: Date()))+        if ambiguous {+            let collision = TransitTask(name: "Collision", type: .feature, project: project, displayID: .permanent(3))+            collision.id = target.id+            collision.statusRawValue = TaskStatus.abandoned.rawValue+            context.insert(collision)+        }+        do { try context.save() } catch {+            preconditionFailure("Could not save synthetic relationship UI fixture: \(error)")+        }+    }+     /// Seeds duplicate-displayId data exercised by `DataMaintenanceUITests`.     /// Includes both a duplicate task pair and a duplicate milestone pair at     /// the SAME display ID number (T-5 and M-5) — this matches T-1062's
Transit/Transit/Views/TaskDetail/TaskDetailView.swift Changed +32 / -7
diff --git a/Transit/Transit/Views/TaskDetail/TaskDetailView.swift b/Transit/Transit/Views/TaskDetail/TaskDetailView.swiftindex a8b49be6..0e10228b 100644--- a/Transit/Transit/Views/TaskDetail/TaskDetailView.swift+++ b/Transit/Transit/Views/TaskDetail/TaskDetailView.swift@@ -5,6 +5,9 @@ struct TaskDetailView: View {     let task: TransitTask     var dismissAll: () -> Void     var onEdit: (() -> Void)?+    var embeddedNavigation: Bool+    @Environment(\.openWindow) private var openWindow+    @State private var linkedTask: TransitTask?     @Environment(TaskService.self) private var taskService     @Environment(\.dismiss) private var dismiss     @Environment(\.resolvedTheme) private var resolvedTheme@@ -15,21 +18,19 @@ struct TaskDetailView: View {     init(         task: TransitTask,         dismissAll: @escaping () -> Void,-        onEdit: (() -> Void)? = nil+        onEdit: (() -> Void)? = nil,+        embeddedNavigation: Bool = false     ) {         self.task = task         self.dismissAll = dismissAll         self.onEdit = onEdit+        self.embeddedNavigation = embeddedNavigation         _comments = Query(CommentService.descriptor(for: task.id))     }      var body: some View {-        NavigationStack {-            #if os(macOS)-            macOSDetail-            #else-            iOSDetail-            #endif+        Group {+            if embeddedNavigation { detailContent } else { NavigationStack { detailContent } }         }         #if os(iOS)         .presentationDetents([.medium, .large])@@ -41,6 +42,24 @@ struct TaskDetailView: View {         }     } +    @ViewBuilder private var detailContent: some View {+        #if os(macOS)+        macOSDetail+        #else+        iOSDetail+        #endif+    }++    private var relationships: some View {+        TaskLinksSection(taskID: task.id) { destination in+            #if os(macOS)+            openWindow(id: "task-detail", value: destination.id)+            #else+            linkedTask = destination+            #endif+        }+    }+     // MARK: - iOS Layout      #if os(iOS)@@ -49,9 +68,13 @@ struct TaskDetailView: View {             iOSDetailSection             iOSDescriptionSection             MetadataSection(metadata: .constant(task.metadata), isEditing: false)+            Section("Relationships") { relationships }             CommentsSection(task: task, comments: comments)             iOSActionSection         }+        .navigationDestination(item: $linkedTask) { destination in+            TaskDetailView(task: destination, dismissAll: dismissAll, embeddedNavigation: true)+        }         .navigationTitle(task.displayID.formatted)         .navigationBarTitleDisplayMode(.inline)         .toolbar { detailToolbar }@@ -170,6 +193,8 @@ struct TaskDetailView: View {                     MetadataSection(metadata: .constant(task.metadata), isEditing: false)                 } +                LiquidGlassSection(title: "Relationships") { relationships }+                 CommentsSection(task: task, comments: comments)                  LiquidGlassSection(title: "Actions") {
Transit/Transit/Views/TaskDetail/TaskDetailWindowView.swift Changed +1 / -5
diff --git a/Transit/Transit/Views/TaskDetail/TaskDetailWindowView.swift b/Transit/Transit/Views/TaskDetail/TaskDetailWindowView.swiftindex 13233ac1..3786bbed 100644--- a/Transit/Transit/Views/TaskDetail/TaskDetailWindowView.swift+++ b/Transit/Transit/Views/TaskDetail/TaskDetailWindowView.swift@@ -11,11 +11,7 @@ struct TaskDetailWindowView: View {     @State private var isEditing = false      private var task: TransitTask? {-        var descriptor = FetchDescriptor<TransitTask>(-            predicate: #Predicate { $0.id == taskID }-        )-        descriptor.fetchLimit = 1-        return try? modelContext.fetch(descriptor).first+        try? TaskLinkNavigationResolver.resolve(taskID, in: modelContext)     }      var body: some View {
Transit/Transit/Views/TaskDetail/TaskLinksSection.swift Changed +93 / -0
diff --git a/Transit/Transit/Views/TaskDetail/TaskLinksSection.swift b/Transit/Transit/Views/TaskDetail/TaskLinksSection.swiftnew file mode 100644index 00000000..587880f1--- /dev/null+++ b/Transit/Transit/Views/TaskDetail/TaskLinksSection.swift@@ -0,0 +1,93 @@+import CoreData+import SwiftData+import SwiftUI++struct TaskLinksSection: View {+    let taskID: UUID+    let onSelect: (TransitTask) -> Void+    @Environment(\.modelContext) private var context+    @State private var state = TaskLinkNativeDetailState()+    @State private var refreshVersion: UInt64 = 0+    @State private var navigationProblem: String?++    var body: some View {+        VStack(alignment: .leading, spacing: 8) {+            Text("Saved relationships")+                .font(.caption).foregroundStyle(.secondary)+                .accessibilityIdentifier("task-links.observation.\(taskID.uuidString)")+            if let detail = state.detail {+                content(detail)+            } else {+                Text(state.problem ?? "Loading saved relationships…").foregroundStyle(.secondary)+            }+            if let navigationProblem { Text(navigationProblem).foregroundStyle(.secondary) }+        }+        .task(id: RefreshKey(source: taskID, version: refreshVersion)) {+            let service = TaskLinkService(container: context.container)+            let debounce: Duration = state.sourceID == taskID ? .milliseconds(100) : .zero+            await state.refresh(source: taskID, debounce: debounce) { source in+                try Task.checkCancellation()+                return try service.savedDetail(for: source, budget: TaskLinkGraphBudget(checkpoint: {+                    try Task.checkCancellation()+                }))+            }+        }+        .onReceive(NotificationCenter.default.publisher(for: ModelContext.didSave)) { _ in refreshVersion &+= 1 }+        .onReceive(NotificationCenter.default.publisher(for: .NSPersistentStoreRemoteChange)) { _ in+            refreshVersion &+= 1+        }+    }++    @ViewBuilder private func content(_ detail: TaskLinkSavedDetail) -> some View {+        let rows = detail.graph.incidence[taskID, default: []]+        Text("Blockers: \(detail.graph.assessment(for: taskID).rawValue.capitalized)")+        if rows.isEmpty { Text("No recorded relationships").foregroundStyle(.secondary) }+        ForEach(rows, id: \.physicalKey) { row in+            relationship(row, graph: detail.graph)+        }+        if let canonical = detail.duplicateResolution.canonical, canonical != taskID {+            Text("Canonical task: \(canonical.uuidString)").font(.caption)+        }+        if let diagnostic = detail.duplicateResolution.diagnostic {+            Text(diagnostic.replacingOccurrences(of: "_", with: " ").capitalized).foregroundStyle(.secondary)+        }+        ForEach(Array(detail.graph.diagnostics.enumerated()), id: \.offset) { _, diagnostic in+            if diagnostic.taskIds.contains(taskID) {+                Text(diagnostic.code.replacingOccurrences(of: "_", with: " ").capitalized)+                    .foregroundStyle(.secondary)+                    .accessibilityIdentifier("task-links.diagnostic.\(diagnostic.code)")+            }+        }+    }++    @ViewBuilder private func relationship(_ row: TaskLinkOccurrenceValue, graph: TaskLinkGraphView) -> some View {+        let incoming = row.target == taskID+        let target = incoming ? row.source : row.target+        let matches = graph.tasksById[target, default: []]+        let title = TaskLinkNativeLabels.title(kind: row.kind, incoming: incoming)+        if matches.count == 1, let value = matches.first {+            Button {+                do {+                    guard let selected = try TaskLinkNavigationResolver.resolve(target, in: context) else {+                        navigationProblem = "This saved destination is missing or ambiguous."+                        refreshVersion &+= 1+                        return+                    }+                    navigationProblem = nil+                    onSelect(selected)+                } catch { navigationProblem = "This saved destination cannot be resolved." }+            } label: {+                VStack(alignment: .leading) {+                    Text("\(title): \(value.name)")+                    Text("\(incoming ? "Incoming" : "Outgoing") · \(target.uuidString)")+                        .font(.caption).foregroundStyle(.secondary)+                }+            }+            .accessibilityIdentifier("task-links.target.\(target.uuidString)")+        } else {+            Text("\(title): Unresolved \(target.uuidString)").foregroundStyle(.secondary)+        }+    }++    private struct RefreshKey: Hashable { let source: UUID; let version: UInt64 }+}
Transit/TransitTests/MCPBatchTaskCoordinatorDurabilityTests.swift Changed +2 / -1
diff --git a/Transit/TransitTests/MCPBatchTaskCoordinatorDurabilityTests.swift b/Transit/TransitTests/MCPBatchTaskCoordinatorDurabilityTests.swiftindex 7299ac4c..7c98dd6f 100644--- a/Transit/TransitTests/MCPBatchTaskCoordinatorDurabilityTests.swift+++ b/Transit/TransitTests/MCPBatchTaskCoordinatorDurabilityTests.swift@@ -224,7 +224,8 @@ struct MCPBatchTaskCoordinatorDurabilityTests {         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 }+                    _ = try MCPRecordSnapshot.task(fixture.tasks[1], incidence: []) { _ in+                        throw Fixture.Fault.injected }                 }             }         }
Transit/TransitTests/MCPBatchTaskCoordinatorFixture.swift Changed +2 / -1
diff --git a/Transit/TransitTests/MCPBatchTaskCoordinatorFixture.swift b/Transit/TransitTests/MCPBatchTaskCoordinatorFixture.swiftindex 9196a8fa..8295bf72 100644--- a/Transit/TransitTests/MCPBatchTaskCoordinatorFixture.swift+++ b/Transit/TransitTests/MCPBatchTaskCoordinatorFixture.swift@@ -54,7 +54,8 @@ import Testing      static func owner(_ url: URL) throws -> TestModelContainer {         let schema = Schema([Project.self, TransitTask.self, Transit.Comment.self, Milestone.self,-                             SyncHeartbeat.self, MCPWriteReceipt.self])+                             SyncHeartbeat.self, MCPWriteReceipt.self,+                             TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self])         return try TestModelContainer(schema: schema, configurations: [ModelConfiguration(             "Task9", schema: schema, url: url, cloudKitDatabase: .none)])     }
Transit/TransitTests/MCPBatchTaskPreviewFixture.swift Changed +2 / -1
diff --git a/Transit/TransitTests/MCPBatchTaskPreviewFixture.swift b/Transit/TransitTests/MCPBatchTaskPreviewFixture.swiftindex 6fc09a21..4c8e6282 100644--- a/Transit/TransitTests/MCPBatchTaskPreviewFixture.swift+++ b/Transit/TransitTests/MCPBatchTaskPreviewFixture.swift@@ -82,7 +82,8 @@ import Testing      static func diskOwner(_ url: URL) throws -> TestModelContainer {         let schema = Schema([Project.self, TransitTask.self, Comment.self, Milestone.self,-                             SyncHeartbeat.self, MCPWriteReceipt.self])+                             SyncHeartbeat.self, MCPWriteReceipt.self,+                             TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self])         let configuration = ModelConfiguration(schema: schema, url: url, cloudKitDatabase: .none)         let owner = try TestModelContainer(schema: schema, configurations: [configuration])         owner.context.autosaveEnabled = false
Transit/TransitTests/MCPBatchTaskSafetyFixture.swift Changed +2 / -1
diff --git a/Transit/TransitTests/MCPBatchTaskSafetyFixture.swift b/Transit/TransitTests/MCPBatchTaskSafetyFixture.swiftindex ef54e28f..03b310e1 100644--- a/Transit/TransitTests/MCPBatchTaskSafetyFixture.swift+++ b/Transit/TransitTests/MCPBatchTaskSafetyFixture.swift@@ -51,7 +51,8 @@ import Testing      static func diskOwner(at url: URL) throws -> TestModelContainer {         let schema = Schema([Project.self, TransitTask.self, Comment.self, Milestone.self,-                             SyncHeartbeat.self, MCPWriteReceipt.self])+                             SyncHeartbeat.self, MCPWriteReceipt.self,+                             TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self])         let configuration = ModelConfiguration(schema: schema, url: url, cloudKitDatabase: .none)         let result = try TestModelContainer(schema: schema, configurations: [configuration])         result.context.autosaveEnabled = false
Transit/TransitTests/MCPDuplicateTaskDisplayIDTests.swift Changed +1 / -0
diff --git a/Transit/TransitTests/MCPDuplicateTaskDisplayIDTests.swift b/Transit/TransitTests/MCPDuplicateTaskDisplayIDTests.swiftindex 8b75a40a..4e43752b 100644--- a/Transit/TransitTests/MCPDuplicateTaskDisplayIDTests.swift+++ b/Transit/TransitTests/MCPDuplicateTaskDisplayIDTests.swift@@ -109,6 +109,7 @@ struct MCPDuplicateTaskDisplayIDTests {     @Test func queryTasksReportsDuplicateDisplayID() async throws {         let env = try MCPTestHelpers.makeEnv()         makeDuplicatePair(in: env.context, displayId: 42)+        try env.context.save()          let response = await env.handler.handle(MCPTestHelpers.toolCallRequest(             tool: "query_tasks",
Transit/TransitTests/MCPFallbackStorageRejectionTests.swift Changed +1 / -0
diff --git a/Transit/TransitTests/MCPFallbackStorageRejectionTests.swift b/Transit/TransitTests/MCPFallbackStorageRejectionTests.swiftindex 9c61db6c..46c56639 100644--- a/Transit/TransitTests/MCPFallbackStorageRejectionTests.swift+++ b/Transit/TransitTests/MCPFallbackStorageRejectionTests.swift@@ -116,6 +116,7 @@ struct MCPFallbackStorageRejectionTests {     func readToolsStillWork() async throws {         let env = try makeEnv()         seedProjectAndTask(in: env.context)+        try env.context.save()          let tasks = await env.handler.handle(             MCPTestHelpers.toolCallRequest(
Transit/TransitTests/MCPReadCaptureBuilderTests.swift Changed +2 / -1
diff --git a/Transit/TransitTests/MCPReadCaptureBuilderTests.swift b/Transit/TransitTests/MCPReadCaptureBuilderTests.swiftindex b8ad1d65..9ec5f5bf 100644--- a/Transit/TransitTests/MCPReadCaptureBuilderTests.swift+++ b/Transit/TransitTests/MCPReadCaptureBuilderTests.swift@@ -190,7 +190,8 @@ struct MCPReadCaptureBuilderTests {      private func diskFixture() throws -> TestModelContainer {         let schema = Schema([Project.self, TransitTask.self, Comment.self, Milestone.self,-                             SyncHeartbeat.self, MCPWriteReceipt.self])+                             SyncHeartbeat.self, MCPWriteReceipt.self,+                             TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self])         let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)         try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)         let config = ModelConfiguration(schema: schema, url: directory.appendingPathComponent("fixture.store"),
Transit/TransitTests/MCPReadServiceTests.swift Changed +1 / -1
diff --git a/Transit/TransitTests/MCPReadServiceTests.swift b/Transit/TransitTests/MCPReadServiceTests.swiftindex 5e142050..028db1d2 100644--- a/Transit/TransitTests/MCPReadServiceTests.swift+++ b/Transit/TransitTests/MCPReadServiceTests.swift@@ -292,7 +292,7 @@ extension MCPReadServiceTests {                 let values = try context.fetch(FetchDescriptor<TransitTask>())                 let corrupt = try #require(values.first { $0.permanentDisplayId == 2 })                 corrupt.creationDate = Date(timeIntervalSinceReferenceDate: .nan)-                #expect(throws: (any Error).self) { try MCPRecordSnapshot.task(corrupt) { _ in [] } }+                #expect(throws: (any Error).self) { try MCPRecordSnapshot.task(corrupt, incidence: []) { _ in [] } }                 return values             })         let service = MCPReadService(source: Source(fixture, builder: builder), monitor: MCPImportEvidenceMonitor(
Transit/TransitTests/MCPRecordRevisionTests.swift Changed +7 / -5
diff --git a/Transit/TransitTests/MCPRecordRevisionTests.swift b/Transit/TransitTests/MCPRecordRevisionTests.swiftindex a13df700..6a164fb0 100644--- a/Transit/TransitTests/MCPRecordRevisionTests.swift+++ b/Transit/TransitTests/MCPRecordRevisionTests.swift@@ -28,7 +28,7 @@ struct MCPRecordRevisionTests {             copy.creationDate = task.creationDate             copy.lastStatusChangeDate = task.lastStatusChangeDate             change(copy)-            let changed = try MCPRecordSnapshot.task(copy) { _ in [] }+            let changed = try MCPRecordSnapshot.task(copy, incidence: []) { _ in [] }             #expect(changed.revision != baseline.revision)         }         task.name = "changed"@@ -46,12 +46,14 @@ struct MCPRecordRevisionTests {         let task = TransitTask(name: "Task", type: .feature, project: project, displayID: .provisional)         let first = Transit.Comment(content: "one", authorName: "A", isAgent: true, task: task)         let second = Transit.Comment(content: "two", authorName: "B", isAgent: false, task: task)-        let snapshot = try MCPRecordSnapshot.task(task) { _ in [first, second] }-        #expect(snapshot.revision == (try MCPRecordSnapshot.task(task) { _ in [second, first] }.revision))+        let snapshot = try MCPRecordSnapshot.task(task, incidence: []) { _ in [first, second] }+        let reordered = try MCPRecordSnapshot.task(task, incidence: []) { _ in [second, first] }+        #expect(snapshot.revision == reordered.revision)         first.content = "changed"-        #expect(snapshot.revision != (try MCPRecordSnapshot.task(task) { _ in [first, second] }.revision))+        let changed = try MCPRecordSnapshot.task(task, incidence: []) { _ in [first, second] }+        #expect(snapshot.revision != changed.revision)         #expect(throws: CocoaError.self) {-            try MCPRecordSnapshot.task(task) { _ in throw CocoaError(.fileReadUnknown) }+            try MCPRecordSnapshot.task(task, incidence: []) { _ in throw CocoaError(.fileReadUnknown) }         }         #expect((snapshot.record["revision"] as? String) == snapshot.revision)     }
Transit/TransitTests/MCPTaskQueryFailureTests.swift Changed +9 / -0
diff --git a/Transit/TransitTests/MCPTaskQueryFailureTests.swift b/Transit/TransitTests/MCPTaskQueryFailureTests.swiftindex f236b24f..d425156e 100644--- a/Transit/TransitTests/MCPTaskQueryFailureTests.swift+++ b/Transit/TransitTests/MCPTaskQueryFailureTests.swift@@ -1,5 +1,6 @@ #if os(macOS) import Foundation+import SwiftData import Testing @testable import Transit @@ -41,6 +42,10 @@ struct MCPTaskQueryFailureTests {         first.id = UUID(uuidString: "00000000-0000-0000-0000-000000000001")!         second.id = UUID(uuidString: "00000000-0000-0000-0000-000000000002")!         comments.values = [second, first]+        env.context.insert(task)+        env.context.insert(first)+        env.context.insert(second)+        try env.context.save()         let response = await env.handler.handle(MCPTestHelpers.toolCallRequest(             tool: "query_tasks", arguments: [                 "displayIds": [42, 42, -1], "detailLevel": "summary", "includeComments": true, "limit": 1@@ -84,6 +89,8 @@ struct MCPTaskQueryFailureTests {         tasks.values = (0..<2).map {             TransitTask(name: "Task \($0)", type: .chore, project: project, displayID: .provisional)         }+        for task in tasks.values { env.context.insert(task) }+        try env.context.save()         comments.shouldFail = true         let noComments = await env.handler.handle(MCPTestHelpers.toolCallRequest(             tool: "query_tasks", arguments: ["detailLevel": "summary", "includeComments": false, "limit": 1]@@ -114,6 +121,8 @@ struct MCPTaskQueryFailureTests {             TransitTask(name: "B", type: .bug, project: project, displayID: .permanent(42)),             TransitTask(name: "C", type: .bug, project: project, displayID: .permanent(43))         ]+        for task in tasks.values { env.context.insert(task) }+        try env.context.save()         let response = await env.handler.handle(MCPTestHelpers.toolCallRequest(             tool: "query_tasks", arguments: [                 "displayIds": [42, 43, 999], "detailLevel": "summary", "includeComments": false, "limit": 100
Transit/TransitTests/MCPTaskQuerySelectorPrecedenceTests.swift Changed +42 / -0
diff --git a/Transit/TransitTests/MCPTaskQuerySelectorPrecedenceTests.swift b/Transit/TransitTests/MCPTaskQuerySelectorPrecedenceTests.swiftnew file mode 100644index 00000000..9107af9f--- /dev/null+++ b/Transit/TransitTests/MCPTaskQuerySelectorPrecedenceTests.swift@@ -0,0 +1,42 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPTaskQuerySelectorPrecedenceTests {+    private struct Failure: Error {}+    private final class FailingProjects: ModelFetching {+        private(set) var calls = 0+        func fetch<T: PersistentModel>(_ descriptor: FetchDescriptor<T>) throws -> [T] {+            calls += 1+            throw Failure()+        }+    }++    @Test(arguments: [0, 1, 2])+    func invalidOrBlankProjectSelectorsNeverInvokeStorageHook(mode: Int) async throws {+        let projects = FailingProjects()+        let env = try MCPTestHelpers.makeEnv(projectFetcher: projects)+        var arguments: [String: Any] = ["detailLevel": "summary", "includeComments": false, "limit": 100]+        switch mode {+        case 0: arguments.merge(["projectId": "not-a-uuid", "project": "Alpha"]) { _, new in new }+        case 1: arguments.merge(["projectId": UUID().uuidString, "project": 42]) { _, new in new }+        default: arguments["project"] = " \n\t "+        }+        let response = await env.handler.handle(MCPTestHelpers.toolCallRequest(+            tool: "query_tasks", arguments: arguments))+        #expect(projects.calls == 0)+        if mode == 2 {+            #expect(try !MCPTestHelpers.isError(response))+            #expect(try MCPTestHelpers.decodeQueryResults(response).isEmpty)+        } else {+            let result = try MCPTestHelpers.decodeResult(response)+            #expect((result["error"] as? [String: String])?["code"] == "INVALID_INPUT")+            #expect(try MCPTestHelpers.queryErrorMessage(response) == (mode == 0+                ? "Invalid projectId: expected a UUID string" : "project must be a string"))+        }+    }+}+#endif
Transit/TransitTests/MCPTaskQueryTests.swift Changed +1 / -0
diff --git a/Transit/TransitTests/MCPTaskQueryTests.swift b/Transit/TransitTests/MCPTaskQueryTests.swiftindex ebaa0b0b..0bd42377 100644--- a/Transit/TransitTests/MCPTaskQueryTests.swift+++ b/Transit/TransitTests/MCPTaskQueryTests.swift@@ -50,6 +50,7 @@ struct MCPTaskQueryTests {         let task = TransitTask(name: "Unallocated", type: .bug, project: project, displayID: .provisional)         task.metadata = ["branch": "test"]         env.context.insert(task)+        try env.context.save()         let rawID = task.id.uuidString.lowercased()         let page = try MCPTestHelpers.decodeResult(await call(env, [             "taskIds": [rawID, UUID().uuidString, rawID], "detailLevel": "full",
Transit/TransitTests/MCPWritePersistenceProbeTests.swift Changed +2 / -1
diff --git a/Transit/TransitTests/MCPWritePersistenceProbeTests.swift b/Transit/TransitTests/MCPWritePersistenceProbeTests.swiftindex d87ae7d9..19510823 100644--- a/Transit/TransitTests/MCPWritePersistenceProbeTests.swift+++ b/Transit/TransitTests/MCPWritePersistenceProbeTests.swift@@ -7,7 +7,8 @@ import Testing struct MCPWritePersistenceProbeTests {     private var schema: Schema {         Schema([Project.self, TransitTask.self, Comment.self, Milestone.self,-                SyncHeartbeat.self, MCPWriteReceipt.self])+                SyncHeartbeat.self, MCPWriteReceipt.self,+                TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self])     }      private func diskFixture(at url: URL, writable: Bool = true) throws -> TestModelContainer {
Transit/TransitTests/NumericDisplayIdParsingTests.swift Changed +2 / -0
diff --git a/Transit/TransitTests/NumericDisplayIdParsingTests.swift b/Transit/TransitTests/NumericDisplayIdParsingTests.swiftindex d79bbda4..0970bb40 100644--- a/Transit/TransitTests/NumericDisplayIdParsingTests.swift+++ b/Transit/TransitTests/NumericDisplayIdParsingTests.swift@@ -164,6 +164,7 @@ struct NumericDisplayIdMCPTests {         )         StatusEngine.initializeNewTask(task)         env.context.insert(task)+        try env.context.save()          let response = await env.handler.handle(             MCPTestHelpers.toolCallRequest(@@ -261,6 +262,7 @@ struct NumericDisplayIdMCPTests {         StatusEngine.initializeNewTask(task)         task.milestone = milestone         env.context.insert(task)+        try env.context.save()          let response = await env.handler.handle(             MCPTestHelpers.toolCallRequest(
Transit/TransitTests/TaskLinkClosedStoreMigrationTests.swift Changed +92 / -0
diff --git a/Transit/TransitTests/TaskLinkClosedStoreMigrationTests.swift b/Transit/TransitTests/TaskLinkClosedStoreMigrationTests.swiftnew file mode 100644index 00000000..826324e8--- /dev/null+++ b/Transit/TransitTests/TaskLinkClosedStoreMigrationTests.swift@@ -0,0 +1,92 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++/// One stage per test-host process. The external runner proves each preceding+/// host exited before starting another; this test never launches child tests.+@MainActor @Suite(.serialized)+struct TaskLinkClosedStoreMigrationTests {+    @Test(.enabled(if: ProcessInfo.processInfo.environment["T1734_CLOSED_STAGE"] != nil))+    func closedStoreStage() throws {+        let environment = ProcessInfo.processInfo.environment+        let stage = try #require(environment["T1734_CLOSED_STAGE"])+        _ = try #require(["seed", "legacy", "upgrade", "reopen"].contains(stage))+        let token = try #require(environment["T1734_CLOSED_TOKEN"].flatMap(UUID.init(uuidString:)))+        let root = try guardedRoot(token: token, stage: stage)+        let manager = FileManager.default+        let manifest = root.appendingPathComponent("original.json")+        let observation = root.appendingPathComponent("\(stage).json")+        _ = try #require(!manager.fileExists(atPath: observation.path))+        let isSeed = stage == "seed"+        _ = try #require(isSeed ? !manager.fileExists(atPath: root.path)+                               : manager.fileExists(atPath: manifest.path))+        let isCurrent = stage == "upgrade" || stage == "reopen"+        let schema: Schema? = isCurrent ? try TestModelContainer().container.schema : nil+        let fixture = try TaskLinkPreFeatureDiskFixture(directory: root, schema: schema, seed: isSeed)+        let original = isSeed ? try fixture.savedFields(in: fixture.owner.context) : nil+        if isSeed { try fixture.owner.context.save() }+        let bytes = try fixture.savedFields(in: fixture.owner.context)+        if isSeed {+            let expected = try #require(original)+            _ = try #require(bytes == expected)+            try bytes.write(to: manifest, options: .withoutOverwriting)+        } else {+            let expected = try Data(contentsOf: manifest)+            _ = try #require(bytes == expected)+        }+        let names = Set(fixture.owner.container.schema.entities.map(\.name))+        let missing = Set(["TaskLinkOccurrence", "TaskLinkRemovalEvidence"]).subtracting(names).sorted()+        let evidence: [String: Any] = [+            "stage": stage, "token": token.uuidString, "pid": ProcessInfo.processInfo.processIdentifier,+            "root": root.path, "store": fixture.storeURL.path, "rawFieldsPreserved": true,+            "schemaEntities": names.sorted(), "missingLinkEntities": missing,+            "cloudKit": "none", "closedStoreProvedByThisProcess": false+        ]+        try JSONSerialization.data(withJSONObject: evidence, options: [.sortedKeys])+            .write(to: observation, options: .withoutOverwriting)+        // Upgrade uses the actual default test schema. Absence is behavioral+        // RED; neither a fabricated candidate schema nor missing Swift types.+        if isCurrent { _ = try #require(missing.isEmpty) }+        _ = try #require(!fixture.owner.context.hasChanges)+    }+    private func guardedRoot(token: UUID, stage: String) throws -> URL {+        let home = URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)+        let expectedSuffix = "/Library/Containers/me.nore.ig.Transit.development/Data"+        _ = try #require(home.path.hasSuffix(expectedSuffix))+        let root = home.appendingPathComponent("tmp/T1734Closed-\(token.uuidString)", isDirectory: true)+        let manager = FileManager.default+        let manifest = root.appendingPathComponent("original.json")+        let observation = root.appendingPathComponent("\(stage).json")+        let canonicalHome = home.resolvingSymlinksInPath()+        _ = try #require(canonicalHome.path == home.path)+        let temp = home.appendingPathComponent("tmp", isDirectory: true)+        _ = try #require(manager.fileExists(atPath: temp.path))+        _ = try #require(temp.resolvingSymlinksInPath().path == canonicalHome.appendingPathComponent("tmp").path)+        let expectedRoot = canonicalHome.appendingPathComponent("tmp/T1734Closed-\(token.uuidString)")+        _ = try #require(root.resolvingSymlinksInPath().path == expectedRoot.path)+        let leaves = [root, manifest, observation, root.appendingPathComponent("pre-feature.store"),+                      root.appendingPathComponent("pre-feature.store-wal"),+                      root.appendingPathComponent("pre-feature.store-shm")]+        for leaf in leaves {+            _ = try #require((try? manager.destinationOfSymbolicLink(atPath: leaf.path)) == nil)+        }+        return root+    }+}++/// Local precheck only; never creates a CloudKit container or sends a request.+/// The development record/deletion gate needs the real task2 models and a+/// separately cleared signed CloudKit development host/operator fixture.+@MainActor @Suite(.serialized)+struct TaskLinkDevelopmentSchemaPrecheckTests {+    @Test(.enabled(if: ProcessInfo.processInfo.environment["T1734_DEV_SCHEMA_PRECHECK"] == "1"))+    func developmentVerificationIsNotSatisfiedByLocalRegistration() throws {+        let fixture = try TestModelContainer()+        _ = try #require(fixture.container.schema.entitiesByName["TaskLinkOccurrence"])+        _ = try #require(fixture.container.schema.entitiesByName["TaskLinkRemovalEvidence"])+        Issue.record("Local schema precheck only: cleared development schema and platform deletion evidence required")+    }+}+#endif
Transit/TransitTests/TaskLinkCommitBoundaryTests.swift Changed +274 / -0
diff --git a/Transit/TransitTests/TaskLinkCommitBoundaryTests.swift b/Transit/TransitTests/TaskLinkCommitBoundaryTests.swiftnew file mode 100644index 00000000..57738ee4--- /dev/null+++ b/Transit/TransitTests/TaskLinkCommitBoundaryTests.swift@@ -0,0 +1,274 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++/// Baseline controls only. No test here certifies graph-write enablement.+/// Independently opened containers observe disk saves; the original owning+/// fixture remains retained, so these are not process-closed migration tests.+@MainActor @Suite(.serialized)+struct TaskLinkCommitBoundaryTests {+    @Test func independentSavedObservationExcludesPendingGraphEdits() throws {+        let fixture = try TaskLinkCommitDiskFixture()+        fixture.source.name = "unsaved draft"+        fixture.owner.context.delete(fixture.edge)+        fixture.owner.context.insert(TaskLinkOccurrence(+            id: UUID(), kindRawValue: "dependency", sourceTaskID: fixture.target.id,+            targetTaskID: fixture.source.id, createdAt: fixture.instant))+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "source")+        let rows = try observer.context.fetch(FetchDescriptor<TaskLinkOccurrence>())+        #expect(rows.count == 1)+        #expect(rows.first?.id == fixture.edge.id)+        #expect(rows.first?.sourceTaskID == fixture.target.id)+        #expect(rows.first?.targetTaskID == fixture.source.id)+        #expect(rows.first?.kindRawValue == "dependency")+        #expect(rows.first?.createdAt == fixture.instant)+        #expect(try fixture.historicReceipt(in: observer.context).resultJSON == fixture.historicJSON)+        #expect(fixture.owner.context.hasChanges)+        #expect(!observer.context.hasChanges)+    }++    @Test func independentSavedObservationSeesPeerChangeAfterRegistration() throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let registered = try fixture.task(fixture.target.id, in: fixture.owner.context)+        #expect(registered.statusRawValue == "done")+        let peer = try fixture.observer()+        let imported = try fixture.task(fixture.target.id, in: peer.context)+        imported.statusRawValue = "abandoned"+        try peer.context.save()+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.target.id, in: observer.context).statusRawValue == "abandoned")+        #expect(try fixture.historicReceipt(in: observer.context).requestJSON == fixture.historicRequest)+        // Registered-model auto-refresh is deliberately not assumed; the+        // future commit seam must explicitly establish authoritative saved data.+    }++    @Test(arguments: ["save", "encode"])+    func legacyCoordinatorFailurePreservesSavedDomainAndHistoricalBytes(failure: String) async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let coordinator = fixture.coordinator(save: { context, stage in+            if case .commit = stage, failure == "save" { throw TaskLinkCommitDiskFixture.Failure.injected }+            try context.save()+        }, encode: { envelope in+            if envelope["outcome"] as? String == "committed", failure == "encode" {+                throw TaskLinkCommitDiskFixture.Failure.injected+            }+            return try MCPWriteOutcome.encode(envelope)+        })+        let result = await coordinator.execute(tool: "update_task", arguments: try fixture.updateArguments())+        #expect(try fixture.decode(result)["outcome"] as? String == "rejected")+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "source")+        #expect(try observer.context.fetch(FetchDescriptor<TaskLinkOccurrence>()).count == 1)+        #expect(try observer.context.fetch(FetchDescriptor<TaskLinkRemovalEvidence>()).count == 1)+        let evidence = try observer.context.fetch(FetchDescriptor<TaskLinkRemovalEvidence>()).first+        #expect(evidence?.kindRawValue == "future-kind")+        #expect(evidence?.occurrenceRevision == "raw-imported-revision")+        #expect(try fixture.historicReceipt(in: observer.context).resultJSON == fixture.historicJSON)+        let key = "boundary-update"+        let receipts = try observer.context.fetch(FetchDescriptor<MCPWriteReceipt>(+            predicate: #Predicate { $0.key == key }))+        let receipt = try #require(receipts.count == 1 ? receipts.first : nil)+        #expect(receipt.stateRawValue == "rejected")+        #expect(receipt.resultIsError == true)+    }++    @Test func legacyRetainedReplayBypassesPreparationAndCommitSave() async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        var commitSaves = 0+        var preparations = 0+        let coordinator = fixture.coordinator(save: { context, stage in+            if case .commit = stage { commitSaves += 1 }+            try context.save()+        }, preparation: { _ in preparations += 1 })+        let arguments = try fixture.updateArguments()+        let original = await coordinator.execute(tool: "update_task", arguments: arguments)+        #expect(try fixture.decode(original)["outcome"] as? String == "committed")+        let replay = await coordinator.execute(tool: "update_task", arguments: arguments)+        #expect(replay.content.first?.text == original.content.first?.text)+        #expect(commitSaves == 1)+        #expect(preparations == 1)+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "committed update")+        #expect(try fixture.historicReceipt(in: observer.context).resultJSON == fixture.historicJSON)+        // Dirty replay/clean-phase guarantees require the handed-off policy;+        // they are not imposed on the unchanged standalone coordinator.+    }++    @Test(.enabled(if: ProcessInfo.processInfo.environment["T1734_TRANSACTION_DIAGNOSTIC"] == "1"))+    func primitiveTransactionEarlierObservationCanBeInvalidatedByPeerSave() throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let peer = try fixture.observer()+        var validatedDone = false+        try fixture.owner.context.transaction {+            validatedDone = try fixture.task(fixture.target.id, in: fixture.owner.context).statusRawValue == "done"+            let imported = try fixture.task(fixture.target.id, in: peer.context)+            imported.statusRawValue = "abandoned"+            try peer.context.save()+            fixture.source.name = "write after earlier validation"+            try fixture.owner.context.save()+        }+        let observer = try fixture.observer()+        #expect(validatedDone)+        #expect(try fixture.task(fixture.target.id, in: observer.context).statusRawValue == "abandoned")+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "write after earlier validation")+        // A passing diagnostic is a counterexample, not an atomicity gate PASS.+        // If peer save blocks/fails, retain that evidence for mechanism review.+        // Run only in a bounded isolated parent-owned host slot with sampling.+    }+    @Test(.enabled(if: ProcessInfo.processInfo.environment["T1734_TRANSACTION_ABORT_DIAGNOSTIC"] == "1"))+    func primitiveTransactionInternalSaveMustRollBackOnClosureAbort() throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let markerID = UUID(), evidenceID = UUID()+        // Fixture-only marker: never an accepted production request, endpoint+        // timestamp, or retained idempotency binding.+        let marker = MCPWriteReceipt(id: markerID, localScopeID: "synthetic-transaction-probe",+            tool: "fixture-only", key: "internal-flush", requestJSON: "{\"probe\":true}",+            acceptedAt: fixture.instant)+        fixture.owner.context.insert(marker)+        try fixture.owner.context.save()+        var internalSaveReturned = false+        var sawInjectedAbort = false+        do {+            try fixture.owner.context.transaction {+                marker.stateRawValue = "fixture-flushed"+                marker.resultJSON = "{\"terminal\":true}"+                fixture.source.name = "internal flush domain"+                fixture.owner.context.delete(fixture.edge)+                fixture.owner.context.insert(TaskLinkRemovalEvidence(id: evidenceID, edgeId: fixture.edge.id,+                    kindRawValue: "dependency", sourceTaskID: fixture.target.id, targetTaskID: fixture.source.id,+                    createdAt: fixture.instant, occurrenceRevision: "fixture-probe", removedAt: fixture.instant))+                try fixture.owner.context.save()+                internalSaveReturned = true+                throw TaskLinkCommitDiskFixture.Failure.injected+            }+        } catch TaskLinkCommitDiskFixture.Failure.injected {+            sawInjectedAbort = true+        }+        try #require(internalSaveReturned && sawInjectedAbort)+        let observer = try fixture.observer()+        let rows = try observer.context.fetch(FetchDescriptor<MCPWriteReceipt>(+            predicate: #Predicate { $0.id == markerID }))+        let savedMarker = try #require(rows.count == 1 ? rows.first : nil)+        #expect(savedMarker.stateRawValue == "accepted")+        #expect(savedMarker.resultJSON == nil)+        #expect(savedMarker.requestJSON == "{\"probe\":true}")+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "source")+        let edges = try observer.context.fetch(FetchDescriptor<TaskLinkOccurrence>())+        #expect(edges.count == 1 && edges.first?.id == fixture.edge.id)+        let evidence = try observer.context.fetch(FetchDescriptor<TaskLinkRemovalEvidence>())+        #expect(!evidence.contains { $0.id == evidenceID })+        #expect(evidence.count == 1)+        #expect(try fixture.historicReceipt(in: observer.context).resultJSON == fixture.historicJSON)+        // Passing establishes abort durability only. It does not establish+        // saved-read freshness, peer exclusion, phantom protection, or success+        // atomicity. A failure disqualifies this internal-flush candidate.+    }+}++@MainActor+struct TaskLinkCommitDiskFixture {+    enum Failure: Error { case injected, ambiguous }+    let owner: TestModelContainer+    let directory: URL+    let instant = Date(timeIntervalSince1970: 1_700_000_000)+    let source: TransitTask+    let target: TransitTask+    let edge: TaskLinkOccurrence+    let allocator = DisplayIDAllocator(store: InMemoryCounterStore(), isCloudSyncActive: false)+    let historicJSON = "{\n  \"original\": \"café\", \"n\":9007199254740993\n}\n"+    let historicRequest = "{ \"original\" : true }"++    init() throws {+        directory = FileManager.default.temporaryDirectory.appendingPathComponent("T1734Commit-\(UUID().uuidString)")+        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+        let schema = try TestModelContainer().container.schema+        let configuration = ModelConfiguration(schema: schema, url: directory.appendingPathComponent("commit.store"),+                                               cloudKitDatabase: .none)+        owner = try TestModelContainer(schema: schema, configurations: [configuration])+        owner.context.autosaveEnabled = false+        let project = Project(name: "boundary", description: "saved", gitRepo: nil, colorHex: "#123456")+        source = TransitTask(name: "source", type: .feature, project: project, displayID: .permanent(1))+        target = TransitTask(name: "target", type: .feature, project: project, displayID: .permanent(2))+        target.statusRawValue = "done"+        edge = TaskLinkOccurrence(id: UUID(), kindRawValue: "dependency", sourceTaskID: target.id,+                                  targetTaskID: source.id, createdAt: instant)+        let removal = TaskLinkRemovalEvidence(id: UUID(), edgeId: UUID(), kindRawValue: "future-kind",+                                             sourceTaskID: source.id, targetTaskID: target.id, createdAt: instant,+                                             occurrenceRevision: "raw-imported-revision", removedAt: instant)+        let historic = MCPWriteReceipt(localScopeID: "historic-local-scope", tool: "update_task",+                                       key: "historic", requestJSON: historicRequest, acceptedAt: instant)+        historic.stateRawValue = "committed"+        historic.resultJSON = historicJSON+        historic.completedAt = instant+        historic.expiresAt = instant.addingTimeInterval(604800)+        historic.resultIsError = false+        owner.context.insert(project)+        owner.context.insert(source)+        owner.context.insert(target)+        owner.context.insert(edge)+        owner.context.insert(removal)+        owner.context.insert(historic)+        try owner.context.save()+        // All owning containers stay retained; do not unlink an open SQLite store.+    }++    func observer() throws -> TestModelContainer {+        let configuration = ModelConfiguration(schema: owner.container.schema,+                                               url: directory.appendingPathComponent("commit.store"),+                                               cloudKitDatabase: .none)+        let observer = try TestModelContainer(schema: owner.container.schema, configurations: [configuration])+        observer.context.autosaveEnabled = false+        return observer+    }++    func task(_ id: UUID, in context: ModelContext) throws -> TransitTask {+        var descriptor = FetchDescriptor<TransitTask>(predicate: #Predicate { $0.id == id })+        descriptor.fetchLimit = 2+        let matches = try context.fetch(descriptor)+        guard matches.count == 1 else { throw Failure.ambiguous }+        return matches[0]+    }++    func historicReceipt(in context: ModelContext) throws -> MCPWriteReceipt {+        let key = "historic"+        let matches = try context.fetch(FetchDescriptor<MCPWriteReceipt>(predicate: #Predicate { $0.key == key }))+        guard matches.count == 1 else { throw Failure.ambiguous }+        return matches[0]+    }++    func updateArguments() throws -> [String: Any] {+        ["taskId": source.id.uuidString, "name": "committed update", "idempotencyKey": "boundary-update",+         "expectedRevision": try MCPRecordSnapshot.task(source, in: owner.context).revision]+    }++    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 coordinator(+        save: @escaping @MainActor (ModelContext, MCPWriteCoordinator.SaveStage) throws -> Void,+        encode: @escaping @MainActor ([String: Any]) throws -> String = MCPWriteOutcome.encode,+        preparation: @escaping @MainActor (MCPWriteCommand) async throws -> Void = { _ in },+        recovery: @escaping @MainActor () throws -> Void = {},+        newTaskID: @escaping @MainActor () -> UUID = UUID.init+    ) -> MCPWriteCoordinator {+        let context = owner.context+        let services = MCPWriteCommandServices(+            tasks: TaskService(modelContext: context, displayIDAllocator: allocator),+            projects: ProjectService(modelContext: context), comments: CommentService(modelContext: context),+            milestones: MilestoneService(modelContext: context, displayIDAllocator: allocator), context: context)+        return MCPWriteCoordinator(services: services, sidecarDirectory: directory.appendingPathComponent("guards"),+                                   persistence: PersistenceAvailability(isFallbackStorageActive: false),+                                   save: save, encode: encode, newTaskID: newTaskID,+                                   preparationHook: preparation, recoveryHook: recovery)+    }++    func commitServices(in context: ModelContext) -> MCPWriteCommitServices {+        MCPWriteCommitServices(context: context, taskAllocator: allocator, milestoneAllocator: allocator)+    }+}+#endif
Transit/TransitTests/TaskLinkFoundationIntegrationTests.swift Changed +133 / -0
diff --git a/Transit/TransitTests/TaskLinkFoundationIntegrationTests.swift b/Transit/TransitTests/TaskLinkFoundationIntegrationTests.swiftnew file mode 100644index 00000000..d5ebf24d--- /dev/null+++ b/Transit/TransitTests/TaskLinkFoundationIntegrationTests.swift@@ -0,0 +1,133 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++/// Real protected routes and independently opened saved observers. Closed-store+/// upgrade itself is covered by the separately drained migration-stage runner.+@MainActor @Suite(.serialized)+struct TaskLinkFoundationIntegrationTests {+    @Test func protectedRepairKeepsFrozenQueryWhileNativeSeesSavedIncidence() async throws {+        let base = try TaskLinkCommitDiskFixture()+        let writes = TaskLinkWriteFixture(base: base)+        let frozen = try capture(base)+        let before = try rows(frozen, id: base.source.id)+        let args = try writes.removal(key: "integration-repair")+        let result = await writes.execute(args)+        try writes.assertOutcome(result, "committed")+        base.source.name = "UI draft after repair"+        let native = try TaskLinkService(container: base.owner.container).savedDetail(for: base.source.id)+        #expect(native.source.name == "source")+        #expect(native.graph.incidence[base.source.id, default: []].isEmpty)+        let current = try rows(capture(base), id: base.source.id)+        #expect(current[0]["revision"] as? String != before[0]["revision"] as? String)+        #expect(try canonical(rows(frozen, id: base.source.id)) == canonical(before))+        #expect(frozen.taskLinkGraph?.occurrences.map(\.id) == [base.edge.id])+        let replay = await writes.execute(args)+        #expect(replay.content.first?.text == result.content.first?.text)+        let observer = try base.observer()+        let destination = try TaskLinkNavigationResolver.resolve(base.target.id, in: observer.context)+        #expect(destination?.id == base.target.id)+        #expect(try base.historicReceipt(in: observer.context).resultJSON == base.historicJSON)+        #expect(base.owner.context.hasChanges)+    }++    @Test func creationStatusCommentAndParticipatingBatchKeepPortfolioCounts() async throws {+        let base = try TaskLinkCommitDiskFixture()+        let writes = TaskLinkWriteFixture(base: base)+        let creation = try creationArguments(base, writes: writes)+        let created = await writes.execute(creation, tool: "create_task")+        try writes.assertOutcome(created, "committed")+        let record = try #require(try base.decode(created)["record"] as? [String: Any])+        let id = try #require((record["taskId"] as? String).flatMap(UUID.init(uuidString:)))+        let status: [String: Any] = ["taskId": id.uuidString, "expectedRevision": try writes.revision(id),+            "idempotencyKey": "integration-status", "status": "in-progress", "comment": " reason ",+            "authorName": " Agent "]+        try writes.assertOutcome(await writes.execute(status, tool: "update_task_status"), "committed")+        let batchArgs: [String: Any] = ["taskId": id.uuidString, "expectedRevision": try writes.revision(id),+            "idempotencyKey": "integration-batch", "name": " Batch name "]+        let document = try MCPBatchTaskRequestFixtures.document(items: [+            ["itemId": "owned", "operation": "update_task", "arguments": batchArgs]])+        let request = try MCPBatchTaskRequestFixtures.valid(document)+        let execution = try await writes.handler.executeBatchItem(request.items[0])+        #expect(!execution.pendingEditsStop)+        let observer = try base.observer()+        let task = try base.task(id, in: observer.context)+        #expect(task.name == "Batch name" && task.statusRawValue == "in-progress")+        let comments = try observer.context.fetch(CommentService.descriptor(for: id))+        #expect(comments.count == 1 && comments[0].content == "reason" && comments[0].authorName == "Agent")+        let view = try capture(base, portfolio: true)+        let summary = try PortfolioSummaryService.summarize(view: view,+            window: CompletionWindow(start: Date(timeIntervalSince1970: 0), end: Date()+60))+        #expect(summary.projects.first?.totalTaskCount == 3)+        #expect(view.tasks.count == 3 && view.taskLinkGraph?.tasks.count == 3)+        #expect(try observer.context.fetchCount(FetchDescriptor<TaskLinkOccurrence>()) == 2)+        try assertBatchGraphShapeRejected(batchArgs, base: base)+        let replay = await writes.execute(creation, tool: "create_task")+        #expect(replay.content.first?.text == created.content.first?.text)+        #expect(try base.historicReceipt(in: observer.context).resultJSON == base.historicJSON)+    }++    @Test func maintenanceExpiryDoesNotRemintTerminalResultOrFrozenToken() async throws {+        let base = try TaskLinkCommitDiskFixture()+        let writes = TaskLinkWriteFixture(base: base)+        let args = try writes.removal(key: "integration-expiry")+        let result = await writes.execute(args)+        try writes.assertOutcome(result, "committed")+        let frozen = try capture(base)+        let original = try rows(frozen, id: base.source.id)+        let revision = try writes.revision(base.source.id)+        let instant = Date() + TaskLinkGraph.evidenceLifetime + 60+        #expect(try TaskLinkService(container: base.owner.container).cleanupExpiredEvidence(+            evaluationInstant: instant) == 1)+        #expect(try writes.revision(base.source.id) == revision)+        #expect(try canonical(rows(frozen, id: base.source.id)) == canonical(original))+        let replay = await writes.execute(args)+        #expect(replay.content.first?.text == result.content.first?.text)+        let observer = try base.observer()+        #expect(try observer.context.fetchCount(FetchDescriptor<TaskLinkOccurrence>()) == 0)+        #expect(try observer.context.fetchCount(FetchDescriptor<TaskLinkRemovalEvidence>()) == 1)+        #expect(try writes.receipts(for: args, in: observer.context).first?.resultJSON == result.content.first?.text)+        #expect(try base.historicReceipt(in: observer.context).resultJSON == base.historicJSON)+    }++    private func capture(_ base: TaskLinkCommitDiskFixture, portfolio: Bool = false) throws -> CapturedReadView {+        try MCPReadCaptureBuilder(container: base.owner.container, fence: .actorOnlyTestFixture).capture(+            ReadCaptureRequest(projectSelectors: nil, selection: portfolio ? .portfolio : .tasks(detail: .fullRecord),+                completeness: portfolio ? .completePortfolio : .selectedRead, includeComments: true))+    }++    private func rows(_ view: CapturedReadView, id: UUID) throws -> [[String: Any]] {+        let args: [String: Any] = ["detailLevel": "full", "includeComments": true, "limit": 100]+        return try MCPReadProjection.tasks(view, request: MCPTaskQueryRequest.parse(args), arguments: args)+            .filter { $0["taskId"] as? String == id.uuidString }+    }++    private func canonical(_ value: Any) throws -> Data {+        try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys])+    }++    private func creationArguments(_ base: TaskLinkCommitDiskFixture,+                                   writes: TaskLinkWriteFixture) throws -> [String: Any] {+        let projectID = try #require(base.source.project?.id)+        return ["name": "Integrated creation", "type": "feature", "projectId": projectID.uuidString,+            "idempotencyKey": "integration-create", "linkChanges": [["action": "add", "type": "relates-to",+                "targetTaskId": base.target.id.uuidString]], "endpointPreconditions": [[+                    "taskId": base.target.id.uuidString, "expectedRevision": try writes.revision(base.target.id)]]]+    }++    private func assertBatchGraphShapeRejected(_ original: [String: Any], base: TaskLinkCommitDiskFixture) throws {+        var unsupported = original+        unsupported["idempotencyKey"] = "integration-unsupported"+        unsupported["linkChanges"] = [] as [[String: Any]]+        let document = try MCPBatchTaskRequestFixtures.document(items: [+            ["itemId": "unsupported", "operation": "update_task", "arguments": unsupported]])+        try MCPBatchTaskRequestFixtures.invalid(document, index: 0, field: "linkChanges")+        let key = "integration-unsupported"+        let receipts = try base.observer().context.fetch(FetchDescriptor<MCPWriteReceipt>(+            predicate: #Predicate { $0.key == key }))+        #expect(receipts.isEmpty)+    }+}+#endif
Transit/TransitTests/TaskLinkGraphGeneratedTests.swift Changed +142 / -0
diff --git a/Transit/TransitTests/TaskLinkGraphGeneratedTests.swift b/Transit/TransitTests/TaskLinkGraphGeneratedTests.swiftnew file mode 100644index 00000000..ce4e25f2--- /dev/null+++ b/Transit/TransitTests/TaskLinkGraphGeneratedTests.swift@@ -0,0 +1,142 @@+import Foundation+import Testing+@testable import Transit++@MainActor+struct TaskLinkGraphGeneratedTests {+    @Test(arguments: Array(UInt64(1)...8))+    func generatedSCCMatchesIndependentReachability(seed: UInt64) throws {+        var state = seed+        let tasks = (0..<6).map { index in+            TaskLinkTaskValue(physicalKey: Data([UInt8(index)]), id: UUID(), name: "generated",+                              status: ["done", "planning", "future-status", "abandoned"][index % 4])+        }+        var rows: [TaskLinkOccurrenceValue] = []+        for source in tasks.indices {+            for target in tasks.indices where target != source {+                state = state &* 6_364_136_223_846_793_005 &+ 1+                if state >> 61 < 2 {+                    rows.append(edge(UInt8(rows.count), kind: "dependency", tasks[source].id, tasks[target].id))+                }+            }+        }+        let view = try project(tasks, rows)+        var expected: Set<UUID> = []+        for task in tasks {+            for other in tasks where other.id != task.id {+                if reaches(task.id, other.id, rows), reaches(other.id, task.id, rows) {+                    expected.insert(task.id)+                }+            }+        }+        #expect(view.cyclicTasks == expected)+        for task in tasks {+            let direct = rows.filter { $0.target == task.id }.compactMap { edge in+                tasks.first { $0.id == edge.source }+            }+            let assessment: TaskLinkBlockerAssessment+            if expected.contains(task.id) || direct.contains(where: { $0.status == "future-status" }) {+                assessment = .invalid+            } else if direct.contains(where: { $0.status != "done" }) { assessment = .blocked } else {+                assessment = .unblocked+            }+            #expect(view.assessment(for: task.id) == assessment)+        }+        let reversed = try project(tasks.reversed(), rows.reversed())+        #expect(reversed.cyclicTasks == view.cyclicTasks)+        #expect(reversed.blockers == view.blockers)+        #expect(reversed.diagnostics == view.diagnostics)+    }++    @Test(arguments: ["chain", "cardinality", "cycle"])+    func duplicatePathsPreserveOriginalAndReportFaults(shape: String) throws {+        let tasks = (0..<3).map { index in+            TaskLinkTaskValue(physicalKey: Data([UInt8(index)]), id: UUID(), name: "duplicate", status: "abandoned")+        }+        var rows = [edge(1, kind: "duplicate", tasks[0].id, tasks[1].id)]+        if shape == "cardinality" { rows.append(edge(2, kind: "duplicate", tasks[0].id, tasks[2].id)) } else {+            rows.append(edge(2, kind: "duplicate", tasks[1].id, shape == "cycle" ? tasks[0].id : tasks[2].id))+        }+        let view = try project(tasks, rows)+        let result = try TaskLinkGraph.duplicateResolution(for: tasks[0].id, in: view)+        #expect(result.path.first == tasks[0].id)+        if shape == "chain" {+            #expect(result.path == tasks.map(\.id))+            #expect(result.canonical == tasks[2].id)+        } else {+            #expect(result.canonical == nil)+            #expect(result.diagnostic == (shape == "cycle" ? "duplicate_cycle" : "duplicate_cardinality"))+        }+        #expect(view.occurrences == rows)+        #expect(view.assessment(for: tasks[0].id) == .unblocked)+    }++    @Test func evidenceExpiryChangesAssessmentWithoutChangingActiveIncidence() throws {+        let tasks = [TaskLinkTaskValue(physicalKey: Data([1]), id: UUID(), name: "blocker", status: "done"),+                     TaskLinkTaskValue(physicalKey: Data([2]), id: UUID(), name: "target", status: "idea")]+        let row = edge(1, kind: "dependency", tasks[0].id, tasks[1].id)+        let removed = Date(timeIntervalSince1970: 200)+        let evidence = TaskLinkRemovalValue(physicalKey: Data([3]), id: UUID(), edgeId: row.id,+            kind: row.kind, source: row.source, target: row.target, createdAt: row.createdAt,+            occurrenceRevision: try TaskLinkGraph.occurrenceRevision(row), removedAt: removed)+        let fresh = try TaskLinkGraph.project(tasks: tasks, occurrences: [row], removalEvidence: [evidence],+                                             evaluationInstant: removed)+        let expired = try TaskLinkGraph.project(tasks: tasks, occurrences: [row], removalEvidence: [evidence],+            evaluationInstant: removed.addingTimeInterval(TaskLinkGraph.evidenceLifetime))+        #expect(fresh.assessment(for: tasks[1].id) == .invalid)+        #expect(expired.assessment(for: tasks[1].id) == .unblocked)+        #expect(fresh.occurrences == expired.occurrences)+        #expect(fresh.incidence == expired.incidence)+        #expect(expired.recognizedRemovals.isEmpty)+    }++    @Test func graphBudgetFailsWholeProjection() {+        #expect(throws: TaskLinkGraphError.self) {+            try TaskLinkGraph.project(tasks: [], occurrences: [], removalEvidence: [], evaluationInstant: Date(),+                                     budget: TaskLinkGraphBudget(deadline: .now.advanced(by: .seconds(-1))))+        }+        #expect(throws: TaskLinkGraphError.self) {+            try TaskLinkGraph.project(tasks: [TaskLinkTaskValue(physicalKey: Data([1]), id: UUID(),+                                                               name: "capacity", status: "idea")],+                occurrences: [], removalEvidence: [], evaluationInstant: Date(),+                budget: TaskLinkGraphBudget(maximumBytes: 1))+        }+    }++    @Test func repeatedOccurrenceUUIDCannotIssueActionableIdentity() throws {+        let source = TaskLinkTaskValue(physicalKey: Data([1]), id: UUID(),+                                       name: "source", status: "done")+        let target = TaskLinkTaskValue(physicalKey: Data([2]), id: UUID(), name: "target", status: "idea")+        let original = edge(1, kind: "dependency", source.id, target.id)+        let copy = TaskLinkOccurrenceValue(physicalKey: Data([9]), id: original.id, kind: original.kind,+                                          source: original.source, target: original.target,+                                          createdAt: original.createdAt)+        let view = try project([source, target], [original, copy])+        #expect(view.occurrencesById[original.id]?.count == 2)+        #expect(view.invalidOccurrences == Set([original.physicalKey, copy.physicalKey]))+        #expect(view.assessment(for: target.id) == .invalid)+    }++    /// Independent reachability reference uses breadth-first traversal, not SCC implementation.+    private func reaches(_ source: UUID, _ target: UUID, _ edges: [TaskLinkOccurrenceValue]) -> Bool {+        var queue = [source], seen: Set<UUID> = [source], offset = 0+        while offset < queue.count {+            let current = queue[offset]; offset += 1+            for edge in edges where edge.source == current {+                if edge.target == target { return true }+                if seen.insert(edge.target).inserted { queue.append(edge.target) }+            }+        }+        return false+    }++    private func edge(_ number: UInt8, kind: String, _ source: UUID, _ target: UUID) -> TaskLinkOccurrenceValue {+        TaskLinkOccurrenceValue(physicalKey: Data([number]), id: UUID(), kind: kind,+                                source: source, target: target, createdAt: Date(timeIntervalSince1970: 100))+    }++    private func project(_ tasks: [TaskLinkTaskValue], _ edges: [TaskLinkOccurrenceValue]) throws -> TaskLinkGraphView {+        try TaskLinkGraph.project(tasks: tasks, occurrences: edges, removalEvidence: [],+                                  evaluationInstant: Date(timeIntervalSince1970: 200))+    }+}
Transit/TransitTests/TaskLinkGraphServiceTests.swift Changed +45 / -0
diff --git a/Transit/TransitTests/TaskLinkGraphServiceTests.swift b/Transit/TransitTests/TaskLinkGraphServiceTests.swiftnew file mode 100644index 00000000..4e9e9ce2--- /dev/null+++ b/Transit/TransitTests/TaskLinkGraphServiceTests.swift@@ -0,0 +1,45 @@+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct TaskLinkGraphServiceTests {+    @Test func savedDetailIgnoresUnsavedLabelAndGraphDrafts() throws {+        let owner = try TestModelContainer()+        let project = Project(name: "saved graph", description: "", gitRepo: nil, colorHex: "#000000")+        let source = TransitTask(name: "saved source", type: .feature, project: project, displayID: .provisional)+        let target = TransitTask(name: "saved target", type: .feature, project: project, displayID: .provisional)+        target.status = .done+        let row = TaskLinkOccurrence(id: UUID(), kindRawValue: "dependency", sourceTaskID: target.id,+                                     targetTaskID: source.id, createdAt: Date())+        owner.context.insert(project)+        owner.context.insert(source)+        owner.context.insert(target)+        owner.context.insert(row)+        try owner.context.save()+        source.name = "draft source"+        target.name = "draft target"+        owner.context.delete(row)+        let detail = try TaskLinkService(container: owner.container).savedDetail(for: source.id)+        #expect(detail.source.name == "saved source")+        #expect(detail.graph.tasksById[target.id]?.first?.name == "saved target")+        #expect(detail.graph.occurrences.map(\.id) == [row.id])+        #expect(detail.graph.assessment(for: source.id) == .unblocked)+        #expect(source.name == "draft source")+        #expect(owner.context.hasChanges)+    }++    @Test func unsavedSourceIsUnavailableInsteadOfEmptyGraph() throws {+        let owner = try TestModelContainer()+        let project = Project(name: "private", description: "", gitRepo: nil, colorHex: "#000000")+        owner.context.insert(project)+        try owner.context.save()+        let source = TransitTask(name: "not saved", type: .feature, project: project, displayID: .provisional)+        owner.context.insert(source)+        #expect(throws: TaskLinkGraphError.self) {+            try TaskLinkService(container: owner.container).savedDetail(for: source.id)+        }+        #expect(owner.context.hasChanges)+    }+}
Transit/TransitTests/TaskLinkGraphTests.swift Changed +96 / -0
diff --git a/Transit/TransitTests/TaskLinkGraphTests.swift b/Transit/TransitTests/TaskLinkGraphTests.swiftnew file mode 100644index 00000000..aa326e9c--- /dev/null+++ b/Transit/TransitTests/TaskLinkGraphTests.swift@@ -0,0 +1,96 @@+import Foundation+import Testing+@testable import Transit++@MainActor+struct TaskLinkGraphTests {+    @Test func inverseAndAssociationNormalization() {+        let source = UUID(), target = UUID()+        #expect(TaskLinkType.blocks.normalized(source: source, target: target)+                == TaskLinkType.blockedBy.normalized(source: target, target: source))+        #expect(TaskLinkType.relatesTo.normalized(source: source, target: target)+                == TaskLinkType.relatesTo.normalized(source: target, target: source))+    }++    @Test(arguments: ["done", "abandoned", "in-progress", "future-status"])+    func directSavedBlockerStatus(status: String) throws {+        let source = task(1, status: status), target = task(2)+        let view = try project([source, target], [edge(1, source.id, target.id)])+        let expected: TaskLinkBlockerAssessment = status == "done" ? .unblocked+            : status == "future-status" ? .invalid : .blocked+        #expect(view.assessment(for: target.id) == expected)+    }++    @Test func dependencyCycleIsInvalidEvenWhenDone() throws {+        let first = task(1, status: "done"), second = task(2, status: "done")+        let view = try project([first, second], [edge(1, first.id, second.id), edge(2, second.id, first.id)])+        #expect(view.cyclicTasks == Set([first.id, second.id]))+        #expect(view.assessment(for: first.id) == .invalid)+        #expect(view.assessment(for: second.id) == .invalid)+    }++    @Test func repeatedLogicalRowsCannotCertifyUnblocked() throws {+        let first = task(1, status: "done"), second = task(2)+        let view = try project([first, second], [edge(1, first.id, second.id), edge(2, first.id, second.id)])+        #expect(view.assessment(for: second.id) == .invalid)+        #expect(view.diagnostics.filter { $0.code == "equivalent_occurrences" }.count == 2)+        #expect(view.incidence[second.id]?.count == 2)+    }++    @Test func doneBlockerDoesNotPropagateItsBadAncestry() throws {+        let blocker = task(1, status: "done"), target = task(2)+        let view = try project([blocker, target], [edge(1, UUID(), blocker.id), edge(2, blocker.id, target.id)])+        #expect(view.assessment(for: blocker.id) == .invalid)+        #expect(view.assessment(for: target.id) == .unblocked)+    }++    @Test func physicalIdentityCollisionAndMissingEndpointRemainVisible() throws {+        let source = task(1)+        let repeated = TaskLinkTaskValue(physicalKey: Data([9]), id: source.id, name: "collision", status: "done")+        let row = edge(1, source.id, UUID())+        let view = try project([source, repeated], [row])+        #expect(view.tasksById[source.id]?.count == 2)+        #expect(Set(view.diagnostics.map(\.code)) == ["ambiguous_endpoint", "missing_endpoint"])+        #expect(view.assessment(for: source.id) == .invalid)+    }++    @Test(arguments: [false, true])+    func candidateUnknownStatusUsesOnlyItsDirectBlockerEvidence(hasDoneBlocker: Bool) throws {+        let candidate = task(1, status: "future-status"), blocker = task(2, status: "done")+        let view = try project([candidate, blocker], hasDoneBlocker ? [edge(1, blocker.id, candidate.id)] : [])+        #expect(view.assessment(for: candidate.id) == .unblocked)+    }++    @Test(arguments: ["collision", "future"])+    func matchingInvalidRemovalEvidenceCannotCertifyActiveRelation(shape: String) throws {+        let source = task(1, status: "done"), target = task(2), active = edge(1, source.id, target.id)+        let row = TaskLinkRemovalValue(physicalKey: Data([10]), id: UUID(), edgeId: active.id,+            kind: active.kind, source: active.source, target: active.target, createdAt: active.createdAt,+            occurrenceRevision: try TaskLinkGraph.occurrenceRevision(active),+            removedAt: Date(timeIntervalSince1970: shape == "future" ? 300 : 150))+        let copy = TaskLinkRemovalValue(physicalKey: Data([11]), id: row.id, edgeId: row.edgeId,+            kind: row.kind, source: row.source, target: row.target, createdAt: row.createdAt,+            occurrenceRevision: row.occurrenceRevision, removedAt: row.removedAt)+        let view = try TaskLinkGraph.project(tasks: [source, target], occurrences: [active],+            removalEvidence: shape == "collision" ? [row, copy] : [row],+            evaluationInstant: Date(timeIntervalSince1970: 200))+        #expect(view.assessment(for: target.id) == .invalid)+        #expect(view.recognizedRemovals.isEmpty)+        #expect(view.diagnostics.contains { $0.code == "active_removal_conflict" })+        #expect(view.diagnostics.contains { $0.code == "invalid_removal_evidence" })+    }++    private func task(_ number: UInt8, status: String = "idea") -> TaskLinkTaskValue {+        TaskLinkTaskValue(physicalKey: Data([number]), id: UUID(), name: "task", status: status)+    }++    private func edge(_ number: UInt8, _ source: UUID, _ target: UUID) -> TaskLinkOccurrenceValue {+        TaskLinkOccurrenceValue(physicalKey: Data([number]), id: UUID(), kind: "dependency",+                                source: source, target: target, createdAt: Date(timeIntervalSince1970: 100))+    }++    private func project(_ tasks: [TaskLinkTaskValue], _ edges: [TaskLinkOccurrenceValue]) throws -> TaskLinkGraphView {+        try TaskLinkGraph.project(tasks: tasks, occurrences: edges, removalEvidence: [],+                                  evaluationInstant: Date(timeIntervalSince1970: 200))+    }+}
Transit/TransitTests/TaskLinkMigrationTests.swift Changed +185 / -0
diff --git a/Transit/TransitTests/TaskLinkMigrationTests.swift b/Transit/TransitTests/TaskLinkMigrationTests.swiftnew file mode 100644index 00000000..819338ba--- /dev/null+++ b/Transit/TransitTests/TaskLinkMigrationTests.swift@@ -0,0 +1,185 @@+import Foundation+import SwiftData+import Testing+@testable import Transit++/// Task 1 source preparation. Missing registered entities must fail at runtime,+/// not by referring to model types that have not been implemented yet.+/// Disk baseline observation below is not a closed-store migration test.+@MainActor @Suite(.serialized)+struct TaskLinkMigrationTests {+    @Test(arguments: ["TaskLinkOccurrence", "TaskLinkRemovalEvidence"])+    func defaultSchemaRegistersCloudCompatibleLinkEntity(name: String) throws {+        let fixture = try TestModelContainer()+        let entity = try #require(fixture.container.schema.entitiesByName[name])+        let occurrenceFields: Set<String> = [+            "id", "kindRawValue", "sourceTaskID", "targetTaskID", "createdAt"+        ]+        let removalFields = occurrenceFields.union(["edgeId", "occurrenceRevision", "removedAt"])+        let expectedFields = name == "TaskLinkOccurrence" ? occurrenceFields : removalFields+        let expectedTypes: [String: Any.Type] = [+            "id": UUID.self, "kindRawValue": String.self, "sourceTaskID": UUID.self,+            "targetTaskID": UUID.self, "createdAt": Date.self, "edgeId": UUID.self,+            "occurrenceRevision": String.self, "removedAt": Date.self+        ]+        #expect(Set(entity.attributes.map(\.name)) == expectedFields)+        #expect(entity.relationships.isEmpty)+        #expect(entity.uniquenessConstraints.isEmpty)+        for attribute in entity.attributes {+            #expect(!attribute.isUnique)+            #expect(attribute.isOptional || attribute.defaultValue != nil)+            let expectedType = try #require(expectedTypes[attribute.name])+            #expect(ObjectIdentifier(attribute.valueType) == ObjectIdentifier(expectedType))+        }+    }++    @Test func preFeatureDiskBaselinePreservesRawFieldsAndReceiptBytes() throws {+        let fixture = try TaskLinkPreFeatureDiskFixture()+        #expect(Set(fixture.owner.container.schema.entities.map(\.name)) == [+            "Project", "TransitTask", "Comment", "Milestone", "SyncHeartbeat", "MCPWriteReceipt"+        ])+        let expected = try fixture.savedFields(in: fixture.owner.context)+        try fixture.owner.context.save()+        #expect(FileManager.default.fileExists(atPath: fixture.storeURL.path))++        // A fresh context avoids registered object identity reuse. The owning+        // container remains open, so this proves saved observation only.+        let observer = ModelContext(fixture.owner.container)+        observer.autosaveEnabled = false+        #expect(try fixture.savedFields(in: observer) == expected)+        let tasks = try observer.fetch(FetchDescriptor<TransitTask>())+        #expect(tasks.count == 2)+        #expect(Set(tasks.map(\.id)).count == 1)+        #expect(Set(tasks.map(\.permanentDisplayId)).count == 1)+        #expect(!observer.hasChanges)+        #expect(!fixture.owner.context.hasChanges)+    }+}++/// Synthetic six-entity schema matching 201205bd's pre-link store. This schema+/// intentionally stays graph-free after the default test fixture is upgraded.+/// Every context is backed by the centrally retained owning TestModelContainer.+@MainActor+struct TaskLinkPreFeatureDiskFixture {+    let owner: TestModelContainer+    let storeURL: URL++    init(directory suppliedDirectory: URL? = nil, schema suppliedSchema: Schema? = nil,+         seed: Bool = true) throws {+        let directory = suppliedDirectory ?? FileManager.default.temporaryDirectory+            .appendingPathComponent("TaskLinkMigration-\(UUID().uuidString)", isDirectory: true)+        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+        storeURL = directory.appendingPathComponent("pre-feature.store")+        let schema = suppliedSchema ?? Schema([+            Project.self, TransitTask.self, Transit.Comment.self, Milestone.self,+            SyncHeartbeat.self, MCPWriteReceipt.self+        ])+        let configuration = ModelConfiguration(schema: schema, url: storeURL, cloudKitDatabase: .none)+        owner = try TestModelContainer(schema: schema, configurations: [configuration])+        owner.context.autosaveEnabled = false+        if seed { seedRows(in: owner.context) }+        // Do not unlink an open SQLite store. TestModelContainer retains it for+        // the process lifetime; all files live in a unique system temp directory.+    }++    private func seedRows(in context: ModelContext) {+        let instant = Date(timeIntervalSince1970: 1_700_000_000)+        let project = Project(name: "Migration", description: "original project",+                              gitRepo: "/synthetic/repo", colorHex: "#123456")+        let milestone = Milestone(name: "Original milestone", description: "preserve",+                                  project: project, displayID: .permanent(41))+        milestone.creationDate = instant+        milestone.lastStatusChangeDate = instant+        let task = TransitTask(name: "Original task", description: "Unicode: café\nsecond line",+                               type: .feature, project: project, displayID: .permanent(42))+        task.milestone = milestone+        task.statusRawValue = "done"+        task.priorityRawValue = "legacy-priority"+        task.creationDate = instant+        task.lastStatusChangeDate = instant+        task.completionDate = instant+        task.metadataJSON = "{ \"original\" : \"bytes\" }"+        let duplicate = TransitTask(name: "Physical duplicate", type: .bug,+                                    project: project, displayID: .permanent(42))+        duplicate.id = task.id+        duplicate.statusRawValue = "future-status"+        duplicate.typeRawValue = "future-type"+        duplicate.creationDate = instant+        duplicate.lastStatusChangeDate = instant+        let comment = Transit.Comment(content: "Saved comment\nnot normalized", authorName: "Agent",+                                      isAgent: true, task: task)+        comment.creationDate = instant+        let receipt = MCPWriteReceipt(localScopeID: "synthetic-origin", tool: "update_task",+                                      key: "migration-original", requestJSON: "{ \"n\":9007199254740993 }",+                                      acceptedAt: instant)+        receipt.stateRawValue = "committed"+        receipt.completedAt = instant+        receipt.expiresAt = instant.addingTimeInterval(7 * 24 * 60 * 60)+        receipt.resultJSON = "{\n  \"outcome\": \"committed\", \"original\": \"café\"\n}\n"+        receipt.resultIsError = false+        let heartbeat = SyncHeartbeat()+        heartbeat.lastBeat = instant+        context.insert(project)+        context.insert(milestone)+        context.insert(task)+        context.insert(duplicate)+        context.insert(comment)+        context.insert(receipt)+        context.insert(heartbeat)+    }++    /// Raw stored values, not effective status/priority/metadata accessors or a+    /// current MCP encoder that could normalize historical content. Receipt JSON+    /// strings remain byte-sensitive, including whitespace and Unicode.+    func savedFields(in context: ModelContext) throws -> Data {+        let projects = try context.fetch(FetchDescriptor<Project>()).map { project in+            ["id": project.id.uuidString, "name": project.name,+             "description": project.projectDescription, "gitRepo": optional(project.gitRepo),+             "colorHex": project.colorHex] as [String: Any]+        }+        let milestones = try context.fetch(FetchDescriptor<Milestone>()).map { milestone in+            ["id": milestone.id.uuidString, "displayId": optional(milestone.permanentDisplayId),+             "name": milestone.name, "description": optional(milestone.milestoneDescription),+             "status": milestone.statusRawValue, "created": milestone.creationDate.timeIntervalSince1970,+             "changed": milestone.lastStatusChangeDate.timeIntervalSince1970,+             "completed": optional(milestone.completionDate?.timeIntervalSince1970),+             "project": optional(milestone.project?.id.uuidString)] as [String: Any]+        }+        let tasks = try context.fetch(FetchDescriptor<TransitTask>()).sorted { $0.name < $1.name }.map { task in+            ["id": task.id.uuidString, "displayId": optional(task.permanentDisplayId), "name": task.name,+             "description": optional(task.taskDescription), "status": task.statusRawValue,+             "type": task.typeRawValue, "priority": task.priorityRawValue,+             "created": task.creationDate.timeIntervalSince1970,+             "changed": task.lastStatusChangeDate.timeIntervalSince1970,+             "completed": optional(task.completionDate?.timeIntervalSince1970),+             "metadataJSON": optional(task.metadataJSON), "project": optional(task.project?.id.uuidString),+             "milestone": optional(task.milestone?.id.uuidString),+             "comments": (task.comments ?? []).map { $0.id.uuidString }.sorted()] as [String: Any]+        }+        let comments = try context.fetch(FetchDescriptor<Transit.Comment>()).map { comment in+            ["id": comment.id.uuidString, "content": comment.content, "author": comment.authorName,+             "isAgent": comment.isAgent, "created": comment.creationDate.timeIntervalSince1970,+             "task": optional(comment.task?.id.uuidString)] as [String: Any]+        }+        let receipts = try context.fetch(FetchDescriptor<MCPWriteReceipt>()).map { receipt in+            ["id": receipt.id.uuidString, "scope": receipt.localScopeID, "tool": receipt.tool,+             "key": receipt.key, "version": receipt.formatVersion, "requestJSON": receipt.requestJSON,+             "state": receipt.stateRawValue, "accepted": receipt.acceptedAt.timeIntervalSince1970,+             "completed": optional(receipt.completedAt?.timeIntervalSince1970),+             "expires": optional(receipt.expiresAt?.timeIntervalSince1970),+             "resultJSON": optional(receipt.resultJSON), "isError": optional(receipt.resultIsError)] as [String: Any]+        }+        let heartbeats = try context.fetch(FetchDescriptor<SyncHeartbeat>()).map { heartbeat in+            ["id": heartbeat.id, "lastBeat": heartbeat.lastBeat.timeIntervalSince1970] as [String: Any]+        }+        return try JSONSerialization.data(withJSONObject: [+            "projects": projects, "milestones": milestones, "tasks": tasks,+            "comments": comments, "receipts": receipts, "heartbeats": heartbeats+        ], options: [.sortedKeys])+    }++    private func optional<T>(_ value: T?) -> Any {+        if let value { return value }+        return NSNull()+    }+}
Transit/TransitTests/TaskLinkNativeLabelTests.swift Changed +18 / -0
diff --git a/Transit/TransitTests/TaskLinkNativeLabelTests.swift b/Transit/TransitTests/TaskLinkNativeLabelTests.swiftnew file mode 100644index 00000000..68d0407e--- /dev/null+++ b/Transit/TransitTests/TaskLinkNativeLabelTests.swift@@ -0,0 +1,18 @@+import Foundation+import Testing+@testable import Transit++@MainActor struct TaskLinkNativeLabelTests {+    @Test(arguments: [+        "dependency|false|Blocks", "dependency|true|Blocked by",+        "association|false|Relates to", "association|true|Relates to",+        "attribution|false|Introduced by", "attribution|true|Introduces",+        "duplicate|false|Duplicate of", "duplicate|true|Duplicated by",+        "future/raw-kind|false|Unknown relation", "future/raw-kind|true|Unknown relation"+    ])+    func labelsAreRelativeToSelectedEndpoint(contract: String) throws {+        let parts = contract.split(separator: "|").map(String.init)+        try #require(parts.count == 3)+        #expect(TaskLinkNativeLabels.title(kind: parts[0], incoming: parts[1] == "true") == parts[2])+    }+}
Transit/TransitTests/TaskLinkNativeProjectionTests.swift Changed +100 / -0
diff --git a/Transit/TransitTests/TaskLinkNativeProjectionTests.swift b/Transit/TransitTests/TaskLinkNativeProjectionTests.swiftnew file mode 100644index 00000000..97a7cf44--- /dev/null+++ b/Transit/TransitTests/TaskLinkNativeProjectionTests.swift@@ -0,0 +1,100 @@+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct TaskLinkNativeProjectionTests {+    @Test func savedRelationshipLabelsIgnoreBothSourceAndEndpointDrafts() throws {+        let fixture = try Fixture()+        fixture.source.name = "source draft"+        fixture.target.name = "endpoint draft"+        let detail = try TaskLinkService(container: fixture.owner.container).savedDetail(for: fixture.source.id)+        #expect(detail.source.name == "source")+        #expect(detail.graph.tasksById[fixture.target.id]?.first?.name == "target")+        #expect(fixture.owner.context.hasChanges)+    }++    @Test(arguments: ["missing", "ambiguous", "unsaved", "pending-delete"])+    func navigationRequiresExactlyOneSavedDestination(fault: String) throws {+        let fixture = try Fixture()+        let id: UUID+        switch fault {+        case "missing": id = UUID()+        case "ambiguous":+            id = fixture.target.id+            let duplicate = TransitTask(name: "collision", type: .feature, project: fixture.project,+                                        displayID: .permanent(3))+            duplicate.id = id+            fixture.owner.context.insert(duplicate)+            try fixture.owner.context.save()+        case "pending-delete":+            id = fixture.target.id+            fixture.owner.context.delete(fixture.target)+        default:+            let pending = TransitTask(name: "not saved", type: .feature, project: fixture.project,+                                      displayID: .permanent(3))+            fixture.owner.context.insert(pending)+            id = pending.id+        }+        #expect(try TaskLinkNavigationResolver.resolve(id, in: fixture.owner.context) == nil)+    }++    @Test func uniqueDestinationKeepsExactUUIDAndUnsavedSourceIsUnavailable() throws {+        let fixture = try Fixture()+        let destination = try TaskLinkNavigationResolver.resolve(fixture.target.id, in: fixture.owner.context)+        let resolved = try #require(destination)+        #expect(resolved.id == fixture.target.id && resolved.id != fixture.source.id)+        let pending = TransitTask(name: "not saved", type: .feature, project: fixture.project,+                                  displayID: .permanent(3))+        fixture.owner.context.insert(pending)+        #expect(throws: TaskLinkGraphError.ambiguousIdentity) {+            try TaskLinkService(container: fixture.owner.container).savedDetail(for: pending.id)+        }+    }++    @Test(arguments: [false, true])+    func staleOrCanceledNativeRefreshCannotReplaceCurrentSelection(cancel: Bool) async throws {+        let fixture = try Fixture()+        let service = TaskLinkService(container: fixture.owner.container)+        let oldDetail = try service.savedDetail(for: fixture.source.id)+        let newDetail = try service.savedDetail(for: fixture.target.id)+        let state = TaskLinkNativeDetailState()+        let gate = Gate()+        let old = Task { await state.refresh(source: fixture.source.id) { _ in try await gate.wait() } }+        for _ in 0..<100 where gate.continuation == nil { await Task.yield() }+        try #require(gate.continuation != nil)+        if cancel { old.cancel() } else { await state.refresh(source: fixture.target.id) { _ in newDetail } }+        gate.continuation?.resume(returning: oldDetail)+        await old.value+        #expect(state.detail?.source.id == (cancel ? nil : fixture.target.id))+        if !cancel { #expect(state.sourceID == fixture.target.id) }+    }++    @MainActor private final class Gate {+        var continuation: CheckedContinuation<TaskLinkSavedDetail, Error>?+        func wait() async throws -> TaskLinkSavedDetail {+            try await withCheckedThrowingContinuation { continuation = $0 }+        }+    }++    @MainActor private struct Fixture {+        let owner: TestModelContainer+        let project: Project+        let source: TransitTask+        let target: TransitTask+        init() throws {+            owner = try TestModelContainer()+            owner.context.autosaveEnabled = false+            project = Project(name: "native", description: "", gitRepo: nil, colorHex: "blue")+            source = TransitTask(name: "source", type: .feature, project: project, displayID: .permanent(1))+            target = TransitTask(name: "target", type: .feature, project: project, displayID: .permanent(2))+            owner.context.insert(project)+            owner.context.insert(source)+            owner.context.insert(target)+            owner.context.insert(TaskLinkOccurrence(id: UUID(), kindRawValue: "association",+                sourceTaskID: source.id, targetTaskID: target.id, createdAt: Date()))+            try owner.context.save()+        }+    }+}
Transit/TransitTests/TaskLinkNativeRefreshTests.swift Changed +87 / -0
diff --git a/Transit/TransitTests/TaskLinkNativeRefreshTests.swift b/Transit/TransitTests/TaskLinkNativeRefreshTests.swiftnew file mode 100644index 00000000..15a728e2--- /dev/null+++ b/Transit/TransitTests/TaskLinkNativeRefreshTests.swift@@ -0,0 +1,87 @@+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct TaskLinkNativeRefreshTests {+    @Test func refreshBurstCapturesLatestCompleteSavedGraphOnce() async throws {+        let owner = try TestModelContainer()+        owner.context.autosaveEnabled = false+        let project = Project(name: "native", description: "", gitRepo: nil, colorHex: "blue")+        let source = TransitTask(name: "before", type: .feature, project: project, displayID: .permanent(1))+        owner.context.insert(project)+        owner.context.insert(source)+        try owner.context.save()+        let service = TaskLinkService(container: owner.container)+        let state = TaskLinkNativeDetailState()+        await state.refresh(source: source.id) { try service.savedDetail(for: $0) }+        try #require(state.detail?.source.name == "before")+        let gates = [Gate(), Gate(), Gate()]+        var captures = 0+        var jobs: [Task<Void, Never>] = []+        for gate in gates {+            jobs.append(Task {+                await state.refresh(source: source.id, wait: { try await gate.wait() }, provider: {+                    captures += 1+                    return try service.savedDetail(for: $0)+                })+            })+            for _ in 0..<100 where gate.continuation == nil { await Task.yield() }+            try #require(gate.continuation != nil)+            #expect(state.detail == nil)+        }+        jobs[1].cancel()+        let peer = ModelContext(owner.container)+        peer.autosaveEnabled = false+        let saved = try #require(peer.fetch(FetchDescriptor<TransitTask>()).first)+        saved.name = "latest saved source"+        let unrelatedProject = Project(name: "elsewhere", description: "", gitRepo: nil, colorHex: "red")+        let unrelated = TransitTask(name: "outside", type: .feature, project: unrelatedProject,+                                    displayID: .permanent(2))+        let endpoint = TransitTask(name: "outside endpoint", type: .feature, project: unrelatedProject,+                                  displayID: .permanent(3))+        let edgeID = UUID()+        peer.insert(unrelatedProject)+        peer.insert(unrelated)+        peer.insert(endpoint)+        peer.insert(TaskLinkOccurrence(id: edgeID, kindRawValue: "association",+            sourceTaskID: unrelated.id, targetTaskID: endpoint.id, createdAt: Date()))+        try peer.save()+        for gate in gates { gate.continuation?.resume() }+        for job in jobs { await job.value }+        #expect(captures == 1)+        #expect(state.detail?.source.name == "latest saved source")+        #expect(state.detail?.graph.tasksById[unrelated.id]?.first?.name == "outside")+        #expect(state.detail?.graph.occurrences.contains { $0.id == edgeID } == true)+    }++    @Test func alreadyCanceledRefreshDoesNotInvalidateCurrentObservation() async throws {+        let owner = try TestModelContainer()+        let project = Project(name: "native", description: "", gitRepo: nil, colorHex: "blue")+        let source = TransitTask(name: "current", type: .feature, project: project, displayID: .permanent(1))+        owner.context.insert(project)+        owner.context.insert(source)+        try owner.context.save()+        let service = TaskLinkService(container: owner.container)+        let state = TaskLinkNativeDetailState()+        await state.refresh(source: source.id) { try service.savedDetail(for: $0) }+        let obsolete = Task {+            await state.refresh(source: UUID(), debounce: .seconds(60)) {+                Issue.record("Canceled request must not capture")+                return try service.savedDetail(for: $0)+            }+        }+        obsolete.cancel()+        await obsolete.value+        #expect(state.sourceID == source.id)+        #expect(state.detail?.source.name == "current")+    }++    @MainActor private final class Gate {+        var continuation: CheckedContinuation<Void, Error>?+        func wait() async throws {+            try await withCheckedThrowingContinuation { continuation = $0 }+        }+    }+}
Transit/TransitTests/TaskLinkOwnedPhaseTests.swift Changed +78 / -0
diff --git a/Transit/TransitTests/TaskLinkOwnedPhaseTests.swift b/Transit/TransitTests/TaskLinkOwnedPhaseTests.swiftnew file mode 100644index 00000000..acb4ff8f--- /dev/null+++ b/Transit/TransitTests/TaskLinkOwnedPhaseTests.swift@@ -0,0 +1,78 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct TaskLinkOwnedPhaseTests {+    @Test func sourceConflictPreventsGraphCallback() async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        var calls = 0+        var arguments = try fixture.updateArguments()+        arguments["expectedRevision"] = "r1:" + String(repeating: "0", count: 64)+        let policy = MCPBatchWritePolicy(makeCommitServices: fixture.commitServices,+            afterTaskApply: { _, _, _ in calls += 1 })+        let result = await fixture.coordinator(save: { context, _ in try context.save() }).execute(+            tool: "update_task", arguments: arguments, batchPolicy: policy)+        #expect(try fixture.decode(result)["outcome"] as? String == "rejected")+        #expect(calls == 0)+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "source")+    }++    @Test func terminalSnapshotIncludesOwnedGraphAndReplayDoesNotRunCallback() async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let inserted = UUID(), evidence = UUID()+        var calls = 0+        let policy = MCPBatchWritePolicy(makeCommitServices: fixture.commitServices,+            afterTaskApply: { _, task, services in+                #expect(task.modelContext === services.context)+                calls += 1+                try fixture.stageGraph(context: services.context, insertedID: inserted, evidenceID: evidence)+            })+        let arguments = try fixture.updateArguments()+        let coordinator = fixture.coordinator(save: { context, _ in try context.save() })+        let first = await coordinator.execute(tool: "update_task", arguments: arguments, batchPolicy: policy)+        #expect(try fixture.decode(first)["outcome"] as? String == "committed")+        let observer = try fixture.observer()+        let saved = try fixture.task(fixture.source.id, in: observer.context)+        let record = try #require(try fixture.decode(first)["record"] as? [String: Any])+        #expect(record["revision"] as? String == (try MCPRecordSnapshot.task(saved, in: observer.context).revision))+        let replay = await coordinator.execute(tool: "update_task", arguments: arguments, batchPolicy: policy)+        #expect(first.content.first?.text == replay.content.first?.text)+        #expect(calls == 1)+    }++    @Test(arguments: ["callback", "save", "encode"])+    func ownedGraphDomainAndReceiptStayAllOrNoneAfterCallback(failure: String) async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let inserted = UUID(), evidence = UUID()+        let policy = MCPBatchWritePolicy(makeCommitServices: fixture.commitServices,+            afterTaskApply: { _, _, services in+                try fixture.stageGraph(context: services.context, insertedID: inserted, evidenceID: evidence)+                if failure == "callback" { throw TaskLinkCommitDiskFixture.Failure.injected }+            })+        let coordinator = fixture.coordinator(save: { context, stage in+            if case .commit = stage, failure == "save" { throw TaskLinkCommitDiskFixture.Failure.injected }+            try context.save()+        }, encode: { envelope in+            if failure == "encode", envelope["outcome"] as? String == "committed" {+                throw TaskLinkCommitDiskFixture.Failure.injected+            }+            return try MCPWriteOutcome.encode(envelope)+        })+        let result = await coordinator.execute(tool: "update_task", arguments: try fixture.updateArguments(),+                                               batchPolicy: policy)+        #expect(try fixture.decode(result)["outcome"] as? String == "rejected")+        #expect(!fixture.owner.context.hasChanges)+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "source")+        let edges = try observer.context.fetch(FetchDescriptor<TaskLinkOccurrence>())+        #expect(edges.count == 1 && edges.first?.id == fixture.edge.id)+        let removals = try observer.context.fetch(FetchDescriptor<TaskLinkRemovalEvidence>())+        #expect(!removals.contains { $0.id == evidence })+        #expect(try fixture.receipts(in: observer.context).first?.stateRawValue == "rejected")+    }+}+#endif
Transit/TransitTests/TaskLinkOwnedScopeTests.swift Changed +170 / -0
diff --git a/Transit/TransitTests/TaskLinkOwnedScopeTests.swift b/Transit/TransitTests/TaskLinkOwnedScopeTests.swiftnew file mode 100644index 00000000..9f115af7--- /dev/null+++ b/Transit/TransitTests/TaskLinkOwnedScopeTests.swift@@ -0,0 +1,170 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct TaskLinkOwnedScopeTests {+    @Test func sealedScopeAppliesAndSavesGraphDomainAndReceiptTogether() async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let inserted = UUID(), removed = UUID()+        var validatedContext: ModelContext?+        var savedContext: ModelContext?+        let policy = MCPBatchWritePolicy(makeCommitServices: fixture.commitServices, afterTaskApply: { _, _, services in+            try fixture.stageGraph(context: services.context, insertedID: inserted, evidenceID: removed)+        }, validateBeforeApply: { _, context in+            #expect(context !== fixture.owner.context && !context.autosaveEnabled && !context.hasChanges)+            validatedContext = context+        })+        let coordinator = fixture.coordinator(save: { context, stage in+            if case .commit = stage { savedContext = context }+            try context.save()+        })+        let result = await coordinator.execute(tool: "update_task", arguments: try fixture.updateArguments(),+                                               batchPolicy: policy)+        #expect(try fixture.decode(result)["outcome"] as? String == "committed")+        #expect(savedContext === validatedContext && savedContext !== fixture.owner.context)+        #expect(!fixture.owner.context.hasChanges)+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "committed update")+        let edges = try observer.context.fetch(FetchDescriptor<TaskLinkOccurrence>())+        #expect(edges.count == 1 && edges.first?.id == inserted)+        let removals = try observer.context.fetch(FetchDescriptor<TaskLinkRemovalEvidence>())+        #expect(removals.filter { $0.id == removed }.count == 1)+        let receipts = try fixture.receipts(in: observer.context)+        #expect(receipts.count == 1 && receipts.first?.stateRawValue == "committed")+        #expect(receipts.first?.resultJSON == result.content.first?.text)+    }++    @Test(arguments: ["save", "encode", "recovery"])+    func scopedFailureRollsBackOnlyOwnedGraphAndRetainsOutcomeEvidence(failure: String) async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let inserted = UUID(), removed = UUID()+        let policy = MCPBatchWritePolicy(makeCommitServices: fixture.commitServices, afterTaskApply: { _, _, services in+            try fixture.stageGraph(context: services.context, insertedID: inserted, evidenceID: removed)+        })+        let coordinator = fixture.coordinator(save: { context, stage in+            if case .commit = stage, failure != "encode" { throw TaskLinkCommitDiskFixture.Failure.injected }+            try context.save()+        }, encode: { envelope in+            if failure == "encode", envelope["outcome"] as? String == "committed" {+                throw TaskLinkCommitDiskFixture.Failure.injected+            }+            return try MCPWriteOutcome.encode(envelope)+        }, recovery: {+            if failure == "recovery" { throw TaskLinkCommitDiskFixture.Failure.injected }+        })+        let result = await coordinator.execute(tool: "update_task", arguments: try fixture.updateArguments(),+                                               batchPolicy: policy)+        #expect(try fixture.decode(result)["outcome"] as? String == (failure == "recovery" ? "uncertain" : "rejected"))+        #expect(!fixture.owner.context.hasChanges)+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "source")+        let edges = try observer.context.fetch(FetchDescriptor<TaskLinkOccurrence>())+        #expect(edges.count == 1 && edges.first?.id == fixture.edge.id)+        let evidence = try observer.context.fetch(FetchDescriptor<TaskLinkRemovalEvidence>())+        #expect(evidence.count == 1 && !evidence.contains { $0.id == removed })+        #expect(try fixture.historicReceipt(in: observer.context).resultJSON == fixture.historicJSON)+        let receipts = try fixture.receipts(in: observer.context)+        #expect(receipts.count == 1)+        #expect(receipts.first?.stateRawValue == (failure == "recovery" ? "accepted" : "rejected"))+    }++    @Test(arguments: ["throw", "mismatch", "dirty", "shared-draft"])+    func invalidFactoryStopsWithoutSavingOrRollingBackSharedDrafts(fault: String) async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let arguments = try fixture.updateArguments()+        var terminalSaves = 0+        let policy = MCPBatchWritePolicy(makeCommitServices: { context in+            switch fault {+            case "throw": throw TaskLinkCommitDiskFixture.Failure.injected+            case "mismatch": return fixture.commitServices(in: fixture.owner.context)+            case "dirty":+                context.insert(Project(name: "owned pending", description: "", gitRepo: nil, colorHex: "112233"))+            case "shared-draft": fixture.source.name = "UI draft from callback"+            default: break+            }+            return fixture.commitServices(in: context)+        })+        let coordinator = fixture.coordinator(save: { context, stage in+            if case .commit = stage { terminalSaves += 1 }+            if case .rejection = stage { terminalSaves += 1 }+            try context.save()+        })+        let result = await coordinator.execute(tool: "update_task", arguments: arguments, batchPolicy: policy)+        #expect(try fixture.decode(result)["outcome"] as? String == "uncertain")+        #expect(terminalSaves == 0)+        #expect(fixture.owner.context.hasChanges == (fault == "shared-draft"))+        if fault == "shared-draft" { #expect(fixture.source.name == "UI draft from callback") }+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "source")+        #expect(try fixture.receipts(in: observer.context).first?.stateRawValue == "accepted")+    }++    @Test(arguments: ["id", "payload", "format", "scope", "tool"])+    func refetchedReceiptMustMatchEntireOriginalAcceptanceBinding(field: String) async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let policy = MCPBatchWritePolicy(makeCommitServices: fixture.commitServices)+        var commitSaves = 0+        let coordinator = fixture.coordinator(save: { context, stage in+            if case .commit = stage { commitSaves += 1 }+            try context.save()+        }, preparation: { _ in+            let matches = try fixture.receipts(in: fixture.owner.context)+            let receipt = try #require(matches.count == 1 ? matches.first : nil)+            switch field {+            case "id": receipt.id = UUID()+            case "payload": receipt.requestJSON = "{\"changed\":true}"+            case "format": receipt.formatVersion = 2+            case "scope": receipt.localScopeID = "foreign-scope"+            case "tool": receipt.tool = "add_comment"+            default: break+            }+            try fixture.owner.context.save()+        })+        let result = await coordinator.execute(tool: "update_task", arguments: try fixture.updateArguments(),+                                               batchPolicy: policy)+        #expect(try fixture.decode(result)["outcome"] as? String == "uncertain")+        #expect(commitSaves == 0)+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "source")+        #expect(try fixture.receipts(in: observer.context).first?.stateRawValue == "accepted")+    }++    @Test func dirtyReplayNeverConstructsOwnedScopeOrTouchesDrafts() async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let arguments = try fixture.updateArguments()+        var factories = 0, saves = 0+        let policy = MCPBatchWritePolicy(makeCommitServices: { context in+            factories += 1+            return fixture.commitServices(in: context)+        })+        let coordinator = fixture.coordinator(save: { context, _ in saves += 1; try context.save() })+        let first = await coordinator.execute(tool: "update_task", arguments: arguments, batchPolicy: policy)+        #expect(try fixture.decode(first)["outcome"] as? String == "committed")+        let savedCount = saves+        fixture.source.name = "pending draft"+        let replay = await coordinator.execute(tool: "update_task", arguments: arguments, batchPolicy: policy)+        #expect(replay.content.first?.text == first.content.first?.text)+        #expect(factories == 1 && saves == savedCount)+        #expect(fixture.source.name == "pending draft" && fixture.owner.context.hasChanges)+    }++    @Test func preparationErrorUsesOwnedRejectionScopeAndOriginalKeyReplay() async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let arguments = try fixture.updateArguments()+        var rejectionWasOwned = false+        let policy = MCPBatchWritePolicy(makeCommitServices: fixture.commitServices)+        let coordinator = fixture.coordinator(save: { context, stage in+            if case .rejection = stage { rejectionWasOwned = context !== fixture.owner.context }+            try context.save()+        }, preparation: { _ in throw TaskLinkCommitDiskFixture.Failure.injected })+        let result = await coordinator.execute(tool: "update_task", arguments: arguments, batchPolicy: policy)+        #expect(try fixture.decode(result)["outcome"] as? String == "rejected")+        #expect(rejectionWasOwned && !fixture.owner.context.hasChanges)+        let replay = await coordinator.execute(tool: "update_task", arguments: arguments, batchPolicy: policy)+        #expect(replay.content.first?.text == result.content.first?.text)+    }+}+#endif
Transit/TransitTests/TaskLinkParticipatingBoundaryTests.swift Changed +220 / -0
diff --git a/Transit/TransitTests/TaskLinkParticipatingBoundaryTests.swift b/Transit/TransitTests/TaskLinkParticipatingBoundaryTests.swiftnew file mode 100644index 00000000..7a5bc087--- /dev/null+++ b/Transit/TransitTests/TaskLinkParticipatingBoundaryTests.swift@@ -0,0 +1,220 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++/// Participating-operation controls; no exclusion of independent writers.+@MainActor @Suite(.serialized)+struct TaskLinkParticipatingBoundaryTests {+    @Test func existingPolicyMustRejectChangedSavedRevisionDespiteRegisteredSource() async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let arguments = try fixture.updateArguments()+        let oldRevision = try #require(arguments["expectedRevision"] as? String)+        let peer = try fixture.observer()+        var changedSavedRevision = false+        let coordinator = fixture.coordinator(save: { context, _ in try context.save() }, preparation: { _ in+            let source = try fixture.task(fixture.source.id, in: peer.context)+            source.name = "outside saved update"+            try peer.context.save()+            let fresh = try fixture.observer()+            let savedSource = try fixture.task(fixture.source.id, in: fresh.context)+            changedSavedRevision = try MCPRecordSnapshot.task(savedSource, in: fresh.context).revision != oldRevision+        })+        // Genuine existing-SUT expectation: no custom fresh validator repairs+        // the long-lived policy/apply context. Runtime establishes RED/GREEN.+        let result = await coordinator.execute(tool: "update_task", arguments: arguments, batchPolicy: .init())+        #expect(changedSavedRevision)+        #expect(try fixture.decode(result)["outcome"] as? String == "rejected")+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "outside saved update")+        #expect(try fixture.receipts(in: observer.context).first?.stateRawValue == "rejected")+    }++    @Test func freshSavedEndpointRevisionRejectsChangeHiddenByRegisteredEndpoint() async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let arguments = try fixture.updateArguments()+        let endpointRevision = try MCPRecordSnapshot.task(fixture.target, in: fixture.owner.context).revision+        let peer = try fixture.observer()+        var observedChangedEndpoint = false+        let coordinator = fixture.coordinator(save: { context, _ in try context.save() }, preparation: { _ in+            let endpoint = try fixture.task(fixture.target.id, in: peer.context)+            endpoint.name = "changed saved endpoint label"+            try peer.context.save()+        })+        let policy = MCPBatchWritePolicy { _, _ in+            let fresh = try fixture.observer()+            let endpoint = try fixture.task(fixture.target.id, in: fresh.context)+            let snapshot = try MCPRecordSnapshot.task(endpoint, in: fresh.context)+            observedChangedEndpoint = snapshot.revision != endpointRevision+            guard snapshot.revision == endpointRevision else {+                throw MCPWriteFailure("REVISION_CONFLICT", "Endpoint changed", currentRecord: snapshot.record)+            }+        }+        let result = await coordinator.execute(tool: "update_task", arguments: arguments, batchPolicy: policy)+        #expect(observedChangedEndpoint)+        #expect(try fixture.decode(result)["outcome"] as? String == "rejected")+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "source")+        #expect(try fixture.task(fixture.target.id, in: observer.context).name == "changed saved endpoint label")+        let replay = await coordinator.execute(tool: "update_task", arguments: arguments, batchPolicy: policy)+        #expect(replay.content.first?.text == result.content.first?.text)+    }++    @Test func freshSavedCycleBeforeApplyRejectsAllOwnedEffects() async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let peer = try fixture.observer()+        let proposedID = UUID(), removalID = UUID()+        let coordinator = fixture.coordinator(save: { context, _ in try context.save() }, preparation: { _ in+            peer.context.insert(TaskLinkOccurrence(id: UUID(), kindRawValue: "dependency",+                sourceTaskID: fixture.source.id, targetTaskID: fixture.target.id, createdAt: fixture.instant))+            try peer.context.save()+        })+        let policy = MCPBatchWritePolicy(afterTaskApply: { _, _, services in+            try fixture.stageGraph(context: services.context, insertedID: proposedID, evidenceID: removalID)+        }, validateBeforeApply: { _, _ in+            let fresh = try fixture.observer()+            let edges = try fresh.context.fetch(FetchDescriptor<TaskLinkOccurrence>())+            guard !fixture.hasCycle(edges.filter { $0.kindRawValue == "dependency" }) else {+                throw MCPWriteFailure("GRAPH_CONFLICT", "Saved cycle before apply")+            }+        })+        let result = await coordinator.execute(tool: "update_task", arguments: try fixture.updateArguments(),+                                               batchPolicy: policy)+        #expect(try fixture.decode(result)["outcome"] as? String == "rejected")+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "source")+        let edges = try observer.context.fetch(FetchDescriptor<TaskLinkOccurrence>())+        #expect(fixture.hasCycle(edges) && !edges.contains { $0.id == proposedID })+        let removals = try observer.context.fetch(FetchDescriptor<TaskLinkRemovalEvidence>())+        #expect(!removals.contains { $0.id == removalID })+        #expect(try fixture.receipts(in: observer.context).first?.stateRawValue == "rejected")+    }++    @Test func ownedGraphDomainAndTerminalReceiptCommitTogether() async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let insertedID = UUID(), evidenceID = UUID()+        let coordinator = fixture.coordinator(save: { context, _ in try context.save() })+        let policy = MCPBatchWritePolicy(afterTaskApply: { _, _, services in+            try fixture.stageGraph(context: services.context, insertedID: insertedID, evidenceID: evidenceID)+        })+        let result = await coordinator.execute(tool: "update_task", arguments: try fixture.updateArguments(),+                                               batchPolicy: policy)+        #expect(try fixture.decode(result)["outcome"] as? String == "committed")+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "committed update")+        let edges = try observer.context.fetch(FetchDescriptor<TaskLinkOccurrence>())+        let edge = try #require(edges.count == 1 ? edges.first : nil)+        #expect(edge.id == insertedID && edge.kindRawValue == "association")+        #expect(edge.sourceTaskID == fixture.source.id && edge.targetTaskID == fixture.target.id)+        #expect(edge.createdAt == fixture.instant)+        let removals = try observer.context.fetch(FetchDescriptor<TaskLinkRemovalEvidence>())+        let matching = removals.filter { $0.id == evidenceID }+        let removal = try #require(matching.count == 1 ? matching.first : nil)+        #expect(removal.edgeId == fixture.edge.id && removal.kindRawValue == "dependency")+        #expect(removal.sourceTaskID == fixture.target.id && removal.targetTaskID == fixture.source.id)+        #expect(removal.createdAt == fixture.instant && removal.removedAt == fixture.instant)+        #expect(removal.occurrenceRevision == "l1:" + String(repeating: "0", count: 64))+        let savedReceipts = try fixture.receipts(in: observer.context)+        let receipt = try #require(savedReceipts.count == 1 ? savedReceipts.first : nil)+        #expect(receipt.stateRawValue == "committed" && receipt.resultIsError == false)+        #expect(receipt.resultJSON == result.content.first?.text)+        #expect(try fixture.historicReceipt(in: observer.context).resultJSON == fixture.historicJSON)+    }++    @Test func participatingOperationCannotEnterDuringSynchronousFinalPhase() async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        var events: [String] = []+        var queued: Task<Bool, Error>?+        var coordinator: MCPWriteCoordinator!+        var commitNumber = 0+        let policy = MCPBatchWritePolicy { command, _ in+            let first = command.key == "boundary-update"+            events.append(first ? "first.validate" : "peer.validate")+            if first {+                queued = Task { @MainActor in+                    events.append("peer.enter")+                    var arguments = try fixture.updateArguments()+                    arguments["idempotencyKey"] = "participating-peer"+                    arguments["name"] = "peer update"+                    let result = await coordinator.execute(tool: "update_task", arguments: arguments,+                                                           batchPolicy: .init())+                    return try fixture.decode(result)["outcome"] as? String == "committed"+                }+            }+        }+        coordinator = fixture.coordinator(save: { context, stage in+            if case .commit = stage {+                commitNumber += 1+                let prefix = commitNumber == 1 ? "first" : "peer"+                events.append(prefix + ".save.begin")+                try context.save()+                events.append(prefix + ".save.end")+            } else { try context.save() }+        }, encode: { envelope in+            if envelope["outcome"] as? String == "committed" {+                let prefix = envelope["idempotencyKey"] as? String == "boundary-update" ? "first" : "peer"+                events.append(prefix + ".encode")+            }+            return try MCPWriteOutcome.encode(envelope)+        })+        let first = await coordinator.execute(tool: "update_task", arguments: try fixture.updateArguments(),+                                              batchPolicy: policy)+        #expect(try fixture.decode(first)["outcome"] as? String == "committed")+        let peerTask = try #require(queued)+        let peerCommitted = try await peerTask.value+        #expect(peerCommitted)+        #expect(events == ["first.validate", "first.encode", "first.save.begin", "first.save.end",+                           "peer.enter", "peer.encode", "peer.save.begin", "peer.save.end"])+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "peer update")+        #expect(try fixture.receipts(in: observer.context).first?.stateRawValue == "committed")+        let key = "participating-peer"+        let peerReceipts = try observer.context.fetch(FetchDescriptor<MCPWriteReceipt>(+            predicate: #Predicate { $0.key == key }))+        #expect(peerReceipts.count == 1 && peerReceipts.first?.stateRawValue == "committed")+        // This exercises participating MainActor jobs only, not outside imports.+    }++}++@MainActor+extension TaskLinkCommitDiskFixture {+    func receipts(in context: ModelContext) throws -> [MCPWriteReceipt] {+        let key = "boundary-update"+        return try context.fetch(FetchDescriptor<MCPWriteReceipt>(predicate: #Predicate { $0.key == key }))+    }++    /// Reads the complete saved dependency predicate for this small fixture,+    /// after its proposed removal. Associations do not contribute cycle edges.+    func hasCycle(_ edges: [TaskLinkOccurrence]) -> Bool {+        var visiting = Set<UUID>(), visited = Set<UUID>()+        let adjacency = Dictionary(grouping: edges, by: \.sourceTaskID)+        func visit(_ id: UUID) -> Bool {+            if visiting.contains(id) { return true }+            if visited.contains(id) { return false }+            visiting.insert(id)+            for edge in adjacency[id] ?? [] where visit(edge.targetTaskID) { return true }+            visiting.remove(id)+            visited.insert(id)+            return false+        }+        return adjacency.keys.contains { visit($0) }+    }++    func stageGraph(context: ModelContext,+                    insertedID: UUID, evidenceID: UUID) throws {+        let edgeID = edge.id+        var descriptor = FetchDescriptor<TaskLinkOccurrence>(predicate: #Predicate { $0.id == edgeID })+        descriptor.fetchLimit = 2+        let matches = try context.fetch(descriptor)+        let savedEdge = try #require(matches.count == 1 ? matches.first : nil)+        context.delete(savedEdge)+        context.insert(TaskLinkOccurrence(id: insertedID, kindRawValue: "association",+            sourceTaskID: source.id, targetTaskID: target.id, createdAt: instant))+        context.insert(TaskLinkRemovalEvidence(id: evidenceID, edgeId: edge.id, kindRawValue: "dependency",+            sourceTaskID: target.id, targetTaskID: source.id, createdAt: instant,+            occurrenceRevision: "l1:" + String(repeating: "0", count: 64), removedAt: instant))+    }+}+#endif
Transit/TransitTests/TaskLinkPlanTests.swift Changed +196 / -0
diff --git a/Transit/TransitTests/TaskLinkPlanTests.swift b/Transit/TransitTests/TaskLinkPlanTests.swiftnew file mode 100644index 00000000..8c9fd9de--- /dev/null+++ b/Transit/TransitTests/TaskLinkPlanTests.swift@@ -0,0 +1,196 @@+import Foundation+import Testing+@testable import Transit++@MainActor+struct TaskLinkPlanTests {+    @Test func additionCannotCloseDependencyCycle() throws {+        let source = task(1), target = task(2)+        let graph = try project([source, target], [edge(1, target.id, source.id)])+        #expect(throws: TaskLinkGraphError.self) {+            try TaskLinkPlan.validate(delta: [.add(type: .blocks, target: target.id)], source: source.id,+                                      preconditions: [target.id: "current"],+                                      revisions: [target.id: "current"], savedGraph: graph)+        }+    }++    @Test func exactRemovalCanIncrementallyRepairCycle() throws {+        let source = task(1), target = task(2), row = edge(1, source.id, target.id)+        let graph = try project([source, target], [row, edge(2, target.id, source.id)])+        let plan = try TaskLinkPlan.validate(delta: [.remove(edgeId: row.id,+                                                           occurrenceRevision: TaskLinkGraph.occurrenceRevision(row))],+            source: source.id, preconditions: [target.id: "current"],+                                      revisions: [target.id: "current"], savedGraph: graph)+        #expect(plan.removals == [row])+        #expect(plan.additions.isEmpty)+    }++    @Test func missingEndpointRemovalDoesNotInventGuard() throws {+        let source = task(1), row = edge(1, source.id, UUID())+        let graph = try project([source], [row])+        let plan = try TaskLinkPlan.validate(delta: [.remove(edgeId: row.id,+                                                           occurrenceRevision: TaskLinkGraph.occurrenceRevision(row))],+            source: source.id, preconditions: [:], revisions: [:], savedGraph: graph)+        #expect(plan.affectedEndpoints.isEmpty)+        #expect(plan.removals == [row])+    }++    @Test func alreadyPresentAddIsNoOpWithoutExtraEndpointGuard() throws {+        let source = task(1), target = task(2), row = edge(1, source.id, target.id)+        let graph = try project([source, target], [row])+        let plan = try TaskLinkPlan.validate(delta: [.add(type: .blocks, target: target.id)], source: source.id,+                                            preconditions: [:], revisions: [:], savedGraph: graph)+        #expect(plan.isNoOp)+        #expect(throws: TaskLinkGraphError.self) {+            try TaskLinkPlan.validate(delta: [.add(type: .blocks, target: target.id)], source: source.id,+                                      preconditions: [target.id: "extra"],+                                      revisions: [target.id: "extra"], savedGraph: graph)+        }+    }++    @Test func removeAndAddSameRelationRejectsEvenIfAddWasNoOp() throws {+        let source = task(1), target = task(2), row = edge(1, source.id, target.id)+        let graph = try project([source, target], [row])+        #expect(throws: TaskLinkGraphError.self) {+            try TaskLinkPlan.validate(delta: [.remove(edgeId: row.id,+                                                      occurrenceRevision: TaskLinkGraph.occurrenceRevision(row)),+                                             .add(type: .blocks, target: target.id)], source: source.id,+                                      preconditions: [target.id: "current"],+                                      revisions: [target.id: "current"], savedGraph: graph)+        }+    }++    @Test func physicalSelectorCollisionNeverChoosesFirst() throws {+        let source = task(1), target = task(2), row = edge(1, source.id, target.id)+        let collision = TaskLinkOccurrenceValue(physicalKey: Data([9]), id: row.id, kind: row.kind,+                                               source: row.source, target: row.target, createdAt: row.createdAt)+        let graph = try project([source, target], [row, collision])+        #expect(throws: TaskLinkGraphError.self) {+            try TaskLinkPlan.validate(delta: [.remove(edgeId: row.id,+                                                      occurrenceRevision: TaskLinkGraph.occurrenceRevision(row))],+                source: source.id, preconditions: [target.id: "current"],+                                      revisions: [target.id: "current"], savedGraph: graph)+        }+    }++    @Test func duplicateCardinalityIsValidatedOnCompleteProposedResult() throws {+        let source = task(1), old = task(2), new = task(3)+        let original = TaskLinkOccurrenceValue(physicalKey: Data([1]), id: UUID(), kind: "duplicate",+                                              source: source.id, target: old.id,+                                              createdAt: Date(timeIntervalSince1970: 100))+        let graph = try project([source, old, new], [original])+        #expect(throws: TaskLinkGraphError.self) {+            try TaskLinkPlan.validate(delta: [.add(type: .duplicateOf, target: new.id)], source: source.id,+                preconditions: [new.id: "current"], revisions: [new.id: "current"], savedGraph: graph)+        }+    }++    @Test func duplicateRetargetRemovesOnlyExactOldOccurrence() throws {+        let source = task(1), old = task(2), new = task(3)+        let original = TaskLinkOccurrenceValue(physicalKey: Data([1]), id: UUID(), kind: "duplicate",+                                              source: source.id, target: old.id,+                                              createdAt: Date(timeIntervalSince1970: 100))+        let graph = try project([source, old, new], [original])+        let guards = [old.id: "old", new.id: "new"]+        let plan = try TaskLinkPlan.validate(delta: [+            .remove(edgeId: original.id, occurrenceRevision: TaskLinkGraph.occurrenceRevision(original)),+            .add(type: .duplicateOf, target: new.id)+        ], source: source.id, preconditions: guards, revisions: guards, savedGraph: graph)+        #expect(plan.removals == [original])+        let newRelation = TaskLinkType.duplicateOf.normalized(source: source.id, target: new.id)+        #expect(plan.additions.map(\.relation) == [newRelation])+        #expect(plan.affectedEndpoints == Set([old.id, new.id]))+    }++    @Test(arguments: [false, true])+    func exactRemovedSelectorNoOpRequiresUnexpiredEvidence(expired: Bool) throws {+        let source = task(1), row = edge(1, source.id, UUID())+        let revision = try TaskLinkGraph.occurrenceRevision(row)+        let evidence = TaskLinkRemovalValue(physicalKey: Data([9]), id: UUID(), edgeId: row.id,+            kind: row.kind, source: row.source, target: row.target, createdAt: row.createdAt,+            occurrenceRevision: revision, removedAt: Date(timeIntervalSince1970: 150))+        let graph = try TaskLinkGraph.project(tasks: [source], occurrences: [], removalEvidence: [evidence],+            evaluationInstant: Date(timeIntervalSince1970: expired ? 150 + TaskLinkGraph.evidenceLifetime : 200))+        if expired {+            #expect(throws: TaskLinkGraphError.self) {+                try TaskLinkPlan.validate(delta: [.remove(edgeId: row.id, occurrenceRevision: revision)],+                    source: source.id, preconditions: [:], revisions: [:], savedGraph: graph)+            }+        } else {+            let plan = try TaskLinkPlan.validate(delta: [.remove(edgeId: row.id, occurrenceRevision: revision)],+                source: source.id, preconditions: [:], revisions: [:], savedGraph: graph)+            #expect(plan.isNoOp)+            #expect(plan.affectedEndpoints.isEmpty)+        }+    }++    @Test func removedEvidenceAndSameLogicalReAddRejectsInOneRequest() throws {+        let source = task(1), target = task(2), row = edge(1, source.id, target.id)+        let revision = try TaskLinkGraph.occurrenceRevision(row)+        let evidence = TaskLinkRemovalValue(physicalKey: Data([9]), id: UUID(), edgeId: row.id,+            kind: row.kind, source: row.source, target: row.target, createdAt: row.createdAt,+            occurrenceRevision: revision, removedAt: Date(timeIntervalSince1970: 150))+        let graph = try TaskLinkGraph.project(tasks: [source, target], occurrences: [], removalEvidence: [evidence],+                                             evaluationInstant: Date(timeIntervalSince1970: 200))+        #expect(throws: TaskLinkGraphError.self) {+            try TaskLinkPlan.validate(delta: [.remove(edgeId: row.id, occurrenceRevision: revision),+                                             .add(type: .blocks, target: target.id)], source: source.id,+                preconditions: [target.id: "current"], revisions: [target.id: "current"], savedGraph: graph)+        }+    }++    @Test(arguments: ["missing", "stale", "extra"])+    func endpointGuardsMustExactlyMatchAffectedSavedEndpoints(shape: String) throws {+        let source = task(1), target = task(2), extra = task(3)+        let graph = try project([source, target, extra], [])+        var guards: [UUID: String] = shape == "missing" ? [:] : [target.id: "stale"]+        if shape == "extra" { guards = [target.id: "current", extra.id: "extra"] }+        #expect(throws: TaskLinkGraphError.self) {+            try TaskLinkPlan.validate(delta: [.add(type: .blocks, target: target.id)], source: source.id,+                preconditions: guards, revisions: [target.id: "current", extra.id: "extra"], savedGraph: graph)+        }+    }++    @Test func exactSelfLinkRepairNeedsNoDuplicateSourceEndpointGuard() throws {+        let source = task(1), row = edge(1, source.id, source.id)+        let graph = try project([source], [row])+        let plan = try TaskLinkPlan.validate(delta: [.remove(edgeId: row.id,+                                                           occurrenceRevision: TaskLinkGraph.occurrenceRevision(row))],+            source: source.id, preconditions: [:], revisions: [:], savedGraph: graph)+        #expect(plan.removals == [row])+        #expect(plan.affectedEndpoints.isEmpty)+    }++    @Test(arguments: ["self", "unknown"])+    func exactImportedRepairEvidenceRemainsRecognizable(shape: String) throws {+        let source = task(1)+        let row = TaskLinkOccurrenceValue(physicalKey: Data([1]), id: UUID(),+            kind: shape == "unknown" ? "future-kind" : "dependency", source: source.id,+            target: shape == "self" ? source.id : UUID(), createdAt: Date(timeIntervalSince1970: 100))+        let revision = try TaskLinkGraph.occurrenceRevision(row)+        let evidence = TaskLinkRemovalValue(physicalKey: Data([9]), id: UUID(), edgeId: row.id,+            kind: row.kind, source: row.source, target: row.target, createdAt: row.createdAt,+            occurrenceRevision: revision, removedAt: Date(timeIntervalSince1970: 150))+        let graph = try TaskLinkGraph.project(tasks: [source], occurrences: [], removalEvidence: [evidence],+                                             evaluationInstant: Date(timeIntervalSince1970: 200))+        let plan = try TaskLinkPlan.validate(delta: [.remove(edgeId: row.id, occurrenceRevision: revision)],+            source: source.id, preconditions: [:], revisions: [:], savedGraph: graph)+        #expect(plan.isNoOp)+        #expect(graph.recognizedRemovals[row.id]?.count == 1)+        #expect(graph.diagnostics.isEmpty)+    }++    private func task(_ number: UInt8) -> TaskLinkTaskValue {+        TaskLinkTaskValue(physicalKey: Data([number]), id: UUID(), name: "task", status: "idea")+    }++    private func edge(_ number: UInt8, _ source: UUID, _ target: UUID) -> TaskLinkOccurrenceValue {+        TaskLinkOccurrenceValue(physicalKey: Data([number]), id: UUID(), kind: "dependency",+                                source: source, target: target, createdAt: Date(timeIntervalSince1970: 100))+    }++    private func project(_ tasks: [TaskLinkTaskValue], _ edges: [TaskLinkOccurrenceValue]) throws -> TaskLinkGraphView {+        try TaskLinkGraph.project(tasks: tasks, occurrences: edges, removalEvidence: [],+                                  evaluationInstant: Date(timeIntervalSince1970: 200))+    }+}
Transit/TransitTests/TaskLinkProtectedBoundaryTests.swift Changed +223 / -0
diff --git a/Transit/TransitTests/TaskLinkProtectedBoundaryTests.swift b/Transit/TransitTests/TaskLinkProtectedBoundaryTests.swiftnew file mode 100644index 00000000..654fad69--- /dev/null+++ b/Transit/TransitTests/TaskLinkProtectedBoundaryTests.swift@@ -0,0 +1,223 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++/// Actual imported clean policy and coordinator hooks. Staged graph rows are+/// test participants, not an implementation of the future graph write adapter.+@MainActor @Suite(.serialized)+struct TaskLinkProtectedBoundaryTests {+    @Test func dirtyBeforeAcceptanceDoesNotSaveOrReserve() async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let arguments = try fixture.updateArguments()+        fixture.source.name = "UI draft"+        var saves = 0+        let coordinator = fixture.coordinator(save: { context, _ in saves += 1; try context.save() })+        let bindings = try bindingBytes(fixture)+        let result = await coordinator.execute(tool: "update_task", arguments: arguments, batchPolicy: .init())+        #expect(try fixture.decode(result)["outcome"] as? String == "uncertain")+        #expect(saves == 0)+        #expect(try bindingBytes(fixture) == bindings)+        #expect(fixture.source.name == "UI draft")+        #expect(fixture.owner.context.hasChanges)+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "source")+        #expect(try fixture.receipts(in: observer.context).isEmpty)+    }++    @Test(arguments: [false, true])+    func dirtyAfterPreparationSuccessOrErrorRetainsAcceptedWithoutTerminalSave(throwsError: Bool) async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        var savesAfterDraft = 0+        var draftInserted = false+        let coordinator = fixture.coordinator(save: { context, _ in+            if draftInserted { savesAfterDraft += 1 }+            try context.save()+        }, preparation: { _ in+            await Task.yield()+            fixture.source.name = "during await draft"+            draftInserted = true+            if throwsError { throw TaskLinkCommitDiskFixture.Failure.injected }+        })+        let result = await coordinator.execute(tool: "update_task", arguments: try fixture.updateArguments(),+                                               batchPolicy: .init())+        let envelope = try fixture.decode(result)+        #expect(envelope["outcome"] as? String == "uncertain")+        #expect(envelope["accepted"] as? Bool == true)+        #expect(savesAfterDraft == 0)+        #expect(fixture.source.name == "during await draft")+        #expect(fixture.owner.context.hasChanges)+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "source")+        let receipt = try #require(try fixture.receipts(in: observer.context).first)+        #expect(receipt.stateRawValue == "accepted")+        #expect(receipt.resultJSON == nil)+    }++    @Test func dirtyRetainedReplayBypassesRecoveryValidationAndAllSaves() async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let arguments = try fixture.updateArguments()+        var saves = 0, recoveries = 0, validations = 0+        let coordinator = fixture.coordinator(save: { context, _ in saves += 1; try context.save() },+                                              recovery: { recoveries += 1 })+        let policy = MCPBatchWritePolicy { _, _ in validations += 1 }+        let original = await coordinator.execute(tool: "update_task", arguments: arguments, batchPolicy: policy)+        #expect(try fixture.decode(original)["outcome"] as? String == "committed")+        let beforeSaves = saves+        let bindings = try bindingBytes(fixture)+        try #require(!bindings.isEmpty)+        fixture.source.name = "unsaved replay draft"+        let replay = await coordinator.execute(tool: "update_task", arguments: arguments, batchPolicy: policy)+        #expect(replay.content.first?.text == original.content.first?.text)+        #expect(saves == beforeSaves)+        #expect(recoveries == 0)+        #expect(validations == 1)+        #expect(try bindingBytes(fixture) == bindings)+        #expect(fixture.source.name == "unsaved replay draft")+        #expect(fixture.owner.context.hasChanges)+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "committed update")+    }++    @Test func freshSavedEndpointValidationRejectsPeerChangeBeforeApply() async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let peer = try fixture.observer()+        let coordinator = fixture.coordinator(save: { context, _ in try context.save() }, preparation: { _ in+            let target = try fixture.task(fixture.target.id, in: peer.context)+            target.statusRawValue = "abandoned"+            try peer.context.save()+        })+        let policy = MCPBatchWritePolicy { _, _ in+            let fresh = try fixture.observer()+            guard try fixture.task(fixture.target.id, in: fresh.context).statusRawValue == "done" else {+                throw MCPWriteFailure("GRAPH_CONFLICT", "Test endpoint changed")+            }+        }+        let result = await coordinator.execute(tool: "update_task", arguments: try fixture.updateArguments(),+                                               batchPolicy: policy)+        #expect(try fixture.decode(result)["outcome"] as? String == "rejected")+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "source")+        #expect(try fixture.task(fixture.target.id, in: observer.context).statusRawValue == "abandoned")+        #expect(try observer.context.fetch(FetchDescriptor<TaskLinkOccurrence>()).count == 1)+        #expect(try fixture.receipts(in: observer.context).first?.stateRawValue == "rejected")+    }++    @Test(arguments: ["save", "encode", "uncertain"])+    func stagedGraphAndTerminalReceiptShareFailureOutcome(failure: String) async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let insertedID = UUID(), evidenceID = UUID()+        let coordinator = fixture.coordinator(save: { context, stage in+            if case .commit = stage, failure != "encode" { throw TaskLinkCommitDiskFixture.Failure.injected }+            try context.save()+        }, encode: { envelope in+            if envelope["outcome"] as? String == "committed", failure == "encode" {+                throw TaskLinkCommitDiskFixture.Failure.injected+            }+            return try MCPWriteOutcome.encode(envelope)+        }, recovery: {+            if failure == "uncertain" { throw TaskLinkCommitDiskFixture.Failure.injected }+        })+        let policy = MCPBatchWritePolicy(afterTaskApply: { _, _, services in+            try fixture.stageGraph(context: services.context, insertedID: insertedID, evidenceID: evidenceID)+        })+        let result = await coordinator.execute(tool: "update_task", arguments: try fixture.updateArguments(),+                                               batchPolicy: policy)+        #expect(try fixture.decode(result)["outcome"] as? String == (failure == "uncertain" ? "uncertain" : "rejected"))+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "source")+        let edges = try observer.context.fetch(FetchDescriptor<TaskLinkOccurrence>())+        #expect(edges.count == 1 && edges.first?.id == fixture.edge.id)+        #expect(edges.first?.kindRawValue == "dependency")+        #expect(edges.first?.sourceTaskID == fixture.target.id)+        #expect(edges.first?.targetTaskID == fixture.source.id)+        #expect(edges.first?.createdAt == fixture.instant)+        let evidence = try observer.context.fetch(FetchDescriptor<TaskLinkRemovalEvidence>())+        #expect(!evidence.contains { $0.id == evidenceID })+        #expect(evidence.count == 1)+        #expect(evidence.first?.kindRawValue == "future-kind")+        #expect(evidence.first?.occurrenceRevision == "raw-imported-revision")+        #expect(evidence.first?.sourceTaskID == fixture.source.id)+        #expect(evidence.first?.targetTaskID == fixture.target.id)+        #expect(evidence.first?.createdAt == fixture.instant)+        #expect(evidence.first?.removedAt == fixture.instant)+        let receipt = try #require(try fixture.receipts(in: observer.context).first)+        #expect(receipt.stateRawValue == (failure == "uncertain" ? "accepted" : "rejected"))+        let historic = try fixture.historicReceipt(in: observer.context)+        #expect(historic.resultJSON == fixture.historicJSON)+        #expect(historic.requestJSON == fixture.historicRequest)+        #expect(historic.acceptedAt == fixture.instant && historic.completedAt == fixture.instant)+        #expect(historic.resultIsError == false && historic.stateRawValue == "committed")+    }++    @Test(.enabled(if: ProcessInfo.processInfo.environment["T1734_OUTSIDE_WRITER_OBSERVATIONS"] == "1"),+          arguments: ["endpoint", "cycle"])+    // This single control retains both the outside-writer interleaving and original byte replay assertions.+    // swiftlint:disable:next function_body_length+    func outsideWriterAfterValidationRemainsSavedAndRetainedReplayIsUnchanged(race: String) async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let arguments = try fixture.updateArguments()+        let peer = try fixture.observer()+        let insertedID = UUID(), evidenceID = UUID()+        var validated = false+        let policy = MCPBatchWritePolicy(afterTaskApply: { _, _, services in+            try fixture.stageGraph(context: services.context, insertedID: insertedID, evidenceID: evidenceID)+        }, validateBeforeApply: { _, _ in+            let fresh = try fixture.observer()+            let target = try fixture.task(fixture.target.id, in: fresh.context)+            guard target.statusRawValue == "done" else { throw MCPWriteFailure("GRAPH_CONFLICT", "Endpoint changed") }+            let dependencies = try fresh.context.fetch(FetchDescriptor<TaskLinkOccurrence>())+                .filter { $0.kindRawValue == "dependency" && $0.id != fixture.edge.id }+            guard !fixture.hasCycle(dependencies) else { throw MCPWriteFailure("GRAPH_CONFLICT", "Dependency cycle") }+            validated = true+        })+        let coordinator = fixture.coordinator(save: { context, stage in+            if case .commit = stage {+                if race == "endpoint" {+                    let target = try fixture.task(fixture.target.id, in: peer.context)+                    target.statusRawValue = "abandoned"+                } else {+                    peer.context.insert(TaskLinkOccurrence(id: UUID(), kindRawValue: "dependency",+                        sourceTaskID: fixture.source.id, targetTaskID: fixture.target.id, createdAt: fixture.instant))+                    peer.context.insert(TaskLinkOccurrence(id: UUID(), kindRawValue: "dependency",+                        sourceTaskID: fixture.target.id, targetTaskID: fixture.source.id, createdAt: fixture.instant))+                }+                try peer.context.save()+            }+            try context.save()+        })+        let result = await coordinator.execute(tool: "update_task", arguments: arguments, batchPolicy: policy)+        #expect(validated)+        #expect(try fixture.decode(result)["outcome"] as? String == "committed")+        let observer = try fixture.observer()+        #expect(try fixture.task(fixture.source.id, in: observer.context).name == "committed update")+        let edges = try observer.context.fetch(FetchDescriptor<TaskLinkOccurrence>())+        #expect(edges.filter { $0.id == insertedID }.count == 1 && !edges.contains { $0.id == fixture.edge.id })+        let removals = try observer.context.fetch(FetchDescriptor<TaskLinkRemovalEvidence>())+        #expect(removals.filter { $0.id == evidenceID }.count == 1)+        if race == "endpoint" {+            // Abandoned is a valid status, not proof of a historical race fault.+            // Actual blocker assessment is tested after projection exists.+            #expect(try fixture.task(fixture.target.id, in: observer.context).statusRawValue == "abandoned")+        } else {+            #expect(fixture.hasCycle(edges.filter { $0.kindRawValue == "dependency" }))+            // Actual cycle diagnostics belong to tasks 5/6 and 21/22.+        }+        let savedReceipts = try fixture.receipts(in: observer.context)+        let receipt = try #require(savedReceipts.count == 1 ? savedReceipts.first : nil)+        #expect(receipt.stateRawValue == "committed")+        #expect(receipt.resultJSON == result.content.first?.text)+        let replay = await coordinator.execute(tool: "update_task", arguments: arguments, batchPolicy: policy)+        #expect(replay.content.first?.text == result.content.first?.text)+    }++    private func bindingBytes(_ fixture: TaskLinkCommitDiskFixture) throws -> [String: Data] {+        let root = fixture.directory.appendingPathComponent("guards/guards")+        let files = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)+        return try Dictionary(uniqueKeysWithValues: files.filter { $0.pathExtension == "json" }.map {+            ($0.lastPathComponent, try Data(contentsOf: $0))+        })+    }+}+#endif
Transit/TransitTests/TaskLinkQueryBoundaryTests.swift Changed +131 / -0
diff --git a/Transit/TransitTests/TaskLinkQueryBoundaryTests.swift b/Transit/TransitTests/TaskLinkQueryBoundaryTests.swiftnew file mode 100644index 00000000..a83cfd0e--- /dev/null+++ b/Transit/TransitTests/TaskLinkQueryBoundaryTests.swift@@ -0,0 +1,131 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct TaskLinkQueryBoundaryTests {+    @Test(arguments: ["introduced-by", "duplicate-of", "relates-to"])+    func publicTypeOrientationMatchesBothSavedEndpoints(type: String) throws {+        let base = try TaskLinkCommitDiskFixture()+        let relation = try #require(TaskLinkType(rawValue: type)).normalized(+            source: base.source.id, target: base.target.id)+        base.owner.context.insert(TaskLinkOccurrence(id: UUID(), kindRawValue: relation.kind,+            sourceTaskID: relation.source, targetTaskID: relation.target, createdAt: Date()))+        try base.owner.context.save()+        let view = try builder(base).capture(request())+        for incoming in [false, true] {+            var args = arguments()+            args["linkType"] = type+            if type != "relates-to" { args["linkDirection"] = incoming ? "incoming" : "outgoing" }+            let rows = try MCPReadProjection.tasks(view, request: MCPTaskQueryRequest.parse(args), arguments: args)+            let expected = type == "relates-to" ? Set([base.source.id.uuidString, base.target.id.uuidString])+                : Set([incoming ? base.target.id.uuidString : base.source.id.uuidString])+            #expect(Set(rows.compactMap { $0["taskId"] as? String }) == expected)+        }+    }++    @Test func graphPredicateNarrowsCanonicalBodiesBeforeCopyWithoutWideningClosure() throws {+        let base = try TaskLinkCommitDiskFixture()+        base.target.statusRawValue = "abandoned"+        try base.owner.context.save()+        var args = arguments()+        args["unblocked"] = false+        let query = try MCPTaskQueryRequest.parse(args)+        let source = builder(base)+        let service = MCPReadService(source: source, monitor: MCPImportEvidenceMonitor(syncActive: false,+            storeIdentifier: nil), snapshots: MCPTaskQuerySnapshotStore())+        let capture = service.captureRequest(tool: "query_tasks", arguments: args,+            selection: .tasks(detail: .fullRecord), includeComments: false, query: query)+        let view = try source.capture(capture)+        let candidate = try #require(view.tasks.first { $0.id == base.source.id })+        let closure = try #require(view.tasks.first { $0.id == base.target.id })+        #expect(candidate.fullRecordWithoutCommentsJSON != nil)+        #expect(closure.fullRecordWithoutCommentsJSON == nil)+        let rows = try MCPReadProjection.tasks(view, request: query, arguments: args)+        #expect(rows.count == 1 && rows[0]["taskId"] as? String == base.source.id.uuidString)+        #expect(view.taskLinkGraph?.tasks.count == 2)+    }++    @Test func graphProjectionHonorsSuppliedOriginalDeadline() throws {+        let base = try TaskLinkCommitDiskFixture()+        let view = try builder(base).capture(request())+        let args = arguments()+        #expect(throws: TaskLinkGraphError.deadlineExceeded) {+            try MCPReadProjection.tasks(view, request: MCPTaskQueryRequest.parse(args), arguments: args,+                budget: TaskLinkGraphBudget(deadline: .now - .seconds(1)))+        }+    }++    @Test func modernCursorKeepsExactFrozenGraphPayloadAfterSavedEndpointAndIncidenceEdits() async throws {+        let base = try TaskLinkCommitDiskFixture()+        let snapshots = MCPTaskQuerySnapshotStore()+        let service = MCPReadService(source: builder(base), monitor: MCPImportEvidenceMonitor(syncActive: false,+            storeIdentifier: nil), snapshots: snapshots,+            pagePreparer: { try MCPModernProviderBinding.prepareReadPages($0, tool: $1, operation: $2) })+        var args = arguments()+        args["taskIds"] = [base.source.id.uuidString, base.source.id.uuidString]+        args["limit"] = 1+        let first = try await execute(service, arguments: args)+        let firstPayload = try payload(first)+        let original = try #require((firstPayload["results"] as? [[String: Any]])?.first?["task"] as? [String: Any])+        let cursor = try #require(firstPayload["nextCursor"] as? String)+        base.target.name = "after saved import"+        base.target.statusRawValue = "abandoned"+        base.owner.context.delete(base.edge)+        try base.owner.context.save()+        let next = try await execute(service, arguments: ["cursor": cursor])+        let nextPayload = try payload(next)+        let replayed = try #require((nextPayload["results"] as? [[String: Any]])?.first?["task"] as? [String: Any])+        #expect(try bytes(original) == bytes(replayed))+        #expect((replayed["links"] as? [[String: Any]])?.first?["targetName"] as? String == "target")+        #expect((replayed["blockerAssessment"] as? [String: Any])?["assessment"] as? String == "unblocked")+    }++    private func execute(_ service: MCPReadService, arguments: [String: Any]) async throws -> [String: Any] {+        let coordinator = MCPReadCoordinator(domain: service.snapshots.domain)+        let fields = arguments.mapValues(AnyCodable.init)+        let output = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { operation in+            do {+                let read = try await service.prepare(tool: "query_tasks", arguments: fields.mapValues(\.value),+                                                     operation: operation)+                let encoded = try MCPModernProviderBinding.read(read, id: .string("link-query"),+                                                               tool: "query_tasks", operation: operation)+                return PreparedReadResult(encodedResponse: encoded, publications: read.publications,+                    publicationErrors: .init(busy: Data("busy".utf8), expired: Data("expired".utf8),+                                             capacity: Data("capacity".utf8)))+            } catch {+                Issue.record("Actual modern graph read failed: \(error)")+                return PreparedReadResult(encodedResponse: Data("failed".utf8), publications: [],+                    publicationErrors: .init(busy: Data(), expired: Data(), capacity: Data()))+            }+        }+        return try #require(JSONSerialization.jsonObject(with: output) as? [String: Any])+    }++    private func payload(_ response: [String: Any]) throws -> [String: Any] {+        let result = try #require(response["result"] as? [String: Any])+        let structured = try #require(result["structuredContent"] as? [String: Any])+        let source = try #require(structured["source"] as? [String: Any])+        let payload = try #require(source["payload"] as? [String: Any])+        let text = try #require((result["content"] as? [[String: Any]])?.first?["text"] as? String)+        #expect(try bytes(payload) == bytes(JSONSerialization.jsonObject(with: Data(text.utf8))))+        return payload+    }++    private func arguments() -> [String: Any] {+        ["detailLevel": "full", "includeComments": false, "limit": 100, "readPolicy": "cached"]+    }+    private func request() -> ReadCaptureRequest {+        ReadCaptureRequest(projectSelectors: nil, selection: .tasks(detail: .fullRecord),+                           completeness: .selectedRead, includeComments: false)+    }+    private func builder(_ base: TaskLinkCommitDiskFixture) -> MCPReadCaptureBuilder {+        MCPReadCaptureBuilder(container: base.owner.container, fence: .actorOnlyTestFixture)+    }+    private func bytes(_ value: Any) throws -> Data {+        try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys])+    }+}+#endif
Transit/TransitTests/TaskLinkQueryTests.swift Changed +147 / -0
diff --git a/Transit/TransitTests/TaskLinkQueryTests.swift b/Transit/TransitTests/TaskLinkQueryTests.swiftnew file mode 100644index 00000000..79c10a56--- /dev/null+++ b/Transit/TransitTests/TaskLinkQueryTests.swift@@ -0,0 +1,147 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct TaskLinkQueryTests {+    @Test(arguments: ["recorded", "empty", "blocked-by", "blocks"])+    func ordinaryGraphFiltersCombineWithSavedSelection(option: String) throws {+        let fixture = try Fixture()+        var args = fixture.arguments+        switch option {+        case "recorded": args["hasLinks"] = true+        case "empty": args["hasLinks"] = false+        default:+            args["linkType"] = option+            args["linkTargetTaskId"] = (option == "blocks" ? fixture.base.source.id : fixture.base.target.id).uuidString+        }+        let records = try fixture.project(args)+        let expected: Set<String> = switch option {+        case "recorded": [fixture.base.source.id.uuidString, fixture.base.target.id.uuidString]+        case "empty": [fixture.unlinked.id.uuidString]+        case "blocks": [fixture.base.target.id.uuidString]+        default: [fixture.base.source.id.uuidString]+        }+        #expect(Set(records.compactMap { $0["taskId"] as? String }) == expected)+    }++    @Test(arguments: ["done", "abandoned", "future-status"])+    func blockedOnlyExcludesUncertifiedAssessment(status: String) throws {+        let fixture = try Fixture()+        fixture.base.target.statusRawValue = status+        try fixture.base.owner.context.save()+        var args = fixture.arguments+        args["unblocked"] = false+        let blocked = try fixture.project(args)+        #expect(blocked.compactMap { $0["taskId"] as? String }+            == (status == "abandoned" ? [fixture.base.source.id.uuidString] : []))+        args["unblocked"] = true+        let unblocked = try fixture.project(args)+        #expect(unblocked.contains { $0["taskId"] as? String == fixture.base.source.id.uuidString }+            == (status == "done"))+    }++    @Test func fullDetailUsesFrozenLabelsIncidenceAndAssessmentAfterSavedEdits() throws {+        let fixture = try Fixture()+        let view = try fixture.capture()+        let before = try fixture.project(fixture.arguments, view: view)+        let source = try #require(before.first { $0["taskId"] as? String == fixture.base.source.id.uuidString })+        let links = try #require(source["links"] as? [[String: Any]])+        #expect(links.count == 1 && links[0]["type"] as? String == "blocked-by")+        #expect(links[0]["targetName"] as? String == "target")+        #expect((source["blockerAssessment"] as? [String: Any])?["assessment"] as? String == "unblocked")+        fixture.base.target.name = "later saved label"+        fixture.base.target.statusRawValue = "abandoned"+        try fixture.base.owner.context.save()+        #expect(try bytes(fixture.project(fixture.arguments, view: view)) == bytes(before))+        let fresh = try fixture.project(fixture.arguments)+        let updated = try #require(fresh.first { $0["taskId"] as? String == fixture.base.source.id.uuidString })+        #expect((updated["blockerAssessment"] as? [String: Any])?["assessment"] as? String == "blocked")+        #expect(updated["revision"] as? String == source["revision"] as? String)+    }++    @Test func missingGraphCaptureExplicitlyReportsUnavailableObservation() throws {+        let fixture = try Fixture()+        let view = try fixture.capture()+        let legacy = CapturedReadView(completeness: view.completeness, captureScope: view.captureScope,+            metadata: view.metadata, createdAt: view.createdAt, retentionDeadline: view.retentionDeadline,+            projects: view.projects, tasks: view.tasks, milestones: view.milestones, comments: view.comments)+        let records = try fixture.project(fixture.arguments, view: legacy)+        #expect(records.allSatisfy { $0["graphCoverage"] as? String == "unavailable" })+        #expect(records.allSatisfy { $0["links"] is NSNull })+    }++    @Test func incomingDuplicateVisibilityDoesNotRedirectOrdinaryTaskIdentity() throws {+        let fixture = try Fixture()+        fixture.base.owner.context.insert(TaskLinkOccurrence(id: UUID(), kindRawValue: "duplicate",+            sourceTaskID: fixture.base.source.id, targetTaskID: fixture.base.target.id, createdAt: Date()))+        try fixture.base.owner.context.save()+        let records = try fixture.project(fixture.arguments)+        let source = try #require(records.first { $0["taskId"] as? String == fixture.base.source.id.uuidString })+        let target = try #require(records.first { $0["taskId"] as? String == fixture.base.target.id.uuidString })+        #expect((source["duplicateResolution"] as? [String: Any])?["canonicalTaskId"] as? String+            == fixture.base.target.id.uuidString)+        let incoming = try #require(target["links"] as? [[String: Any]])+        #expect(incoming.contains {+            $0["type"] as? String == "duplicate-of" && $0["direction"] as? String == "incoming"+        })+    }++    @Test func defaultHandlerCannotReturnUnsavedSourceOrCommentDrafts() async throws {+        let env = try MCPTestHelpers.makeEnv()+        let project = MCPTestHelpers.makeProject(in: env.context)+        let task = try await env.taskService.createTask(+            name: "saved", description: nil, type: .feature, project: project)+        let comment = try env.commentService.addComment(+            to: task, content: "saved comment", authorName: "A", isAgent: true)+        task.name = "draft"+        comment.content = "draft comment"+        let response = await env.handler.handle(MCPTestHelpers.toolCallRequest(tool: "query_tasks", arguments: [+            "detailLevel": "full", "includeComments": true, "limit": 100]))+        let records = try MCPTestHelpers.decodeQueryResults(response)+        #expect(records[0]["name"] as? String == "saved")+        #expect((records[0]["comments"] as? [[String: Any]])?.first?["content"] as? String == "saved comment")+        #expect(env.context.hasChanges && task.name == "draft" && comment.content == "draft comment")+    }++    @Test(arguments: ["hasLinks", "unblocked", "linkType", "linkTargetTaskId", "linkDirection"])+    func malformedOptionsAndReusableGraphOptionsAreRejected(key: String) throws {+        let fixture = try Fixture()+        var args = fixture.arguments+        args[key] = 42+        #expect(throws: MCPTaskQueryError.self) { try MCPTaskQueryRequest.parse(args) }+        args[key] = key == "hasLinks" || key == "unblocked" ? true : "duplicate-of"+        args["snapshotId"] = UUID().uuidString+        #expect(throws: MCPSnapshotTaskQueryError.self) { try MCPSnapshotTaskQueryRequest.parse(args) }+    }++    private func bytes(_ value: Any) throws -> Data {+        try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys])+    }++    @MainActor private struct Fixture {+        let base: TaskLinkCommitDiskFixture+        let unlinked: TransitTask+        let arguments: [String: Any] = ["detailLevel": "full", "includeComments": false, "limit": 100]+        init() throws {+            base = try TaskLinkCommitDiskFixture()+            let project = try #require(base.source.project)+            unlinked = TransitTask(name: "unlinked", type: .feature, project: project,+                                   displayID: .permanent(3))+            base.owner.context.insert(unlinked)+            try base.owner.context.save()+        }+        func capture() throws -> CapturedReadView {+            try MCPReadCaptureBuilder(container: base.owner.container, fence: .actorOnlyTestFixture).capture(+                ReadCaptureRequest(projectSelectors: nil, selection: .tasks(detail: .fullRecord),+                                   completeness: .selectedRead, includeComments: false))+        }+        func project(_ args: [String: Any], view: CapturedReadView? = nil) throws -> [[String: Any]] {+            let request = try MCPTaskQueryRequest.parse(args)+            return try MCPReadProjection.tasks(view ?? capture(), request: request, arguments: args)+        }+    }+}+#endif
Transit/TransitTests/TaskLinkReadCaptureBoundaryTests.swift Changed +177 / -0
diff --git a/Transit/TransitTests/TaskLinkReadCaptureBoundaryTests.swift b/Transit/TransitTests/TaskLinkReadCaptureBoundaryTests.swiftnew file mode 100644index 00000000..580bbd0a--- /dev/null+++ b/Transit/TransitTests/TaskLinkReadCaptureBoundaryTests.swift@@ -0,0 +1,177 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct TaskLinkReadCaptureBoundaryTests {+    @Test func linkOnlySavedChangeInvalidatesPersistentHistoryFence() throws {+        let owner = try diskOwner()+        let project = Project(name: "history", description: "", gitRepo: nil, colorHex: "blue")+        let source = TransitTask(name: "source", type: .feature, project: project, displayID: .permanent(1))+        owner.context.insert(project)+        owner.context.insert(source)+        try owner.context.save()+        let peer = ModelContext(owner.container)+        peer.autosaveEnabled = false+        let builder = MCPReadCaptureBuilder(container: owner.container, afterProjects: {+            peer.insert(TaskLinkOccurrence(id: UUID(), kindRawValue: "dependency", sourceTaskID: UUID(),+                                           targetTaskID: source.id, createdAt: Date()))+            try peer.save()+        })+        #expect(throws: MCPReadCaptureError.incoherentCapture) { try builder.capture(request()) }+        #expect(try owner.context.fetchCount(FetchDescriptor<TaskLinkOccurrence>()) == 1)+    }++    @Test func retentionClockStartsBeforeCopyResumes() throws {+        let owner = try TestModelContainer()+        var resumedAt: ContinuousClock.Instant?+        let builder = MCPReadCaptureBuilder(container: owner.container, fence: .actorOnlyTestFixture,+            afterProjects: { resumedAt = ContinuousClock.now })+        let view = try builder.capture(request())+        let resumed = try #require(resumedAt)+        #expect(view.createdAt <= resumed)+        #expect(view.createdAt.duration(to: view.retentionDeadline) == .seconds(300))+        let graph = try #require(view.taskLinkGraph)+        #expect(MCPRecordSnapshot.timestamp(graph.evaluationInstant) == view.metadata.asOf)+    }++    @Test func capturedEndpointMultiplicityRemainsInvalid() throws {+        let owner = try TestModelContainer()+        let project = Project(name: "collision", description: "", gitRepo: nil, colorHex: "blue")+        let first = TransitTask(name: "one", type: .feature, project: project, displayID: .permanent(1))+        let second = TransitTask(name: "two", type: .feature, project: project, displayID: .permanent(2))+        second.id = first.id+        owner.context.insert(project)+        owner.context.insert(first)+        owner.context.insert(second)+        try owner.context.save()+        let builder = MCPReadCaptureBuilder(container: owner.container, fence: .actorOnlyTestFixture)+        let view = try builder.capture(request())+        let graph = try #require(view.taskLinkGraph)+        #expect(graph.tasksById[first.id]?.count == 2)+        #expect(graph.assessment(for: first.id) == .invalid)+        #expect(view.tasks.count == 2)+    }++    @Test func oneFrozenExpiryInstantIsSharedByEveryAssessment() throws {+        let owner = try TestModelContainer()+        let project = Project(name: "expiry", description: "", gitRepo: nil, colorHex: "blue")+        let source = TransitTask(name: "source", type: .feature, project: project, displayID: .permanent(1))+        let target = TransitTask(name: "target", type: .feature, project: project, displayID: .permanent(2))+        source.status = .done+        let instant = Date()+        let edge = TaskLinkOccurrence(id: UUID(), kindRawValue: "dependency", sourceTaskID: source.id,+                                      targetTaskID: target.id, createdAt: instant.addingTimeInterval(-10))+        let value = TaskLinkOccurrenceValue(physicalKey: Data([1]), id: edge.id, kind: edge.kindRawValue,+            source: edge.sourceTaskID, target: edge.targetTaskID, createdAt: edge.createdAt)+        let evidence = TaskLinkRemovalEvidence(id: UUID(), edgeId: edge.id, kindRawValue: edge.kindRawValue,+            sourceTaskID: edge.sourceTaskID, targetTaskID: edge.targetTaskID, createdAt: edge.createdAt,+            occurrenceRevision: try TaskLinkGraph.occurrenceRevision(value), removedAt: instant)+        for task in [source, target] { owner.context.insert(task) }+        owner.context.insert(project)+        owner.context.insert(edge)+        owner.context.insert(evidence)+        try owner.context.save()+        let builder = MCPReadCaptureBuilder(container: owner.container, fence: .actorOnlyTestFixture)+        let view = try builder.capture(request())+        let graph = try #require(view.taskLinkGraph)+        #expect(graph.assessment(for: target.id) == .invalid)+        #expect(view.metadata.asOf == MCPRecordSnapshot.timestamp(graph.evaluationInstant))+        let later = try TaskLinkGraph.project(tasks: graph.tasks, occurrences: graph.occurrences,+            removalEvidence: graph.removalEvidence,+            evaluationInstant: instant.addingTimeInterval(TaskLinkGraph.evidenceLifetime + 1))+        #expect(later.assessment(for: target.id) == .unblocked)+        #expect(graph.assessment(for: target.id) == .invalid)+    }++    @Test func retainedGraphIndicesAndDiagnosticsAreChargedAlongsideCapture() async throws {+        let owner = try TestModelContainer()+        let project = Project(name: "charge", description: "", gitRepo: nil, colorHex: "blue")+        let source = TransitTask(name: "source", type: .feature, project: project, displayID: .permanent(1))+        let collision = TransitTask(name: "collision", type: .feature, project: project, displayID: .permanent(2))+        collision.id = source.id+        let row = TaskLinkOccurrence(id: UUID(), kindRawValue: "future-kind", sourceTaskID: source.id,+                                     targetTaskID: UUID(), createdAt: Date())+        let copy = TaskLinkOccurrence(id: row.id, kindRawValue: row.kindRawValue, sourceTaskID: row.sourceTaskID,+                                      targetTaskID: row.targetTaskID, createdAt: row.createdAt)+        owner.context.insert(project)+        owner.context.insert(source)+        owner.context.insert(collision)+        owner.context.insert(row)+        owner.context.insert(copy)+        try owner.context.save()+        let builder = MCPReadCaptureBuilder(container: owner.container, fence: .actorOnlyTestFixture)+        let view = try builder.capture(request())+        let graph = try #require(view.taskLinkGraph)+        #expect(graph.tasksById[source.id]?.count == 2)+        #expect(graph.occurrencesById[row.id]?.count == 2)+        #expect(graph.incidence[source.id]?.count == 2)+        #expect(graph.invalidOccurrences.count == 2)+        #expect(!graph.diagnostics.isEmpty)+        let without = CapturedReadView(completeness: view.completeness, captureScope: view.captureScope,+            metadata: view.metadata, createdAt: view.createdAt, retentionDeadline: view.retentionDeadline,+            projects: view.projects, tasks: view.tasks, milestones: view.milestones, comments: view.comments)+        let metadata = try JSONEncoder().encode(view.metadata)+        let capsule = MCPPreparedReadCapture(view: view, frozenMetadataBytes: metadata)+        let legacy = MCPPreparedReadCapture(view: without, frozenMetadataBytes: metadata)+        let coordinator = MCPReadCoordinator()+        let bytes = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { operation in+            let response: Data+            do {+                let delta = try MCPPortfolioCaptureCharge.bytes(capsule, operation: operation)+                    - MCPPortfolioCaptureCharge.bytes(legacy, operation: operation)+                response = Data(String(delta).utf8)+            } catch { response = Data(String(describing: error).utf8) }+            return PreparedReadResult(encodedResponse: response, publications: [],+                publicationErrors: PreencodedPublicationErrors(busy: Data(), expired: Data(), capacity: Data()))+        }+        #expect(bytes == Data(String(graph.retainedBytes).utf8))+        #expect(graph.retainedBytes > 0)+        for _ in 0..<100 where coordinator.unfinishedCount != 0 {+            try await Task.sleep(for: .milliseconds(5))+        }+        #expect(coordinator.unfinishedCount == 0)+    }++    @Test(arguments: [8, 64])+    func inputScalarsFitButRetainedIndexCapacityFailsWholeGraph(count: Int) throws {+        let tasks = (0..<count).map { index in+            TaskLinkTaskValue(physicalKey: Data(repeating: UInt8(index), count: 128), id: UUID(),+                              name: String(repeating: "s", count: 200), status: "done")+        }+        let edges = (0..<(count - 1)).map { index in+            TaskLinkOccurrenceValue(physicalKey: Data(repeating: UInt8(index), count: 128), id: UUID(),+                kind: "dependency", source: tasks[index].id, target: tasks[index + 1].id, createdAt: Date())+        }+        let instant = Date()+        let input = try TaskLinkGraphIndex(tasks: tasks, occurrences: edges, evidence: [], instant: instant,+                                          budget: TaskLinkGraphBudget())+        let cap = input.retainedBytes * 2+        let complete = try TaskLinkGraph.project(tasks: tasks, occurrences: edges, removalEvidence: [],+                                                evaluationInstant: instant)+        #expect(input.retainedBytes < cap)+        #expect(complete.retainedBytes > cap)+        #expect(throws: TaskLinkGraphError.capacityExceeded) {+            try TaskLinkGraph.project(tasks: tasks, occurrences: edges, removalEvidence: [],+                                      evaluationInstant: instant, budget: TaskLinkGraphBudget(maximumBytes: cap))+        }+    }++    private func request() -> ReadCaptureRequest {+        ReadCaptureRequest(projectSelectors: nil, selection: .portfolio, completeness: .completePortfolio,+                           includeComments: false)+    }++    private func diskOwner() throws -> TestModelContainer {+        let baseline = try TestModelContainer()+        let root = FileManager.default.temporaryDirectory.appendingPathComponent("T1734GraphFence-\(UUID().uuidString)")+        try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false,+                                               attributes: [.posixPermissions: 0o700])+        let config = ModelConfiguration("T1734GraphFence", schema: baseline.container.schema,+                                        url: root.appendingPathComponent("graph.store"), cloudKitDatabase: .none)+        return try TestModelContainer(schema: baseline.container.schema, configurations: [config])+    }+}+#endif
Transit/TransitTests/TaskLinkReadCaptureTests.swift Changed +130 / -0
diff --git a/Transit/TransitTests/TaskLinkReadCaptureTests.swift b/Transit/TransitTests/TaskLinkReadCaptureTests.swiftnew file mode 100644index 00000000..1d6cf015--- /dev/null+++ b/Transit/TransitTests/TaskLinkReadCaptureTests.swift@@ -0,0 +1,130 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct TaskLinkReadCaptureTests {+    @Test func captureKeepsSavedGraphWhileAllDraftKindsRemainUnsaved() throws {+        let fixture = try TaskLinkReadFixture()+        let context = fixture.owner.context+        fixture.source.name = "draft source"+        fixture.target.name = "draft target"+        fixture.target.status = .abandoned+        fixture.comment.content = "draft comment"+        context.delete(fixture.edge)+        context.insert(TaskLinkOccurrence(id: UUID(), kindRawValue: "duplicate", sourceTaskID: fixture.source.id,+                                         targetTaskID: fixture.target.id, createdAt: Date()))+        context.insert(TaskLinkRemovalEvidence(id: UUID(), edgeId: fixture.edge.id,+            kindRawValue: fixture.edge.kindRawValue, sourceTaskID: fixture.edge.sourceTaskID,+            targetTaskID: fixture.edge.targetTaskID, createdAt: fixture.edge.createdAt,+            occurrenceRevision: "draft evidence", removedAt: Date()))+        let view = try fixture.builder().capture(fixture.request())+        let graph = try #require(view.taskLinkGraph)+        #expect(graph.tasksById[fixture.source.id]?.first?.name == "source")+        #expect(graph.tasksById[fixture.target.id]?.first?.name == "target")+        #expect(graph.tasksById[fixture.target.id]?.first?.status == "done")+        #expect(graph.occurrences.map(\.id) == [fixture.edge.id])+        #expect(graph.removalEvidence.isEmpty)+        #expect(graph.assessment(for: fixture.source.id) == .unblocked)+        #expect(view.comments.first?.content == "saved comment")+        #expect(context.hasChanges)+    }++    @Test func foreignGraphClosureDoesNotExpandSelectedMembership() throws {+        let fixture = try TaskLinkReadFixture()+        let second = TaskLinkOccurrence(id: UUID(), kindRawValue: "dependency", sourceTaskID: fixture.source.id,+                                        targetTaskID: fixture.target.id, createdAt: Date())+        fixture.owner.context.insert(second)+        try fixture.owner.context.save()+        let view = try fixture.builder().capture(fixture.request())+        let graph = try #require(view.taskLinkGraph)+        #expect(view.tasks.map(\.id) == [fixture.source.id])+        #expect(Set(graph.tasks.map(\.id)) == Set([fixture.source.id, fixture.target.id]))+        #expect(graph.cyclicTasks == Set([fixture.source.id, fixture.target.id]))+        #expect(graph.assessment(for: fixture.source.id) == .invalid)+    }++    @Test func importedPhysicalMultiplicityIsNotCollapsedInCapture() throws {+        let fixture = try TaskLinkReadFixture()+        let copy = TaskLinkOccurrence(id: fixture.edge.id, kindRawValue: fixture.edge.kindRawValue,+                                     sourceTaskID: fixture.edge.sourceTaskID, targetTaskID: fixture.edge.targetTaskID,+                                     createdAt: fixture.edge.createdAt)+        fixture.owner.context.insert(copy)+        try fixture.owner.context.save()+        let view = try fixture.builder().capture(fixture.request())+        let graph = try #require(view.taskLinkGraph)+        #expect(graph.occurrencesById[fixture.edge.id]?.count == 2)+        #expect(Set(graph.occurrences.map(\.physicalKey)).count == 2)+        #expect(graph.assessment(for: fixture.source.id) == .invalid)+    }++    @Test(arguments: ["deadline", "capacity"])+    func originalGraphBudgetFailsEntireReadInsteadOfReturningEmpty(shape: String) throws {+        let fixture = try TaskLinkReadFixture()+        let budget = shape == "deadline"+            ? TaskLinkGraphBudget(deadline: .now.advanced(by: .seconds(-1)))+            : TaskLinkGraphBudget(maximumBytes: 1)+        #expect(throws: TaskLinkGraphError.self) {+            try fixture.builder().capture(fixture.request(budget: budget))+        }+    }++    @Test func laterSavedGraphChangesCannotEnrichFrozenCapture() throws {+        let fixture = try TaskLinkReadFixture()+        let view = try fixture.builder().capture(fixture.request())+        let original = try #require(view.taskLinkGraph)+        let peer = ModelContext(fixture.owner.container)+        peer.autosaveEnabled = false+        let id = fixture.target.id+        let matches = try peer.fetch(FetchDescriptor<TransitTask>(predicate: #Predicate { $0.id == id }))+        let target = try #require(matches.first)+        target.status = .abandoned+        try peer.save()+        #expect(original.assessment(for: fixture.source.id) == .unblocked)+        let fresh = try #require(try fixture.builder().capture(fixture.request()).taskLinkGraph)+        #expect(fresh.assessment(for: fixture.source.id) == .blocked)+        #expect(original.tasksById[id]?.first?.status == "done")+    }+}++@MainActor+private struct TaskLinkReadFixture {+    let owner: TestModelContainer+    let selected: Project+    let source: TransitTask+    let target: TransitTask+    let edge: TaskLinkOccurrence+    let comment: Transit.Comment++    init() throws {+        owner = try TestModelContainer()+        owner.context.autosaveEnabled = false+        selected = Project(name: "selected", description: "", gitRepo: nil, colorHex: "blue")+        let foreign = Project(name: "foreign", description: "", gitRepo: nil, colorHex: "green")+        source = TransitTask(name: "source", type: .feature, project: selected, displayID: .permanent(1))+        target = TransitTask(name: "target", type: .feature, project: foreign, displayID: .permanent(2))+        target.status = .done+        edge = TaskLinkOccurrence(id: UUID(), kindRawValue: "dependency", sourceTaskID: target.id,+                                  targetTaskID: source.id, createdAt: Date())+        comment = Transit.Comment(content: "saved comment", authorName: "fixture", isAgent: true, task: source)+        owner.context.insert(selected)+        owner.context.insert(foreign)+        owner.context.insert(source)+        owner.context.insert(target)+        owner.context.insert(edge)+        owner.context.insert(comment)+        try owner.context.save()+    }++    func builder() -> MCPReadCaptureBuilder {+        MCPReadCaptureBuilder(container: owner.container, fence: .actorOnlyTestFixture)+    }++    func request(budget: TaskLinkGraphBudget? = nil) -> ReadCaptureRequest {+        ReadCaptureRequest(projectSelectors: [.id(selected.id)], selection: .tasks(detail: .fullRecord),+                           completeness: .selectedRead, includeComments: true, taskLinkBudget: budget)+    }+}+#endif
Transit/TransitTests/TaskLinkRemovalEvidenceTests.swift Changed +103 / -0
diff --git a/Transit/TransitTests/TaskLinkRemovalEvidenceTests.swift b/Transit/TransitTests/TaskLinkRemovalEvidenceTests.swiftnew file mode 100644index 00000000..0ea4031b--- /dev/null+++ b/Transit/TransitTests/TaskLinkRemovalEvidenceTests.swift@@ -0,0 +1,103 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct TaskLinkRemovalEvidenceTests {+    @Test func cleanupDeletesOnlyEligibleEvidenceAndNeverSavesUIDraftsOrActiveRows() throws {+        let base = try TaskLinkCommitDiskFixture()+        let instant = Date()+        let evidence = try row(base, removedAt: instant - TaskLinkGraph.evidenceLifetime - 1)+        base.owner.context.insert(evidence)+        try base.owner.context.save()+        let before = try MCPRecordSnapshot.task(base.source, in: base.owner.context).revision+        base.source.name = "UI draft"+        let removed = try TaskLinkService(container: base.owner.container).cleanupExpiredEvidence(+            evaluationInstant: instant)+        #expect(removed == 1)+        #expect(base.source.name == "UI draft" && base.owner.context.hasChanges)+        let observer = try base.observer()+        #expect(try observer.context.fetchCount(FetchDescriptor<TaskLinkOccurrence>()) == 1)+        #expect(try observer.context.fetchCount(FetchDescriptor<TaskLinkRemovalEvidence>()) == 1)+        let saved = try base.task(base.source.id, in: observer.context)+        let savedRevision = try MCPRecordSnapshot.task(saved, in: observer.context).revision+        #expect(saved.name == "source" && savedRevision == before)+        #expect(try base.historicReceipt(in: observer.context).resultJSON == base.historicJSON)+    }++    @Test(arguments: ["future", "malformed", "ambiguous"])+    func cleanupDefersUnsafeEvidenceIdentityAndDates(fault: String) throws {+        let base = try TaskLinkCommitDiskFixture()+        let now = Date()+        let removedAt = fault == "future" ? now + 1 : now - TaskLinkGraph.evidenceLifetime - 1+        let candidate = try row(base, removedAt: removedAt, revision: fault == "malformed" ? "corrupt" : nil)+        base.owner.context.insert(candidate)+        if fault == "ambiguous" {+            base.owner.context.insert(try row(base, removedAt: now, id: candidate.id))+        }+        try base.owner.context.save()+        #expect(try TaskLinkService(container: base.owner.container).cleanupExpiredEvidence(+            evaluationInstant: now) == 0)+        let observer = try base.observer()+        #expect(try observer.context.fetchCount(FetchDescriptor<TaskLinkRemovalEvidence>())+            == (fault == "ambiguous" ? 3 : 2))+    }++    @Test func cleanupIsBoundedAndExpiredBudgetCannotDeleteAnything() throws {+        let base = try TaskLinkCommitDiskFixture()+        let now = Date()+        for _ in 0..<3 {+            base.owner.context.insert(try row(base, removedAt: now - TaskLinkGraph.evidenceLifetime - 1))+        }+        try base.owner.context.save()+        let service = TaskLinkService(container: base.owner.container)+        #expect(throws: TaskLinkGraphError.deadlineExceeded) {+            try service.cleanupExpiredEvidence(evaluationInstant: now,+                budget: TaskLinkGraphBudget(deadline: .now - .seconds(1)))+        }+        #expect(try base.observer().context.fetchCount(FetchDescriptor<TaskLinkRemovalEvidence>()) == 4)+        #expect(try service.cleanupExpiredEvidence(evaluationInstant: now, limit: 2) == 2)+        #expect(try base.observer().context.fetchCount(FetchDescriptor<TaskLinkRemovalEvidence>()) == 2)+    }++    @Test(arguments: [false, true])+    func bothArrivalOrdersPreserveConflictAndFrozenExpiryWithoutChangingContentToken(evidenceFirst: Bool) throws {+        let base = try TaskLinkCommitDiskFixture()+        let now = Date()+        let edgeID = base.edge.id+        let source = base.edge.sourceTaskID+        let target = base.edge.targetTaskID+        base.owner.context.delete(base.edge)+        try base.owner.context.save()+        let evidence = try row(base, removedAt: now, edgeID: edgeID, source: source, target: target)+        let active = TaskLinkOccurrence(id: edgeID, kindRawValue: "dependency", sourceTaskID: source,+                                        targetTaskID: target, createdAt: base.instant)+        if evidenceFirst { base.owner.context.insert(evidence) } else { base.owner.context.insert(active) }+        try base.owner.context.save()+        if evidenceFirst { base.owner.context.insert(active) } else { base.owner.context.insert(evidence) }+        try base.owner.context.save()+        let frozen = try TaskLinkService.graph(in: base.owner.context, evaluationInstant: now)+        let revision = try MCPRecordSnapshot.task(base.source, in: base.owner.context).revision+        #expect(frozen.diagnostics.contains { $0.code == "active_removal_conflict" && $0.edgeId == edgeID })+        #expect(frozen.assessment(for: target) == .invalid)+        let later = try TaskLinkService.graph(in: base.owner.context,+            evaluationInstant: now + TaskLinkGraph.evidenceLifetime + 1)+        #expect(later.assessment(for: target) == .unblocked)+        #expect(frozen.assessment(for: target) == .invalid)+        #expect(try MCPRecordSnapshot.task(base.source, in: base.owner.context).revision == revision)+        #expect(try base.owner.context.fetchCount(FetchDescriptor<TaskLinkOccurrence>()) == 1)+    }++    private func row(_ base: TaskLinkCommitDiskFixture, removedAt: Date, id: UUID = UUID(),+                     revision: String? = nil, edgeID: UUID? = nil, source: UUID? = nil,+                     target: UUID? = nil) throws -> TaskLinkRemovalEvidence {+        let value = TaskLinkOccurrenceValue(physicalKey: Data(), id: edgeID ?? UUID(), kind: "dependency",+            source: source ?? base.source.id, target: target ?? base.target.id, createdAt: base.instant)+        return try TaskLinkRemovalEvidence(id: id, edgeId: value.id, kindRawValue: value.kind,+            sourceTaskID: value.source, targetTaskID: value.target, createdAt: value.createdAt,+            occurrenceRevision: revision ?? TaskLinkGraph.occurrenceRevision(value), removedAt: removedAt)+    }+}+#endif
Transit/TransitTests/TaskLinkRevisionTests.swift Changed +164 / -0
diff --git a/Transit/TransitTests/TaskLinkRevisionTests.swift b/Transit/TransitTests/TaskLinkRevisionTests.swiftnew file mode 100644index 00000000..455f8ae0--- /dev/null+++ b/Transit/TransitTests/TaskLinkRevisionTests.swift@@ -0,0 +1,164 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct TaskLinkRevisionTests {+    @Test func emptyIncidenceTransitionsEveryCurrentTaskToken() throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let context = fixture.owner.context+        context.delete(fixture.edge)+        try context.save()+        let current = try MCPRecordSnapshot.task(fixture.source, in: context)+        let oldFields = current.coveredFields.filter { $0.key != "linkContract" && $0.key != "incidentLinks" }+        let oldToken = try MCPRecordRevision.token(entity: "task", fields: oldFields)+        #expect(current.revision != oldToken)+        #expect(current.coveredFields["linkContract"] as? String == "task-links-v1")+        #expect((current.coveredFields["incidentLinks"] as? [[String: Any]])?.isEmpty == true)+        #expect(current.record["revisionCoverage"] as? String == "task-fields-comments-links-v1")+        #expect(current.record["graphCoverage"] as? String == "available")+    }++    @Test(arguments: ["update_task", "update_task_status"])+    func preFeatureTokenIsRejectedWithoutChangingNoLinkTask(tool: String) async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        fixture.owner.context.delete(fixture.edge)+        try fixture.owner.context.save()+        let snapshot = try MCPRecordSnapshot.task(fixture.source, in: fixture.owner.context)+        let legacy = try MCPRecordRevision.token(entity: "task", fields: snapshot.coveredFields.filter {+            $0.key != "linkContract" && $0.key != "incidentLinks"+        })+        var arguments: [String: Any] = ["taskId": fixture.source.id.uuidString,+                                      "expectedRevision": legacy, "idempotencyKey": "legacy-" + tool]+        if tool == "update_task" { arguments["name"] = "must not save" } else { arguments["status"] = "abandoned" }+        let coordinator = fixture.coordinator(save: { context, _ in try context.save() })+        let result = try fixture.decode(await coordinator.execute(tool: tool, arguments: arguments))+        #expect(result["outcome"] as? String == "rejected")+        let error = try #require(result["error"] as? [String: Any])+        #expect(error["code"] as? String == "REVISION_CONFLICT")+        let current = try #require(result["currentRecord"] as? [String: Any])+        #expect(current["revisionCoverage"] as? String == "task-fields-comments-links-v1")+        let observer = try fixture.observer()+        let saved = try fixture.task(fixture.source.id, in: observer.context)+        #expect(saved.name == "source" && saved.statusRawValue == fixture.source.statusRawValue)+    }++    @Test func legacyCommentOnlyOverloadReportsMissingGraphCoverage() throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let snapshot = try MCPRecordSnapshot.task(fixture.source, incidence: nil) { _ in [] }+        #expect(snapshot.record["graphCoverage"] as? String == "unavailable")+        #expect(snapshot.record["revisionCoverage"] as? String == "task-fields-comments-v1")+    }++    @Test(arguments: ["incoming", "outgoing"])+    func incidenceAloneChangesBothEndpointTokens(direction: String) throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let context = fixture.owner.context+        let source = try MCPRecordSnapshot.task(fixture.source, in: context).revision+        let target = try MCPRecordSnapshot.task(fixture.target, in: context).revision+        let row = TaskLinkOccurrence(id: UUID(), kindRawValue: "attribution",+            sourceTaskID: direction == "outgoing" ? fixture.source.id : fixture.target.id,+            targetTaskID: direction == "outgoing" ? fixture.target.id : fixture.source.id, createdAt: fixture.instant)+        context.insert(row)+        try context.save()+        #expect(try MCPRecordSnapshot.task(fixture.source, in: context).revision != source)+        #expect(try MCPRecordSnapshot.task(fixture.target, in: context).revision != target)+    }++    @Test func physicalMultiplicityAndMalformedRawTupleCannotDisappearFromToken() throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let context = fixture.owner.context+        let baseline = try MCPRecordSnapshot.task(fixture.source, in: context).revision+        let copy = TaskLinkOccurrence(id: fixture.edge.id, kindRawValue: fixture.edge.kindRawValue,+            sourceTaskID: fixture.edge.sourceTaskID, targetTaskID: fixture.edge.targetTaskID,+            createdAt: fixture.edge.createdAt)+        context.insert(copy)+        try context.save()+        #expect(try MCPRecordSnapshot.task(fixture.source, in: context).revision != baseline)+        context.delete(copy)+        try context.save()+        #expect(try MCPRecordSnapshot.task(fixture.source, in: context).revision == baseline)+        let rawId = fixture.edge.id+        context.delete(fixture.edge)+        context.insert(TaskLinkOccurrence(id: rawId, kindRawValue: "future-kind", sourceTaskID: fixture.source.id,+                                         targetTaskID: fixture.target.id, createdAt: fixture.instant))+        try context.save()+        #expect(try MCPRecordSnapshot.task(fixture.source, in: context).revision != baseline)+    }++    @Test func endpointLabelsAndRemovalExpiryDoNotChangeActiveContentToken() throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let context = fixture.owner.context+        let token = try MCPRecordSnapshot.task(fixture.source, in: context).revision+        fixture.target.name = "new saved label"+        fixture.target.status = .abandoned+        context.insert(TaskLinkRemovalEvidence(id: UUID(), edgeId: fixture.edge.id,+            kindRawValue: fixture.edge.kindRawValue, sourceTaskID: fixture.edge.sourceTaskID,+            targetTaskID: fixture.edge.targetTaskID, createdAt: fixture.edge.createdAt,+            occurrenceRevision: "raw preserved invalid evidence", removedAt: fixture.instant))+        try context.save()+        #expect(try MCPRecordSnapshot.task(fixture.source, in: context).revision == token)+    }++    @Test func fullCapturedTokenStillCoversLinksWhenBodiesAreOmitted() throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let view = try MCPReadCaptureBuilder(container: fixture.owner.container, fence: .actorOnlyTestFixture).capture(+            ReadCaptureRequest(projectSelectors: nil, selection: .portfolio, completeness: .completePortfolio,+                               includeComments: false))+        let task = try #require(view.tasks.first { $0.id == fixture.source.id })+        let bytes = try #require(task.fullRecordWithoutCommentsJSON)+        let record = try #require(try JSONSerialization.jsonObject(with: bytes) as? [String: Any])+        #expect(record["revisionCoverage"] as? String == "task-fields-comments-links-v1")+        #expect(record["graphCoverage"] as? String == "available")+        #expect(record["comments"] == nil)+        #expect(task.revision == (try MCPRecordSnapshot.task(fixture.source, in: fixture.owner.context).revision))+    }++    @Test func directIncidencePermutationPreservesRepeatedRawTuples() throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let rows = try TaskLinkIncidence.capture(fixture.source.id, in: fixture.owner.context)+        let row = try #require(rows.first)+        let other = TaskLinkOccurrenceValue(physicalKey: Data(), id: UUID(), kind: "future-kind",+                                           source: row.target, target: row.source, createdAt: fixture.instant)+        let left = try MCPRecordSnapshot.task(fixture.source, incidence: [row, other, row]) { _ in [] }+        let right = try MCPRecordSnapshot.task(fixture.source, incidence: [row, row, other]) { _ in [] }+        #expect(left.revision == right.revision)+        let fewer = try MCPRecordSnapshot.task(fixture.source, incidence: [row, other]) { _ in [] }+        #expect(left.revision != fewer.revision)+    }++    @Test func actualBatchPreviewRejectsTokenAfterSavedLinkOnlyChange() throws {+        let fixture = try MCPBatchTaskPreviewFixture()+        let request = try fixture.request([fixture.item()])+        fixture.owner.context.insert(TaskLinkOccurrence(id: UUID(), kindRawValue: "attribution",+            sourceTaskID: fixture.targets[0].id, targetTaskID: fixture.targets[1].id, createdAt: Date()))+        try fixture.owner.context.save()+        let report = try MCPBatchTaskPreview.evaluate(request, container: fixture.owner.container,+            persistence: PersistenceAvailability(isFallbackStorageActive: false), includeComments: false)+        let entry = try #require(report.entries.first)+        #expect(entry.state == .invalid && entry.code == "REVISION_CONFLICT")+        let coverage = MCPBatchTaskPreviewFixture.field("revisionCoverage", entry.current)+        #expect(coverage == .string("task-fields-comments-links-v1"))+        #expect(MCPBatchTaskPreviewFixture.field("graphCoverage", entry.current) == .string("available"))+        #expect(MCPBatchTaskPreviewFixture.field("comments", entry.current) == nil)+    }++    @Test func retainedReceiptReplayStaysByteIdenticalAfterIncidenceChanges() async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        let coordinator = fixture.coordinator(save: { context, _ in try context.save() })+        let arguments = try fixture.updateArguments()+        let first = await coordinator.execute(tool: "update_task", arguments: arguments)+        #expect(try fixture.decode(first)["outcome"] as? String == "committed")+        fixture.owner.context.insert(TaskLinkOccurrence(id: UUID(), kindRawValue: "association",+            sourceTaskID: fixture.source.id, targetTaskID: fixture.target.id, createdAt: fixture.instant))+        try fixture.owner.context.save()+        let replay = await coordinator.execute(tool: "update_task", arguments: arguments)+        #expect(first.content.first?.text == replay.content.first?.text)+        let observer = try fixture.observer()+        #expect(try fixture.historicReceipt(in: observer.context).resultJSON == fixture.historicJSON)+        #expect(try fixture.historicReceipt(in: observer.context).requestJSON == fixture.historicRequest)+    }+}+#endif
Transit/TransitTests/TaskLinkWireTests.swift Changed +141 / -0
diff --git a/Transit/TransitTests/TaskLinkWireTests.swift b/Transit/TransitTests/TaskLinkWireTests.swiftnew file mode 100644index 00000000..243528c2--- /dev/null+++ b/Transit/TransitTests/TaskLinkWireTests.swift@@ -0,0 +1,141 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct TaskLinkWireTests {+    let source = UUID(uuidString: "10000000-0000-0000-0000-000000000001")!+    let target = UUID(uuidString: "10000000-0000-0000-0000-000000000002")!+    let revision = "r1:" + String(repeating: "a", count: 64)+    let occurrenceRevision = "l1:" + String(repeating: "b", count: 64)++    func arguments(changes: [[String: Any]]) -> [String: Any] {+        ["taskId": source.uuidString, "expectedRevision": revision, "idempotencyKey": "wire",+         "linkChanges": changes, "endpointPreconditions": []]+    }++    func addition(_ type: String = "blocks", target: UUID? = nil) -> [String: Any] {+        ["action": "add", "type": type, "targetTaskId": (target ?? self.target).uuidString]+    }++    @Test(arguments: TaskLinkType.allCases)+    func exactPublicTypesReachAcceptedCommandShape(type: TaskLinkType) throws {+        let command = try MCPWriteCommand.validate(+            tool: "update_task", arguments: arguments(changes: [addition(type.rawValue)]))+        #expect(command.tool == "update_task")+        let parsed = try #require(try TaskLinkWireRequest.parse(tool: command.tool, arguments: command.arguments))+        #expect(parsed.changes == [.add(type: type, target: target)])+    }++    @Test(arguments: [0, 50])+    func directiveBoundaryIsInclusive(count: Int) throws {+        let changes = (0..<count).map { _ in addition(target: UUID()) }+        _ = try MCPWriteCommand.validate(tool: "update_task", arguments: arguments(changes: changes))+    }++    @Test func omittedLinkFieldsPreserveOrdinaryCommandShape() throws {+        var args = arguments(changes: [])+        args.removeValue(forKey: "linkChanges")+        args.removeValue(forKey: "endpointPreconditions")+        args["name"] = "ordinary update"+        _ = try MCPWriteCommand.validate(tool: "update_task", arguments: args)+    }++    @Test(arguments: ["unknownType", "badUUID", "badL1", "duplicateRemove", "extraField", "sourcePrecondition",+                      "duplicateEndpoint", "oversize", "removeOnCreate", "self", "duplicateAddition"])+    // Each row isolates one closed-shape rejection through the actual command parser.+    // swiftlint:disable:next cyclomatic_complexity+    func malformedDeltaRejectsBeforeDomainLookup(fault: String) throws {+        var args = arguments(changes: [addition()])+        var tool = "update_task"+        switch fault {+        case "unknownType": args["linkChanges"] = [addition("blocked_by")]+        case "badUUID": args["linkChanges"] = [["action": "add", "type": "blocks", "targetTaskId": "T-42"]]+        case "badL1": args["linkChanges"] = [["action": "remove", "edgeId": target.uuidString,+                                              "occurrenceRevision": revision]]+        case "duplicateRemove":+            let remove: [String: Any] = ["action": "remove", "edgeId": target.uuidString,+                                         "occurrenceRevision": occurrenceRevision]+            args["linkChanges"] = [remove, remove]+        case "extraField": var add = addition(); add["displayId"] = 42; args["linkChanges"] = [add]+        case "sourcePrecondition":+            args["endpointPreconditions"] = [["taskId": source.uuidString, "expectedRevision": revision]]+        case "duplicateEndpoint":+            let guardValue = ["taskId": target.uuidString, "expectedRevision": revision]+            args["endpointPreconditions"] = [guardValue, guardValue]+        case "oversize": args["linkChanges"] = (0..<51).map { _ in addition(target: UUID()) }+        case "removeOnCreate":+            tool = "create_task"+            args = ["name": "created", "type": "feature", "projectId": source.uuidString, "idempotencyKey": "wire",+                    "linkChanges": [["action": "remove", "edgeId": target.uuidString,+                                      "occurrenceRevision": occurrenceRevision]]]+        case "self": args["linkChanges"] = [addition(target: source)]+        default: args["linkChanges"] = [addition("relates-to"), addition("relates-to")]+        }+        #expect(throws: MCPWriteFailure.self) { try MCPWriteCommand.validate(tool: tool, arguments: args) }+    }++    @Test(arguments: ["add", "remove"])+    func validShapeDoesNotPerformMissingReferenceOrSelectorLookup(action: String) throws {+        let change = action == "add" ? addition() : ["action": "remove", "edgeId": target.uuidString,+                                                     "occurrenceRevision": occurrenceRevision]+        _ = try MCPWriteCommand.validate(tool: "update_task", arguments: arguments(changes: [change]))+    }++    @Test(arguments: ["linkChanges", "endpointPreconditions"])+    func batchRejectsGraphFieldsBeforeAnyItemAcceptance(field: String) throws {+        var args: [String: Any] = ["taskId": source.uuidString, "expectedRevision": revision, "idempotencyKey": "wire"]+        args[field] = [] as [String]+        let request = try MCPBatchTaskRequestFixtures.document(mode: "execute", items: [+            ["itemId": "one", "operation": "update_task", "arguments": args]+        ])+        try MCPBatchTaskRequestFixtures.invalid(request, index: 0, field: field)+    }++    @Test(arguments: [false, true])+    func freshLinkRequestCannotBeAcceptedWithoutOwnedPolicy(genericCallback: Bool) async throws {+        let fixture = try TaskLinkCommitDiskFixture()+        var args = try fixture.updateArguments()+        args["linkChanges"] = [addition("relates-to", target: fixture.target.id)]+        args["endpointPreconditions"] = [["taskId": fixture.target.id.uuidString,+            "expectedRevision": try MCPRecordSnapshot.task(fixture.target, in: fixture.owner.context).revision]]+        var callbackCount = 0+        let policy: MCPBatchWritePolicy? = genericCallback+            ? MCPBatchWritePolicy(afterTaskApply: { _, _, _ in callbackCount += 1 }) : nil+        let result = try fixture.decode(await fixture.coordinator(save: { context, _ in try context.save() })+            .execute(tool: "update_task", arguments: args, batchPolicy: policy))+        #expect(result["accepted"] as? Bool == false && callbackCount == 0)+        let error = try #require(result["error"] as? [String: Any])+        #expect(error["code"] as? String == "PERSISTENCE_UNAVAILABLE")+        #expect(try fixture.receipts(in: fixture.owner.context).isEmpty)+    }++    @Test(arguments: ["create_task", "update_task"])+    func generatedArraySchemaClosesEachDirectiveAndBoundsCount(tool: String) throws {+        let definition = try #require(MCPToolDefinitions.coreTools.first { $0.name == tool })+        let changes = try #require(definition.inputSchema.properties?["linkChanges"])+        #expect(changes.maxItems == 50)+        let branches = try #require(changes.items?.oneOf)+        #expect(branches.count == (tool == "create_task" ? 1 : 2))+        #expect(branches.allSatisfy { $0.additionalProperties == false && $0.required?.isEmpty == false })+        let endpoints = try #require(definition.inputSchema.properties?["endpointPreconditions"])+        #expect(endpoints.maxItems == 50)+        let endpoint = try #require(endpoints.items?.oneOf?.first)+        #expect(endpoint.additionalProperties == false)+        #expect(Set(endpoint.required ?? []) == ["taskId", "expectedRevision"])+    }++    @Test func taskSchemasDescribeLinkGuardsAndUnsupportedBatches() throws {+        for name in ["create_task", "update_task"] {+            let definition = try #require(MCPToolDefinitions.coreTools.first { $0.name == name })+            #expect(definition.inputSchema.properties?["linkChanges"]?.type == "array")+            #expect(definition.inputSchema.properties?["endpointPreconditions"]?.type == "array")+            #expect(definition.description.contains("50"))+            #expect(definition.description.contains("seven days"))+            #expect(definition.description.contains("batch"))+        }+    }+}+#endif
Transit/TransitTests/TaskLinkWriteFixture.swift Changed +76 / -0
diff --git a/Transit/TransitTests/TaskLinkWriteFixture.swift b/Transit/TransitTests/TaskLinkWriteFixture.swiftnew file mode 100644index 00000000..4ec106ec--- /dev/null+++ b/Transit/TransitTests/TaskLinkWriteFixture.swift@@ -0,0 +1,76 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++/// The real shared protected handler/coordinator route with the production+/// feature adapter. No test code inserts graph changes on behalf of the SUT.+@MainActor struct TaskLinkWriteFixture {+    let base: TaskLinkCommitDiskFixture+    let coordinator: MCPWriteCoordinator+    let handler: MCPToolHandler++    init(base: TaskLinkCommitDiskFixture,+         save: @escaping @MainActor (ModelContext, MCPWriteCoordinator.SaveStage) throws -> Void =+            { context, _ in try context.save() },+         encode: @escaping @MainActor ([String: Any]) throws -> String = MCPWriteOutcome.encode,+         preparation: @escaping @MainActor (MCPWriteCommand) async throws -> Void = { _ in },+         newTaskID: @escaping @MainActor () -> UUID = UUID.init) {+        self.base = base+        coordinator = base.coordinator(save: save, encode: encode, preparation: preparation, newTaskID: newTaskID)+        let context = base.owner.context+        let tasks = TaskService(modelContext: context, displayIDAllocator: base.allocator)+        let projects = ProjectService(modelContext: context)+        let comments = CommentService(modelContext: context)+        let milestones = MilestoneService(modelContext: context, displayIDAllocator: base.allocator)+        let maintenance = DisplayIDMaintenanceService(modelContext: context, taskAllocator: base.allocator,+            milestoneAllocator: base.allocator, commentService: comments)+        handler = MCPToolHandler(taskService: tasks, projectService: projects, commentService: comments,+            milestoneService: milestones, maintenanceService: maintenance, settings: MCPSettings(),+            persistence: PersistenceAvailability(isFallbackStorageActive: false), writeCoordinator: coordinator,+            batchContainer: base.owner.container,+            taskLinkWriteAdapter: TaskLinkWriteAdapter(taskAllocator: base.allocator,+                                                     milestoneAllocator: base.allocator))+    }++    func revision(_ id: UUID) throws -> String {+        let observer = try base.observer()+        return try MCPRecordSnapshot.task(base.task(id, in: observer.context), in: observer.context).revision+    }++    func addition(type: String = "relates-to", key: String = "linked") throws -> [String: Any] {+        ["taskId": base.source.id.uuidString, "expectedRevision": try revision(base.source.id),+         "idempotencyKey": key, "linkChanges": [["action": "add", "type": type,+                                                "targetTaskId": base.target.id.uuidString]],+         "endpointPreconditions": [["taskId": base.target.id.uuidString,+                                    "expectedRevision": try revision(base.target.id)]]]+    }++    func removal(key: String = "remove") throws -> [String: Any] {+        let edge = base.edge+        let value = TaskLinkOccurrenceValue(physicalKey: Data(), id: edge.id, kind: edge.kindRawValue,+            source: edge.sourceTaskID, target: edge.targetTaskID, createdAt: edge.createdAt)+        return ["taskId": base.source.id.uuidString, "expectedRevision": try revision(base.source.id),+                "idempotencyKey": key, "linkChanges": [["action": "remove", "edgeId": edge.id.uuidString,+                    "occurrenceRevision": try TaskLinkGraph.occurrenceRevision(value)]],+                "endpointPreconditions": [["taskId": base.target.id.uuidString,+                                           "expectedRevision": try revision(base.target.id)]]]+    }++    func execute(_ arguments: [String: Any], tool: String = "update_task") async -> MCPToolResult {+        await handler.protectedWriteResult(tool: tool, arguments: arguments)+    }++    func receipts(for arguments: [String: Any], in context: ModelContext) throws -> [MCPWriteReceipt] {+        let key = try #require(arguments["idempotencyKey"] as? String)+        return try context.fetch(FetchDescriptor<MCPWriteReceipt>(predicate: #Predicate { $0.key == key }))+    }++    func assertOutcome(_ result: MCPToolResult, _ outcome: String, accepted: Bool = true) throws {+        let value = try base.decode(result)+        #expect(value["outcome"] as? String == outcome)+        #expect(value["accepted"] as? Bool == accepted)+    }+}+#endif
Transit/TransitTests/TaskLinkWriteIntegrationTests.swift Changed +198 / -0
diff --git a/Transit/TransitTests/TaskLinkWriteIntegrationTests.swift b/Transit/TransitTests/TaskLinkWriteIntegrationTests.swiftnew file mode 100644index 00000000..c4162359--- /dev/null+++ b/Transit/TransitTests/TaskLinkWriteIntegrationTests.swift@@ -0,0 +1,198 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct TaskLinkWriteIntegrationTests {+    @Test(arguments: ["relates-to", "introduced-by", "duplicate-of"])+    func mixedFieldsAndLinkCommitWithCoveredTerminalReceipt(type: String) async throws {+        let base = try TaskLinkCommitDiskFixture()+        let fixture = TaskLinkWriteFixture(base: base)+        let sourceProject = base.source.project?.id+        let targetDate = base.target.lastStatusChangeDate+        var args = try fixture.addition(type: type)+        args["name"] = "mixed committed"+        let result = await fixture.execute(args)+        try fixture.assertOutcome(result, "committed")+        let observer = try base.observer()+        let source = try base.task(base.source.id, in: observer.context)+        let target = try base.task(base.target.id, in: observer.context)+        #expect(source.name == "mixed committed" && source.project?.id == sourceProject)+        #expect(target.name == "target" && target.statusRawValue == "done" && target.lastStatusChangeDate == targetDate)+        #expect(try observer.context.fetchCount(FetchDescriptor<TaskLinkOccurrence>()) == 2)+        let record = try #require(try base.decode(result)["record"] as? [String: Any])+        #expect(record["revision"] as? String == (try MCPRecordSnapshot.task(source, in: observer.context).revision))+        #expect(try fixture.receipts(for: args, in: observer.context).first?.resultJSON == result.content.first?.text)+        #expect(try base.historicReceipt(in: observer.context).resultJSON == base.historicJSON)+    }++    @Test func createUsesItsFinalUUIDForProposedGraphAndOwnedSave() async throws {+        let base = try TaskLinkCommitDiskFixture()+        let fixture = TaskLinkWriteFixture(base: base)+        let projectID = try #require(base.source.project?.id)+        let args: [String: Any] = ["name": "linked creation", "type": "feature", "projectId": projectID.uuidString,+            "idempotencyKey": "created-link", "linkChanges": [["action": "add", "type": "blocked-by",+                "targetTaskId": base.target.id.uuidString]], "endpointPreconditions": [+                    ["taskId": base.target.id.uuidString, "expectedRevision": try fixture.revision(base.target.id)]]]+        let result = await fixture.execute(args, tool: "create_task")+        try fixture.assertOutcome(result, "committed")+        let record = try #require(try base.decode(result)["record"] as? [String: Any])+        let id = try #require((record["taskId"] as? String).flatMap(UUID.init(uuidString:)))+        #expect(id != base.source.id && id != base.target.id)+        let observer = try base.observer()+        let created = try base.task(id, in: observer.context)+        #expect(created.name == "linked creation" && created.project?.id == projectID)+        let edges = try observer.context.fetch(FetchDescriptor<TaskLinkOccurrence>())+        #expect(edges.filter { $0.sourceTaskID == base.target.id && $0.targetTaskID == id }.count == 1)+        #expect(record["revision"] as? String == (try MCPRecordSnapshot.task(created, in: observer.context).revision))+        let replay = await fixture.execute(args, tool: "create_task")+        #expect(replay.content.first?.text == result.content.first?.text)+        #expect(try observer.context.fetchCount(FetchDescriptor<TransitTask>()) == 3)+    }++    @Test func existingAdditionIsProtectedNoOpWithoutExtraEndpointGuard() async throws {+        let base = try TaskLinkCommitDiskFixture()+        let fixture = TaskLinkWriteFixture(base: base)+        var args = try fixture.addition(type: "blocked-by")+        args["endpointPreconditions"] = [] as [[String: String]]+        let before = try fixture.revision(base.source.id)+        let result = await fixture.execute(args)+        try fixture.assertOutcome(result, "committed")+        #expect(try fixture.revision(base.source.id) == before)+        let observer = try base.observer()+        #expect(try observer.context.fetchCount(FetchDescriptor<TaskLinkOccurrence>()) == 1)+        #expect(try fixture.receipts(for: args, in: observer.context).count == 1)+        let replay = await fixture.execute(args)+        #expect(replay.content.first?.text == result.content.first?.text)+    }++    @Test func exactRemovalFreshKeyNoOpAndReAddPreserveOriginalEvidence() async throws {+        let base = try TaskLinkCommitDiskFixture()+        let fixture = TaskLinkWriteFixture(base: base)+        let edgeID = base.edge.id+        let args = try fixture.removal()+        let first = await fixture.execute(args)+        try fixture.assertOutcome(first, "committed")+        let observer = try base.observer()+        let evidence = try observer.context.fetch(FetchDescriptor<TaskLinkRemovalEvidence>())+            .filter { $0.edgeId == edgeID }+        let original = try #require(evidence.count == 1 ? evidence.first : nil)+        var retry = args+        retry["idempotencyKey"] = "fresh-removal-noop"+        retry["expectedRevision"] = try fixture.revision(base.source.id)+        retry["endpointPreconditions"] = [] as [[String: String]]+        try fixture.assertOutcome(await fixture.execute(retry), "committed")+        let unchanged = try base.observer().context.fetch(FetchDescriptor<TaskLinkRemovalEvidence>())+            .filter { $0.edgeId == edgeID }+        #expect(unchanged.count == 1 && unchanged.first?.id == original.id)+        #expect(unchanged.first?.removedAt == original.removedAt)+        let reAdd = try fixture.addition(type: "blocked-by", key: "re-add")+        try fixture.assertOutcome(await fixture.execute(reAdd), "committed")+        let reopened = try base.observer()+        let edges = try reopened.context.fetch(FetchDescriptor<TaskLinkOccurrence>())+        #expect(edges.count == 1 && edges.first?.id != edgeID)+        let replay = await fixture.execute(args)+        #expect(replay.content.first?.text == first.content.first?.text)+    }++    @Test func removalOnlyRepairsExactRowWithoutAbsorbingUnrelatedCorruption() async throws {+        let base = try TaskLinkCommitDiskFixture()+        let unrelated = UUID()+        base.owner.context.insert(TaskLinkOccurrence(id: unrelated, kindRawValue: "future-kind",+            sourceTaskID: base.source.id, targetTaskID: UUID(), createdAt: base.instant))+        try base.owner.context.save()+        let fixture = TaskLinkWriteFixture(base: base)+        let args = try fixture.removal()+        let result = await fixture.execute(args)+        try fixture.assertOutcome(result, "committed")+        let observer = try base.observer()+        let edges = try observer.context.fetch(FetchDescriptor<TaskLinkOccurrence>())+        #expect(edges.count == 1 && edges.first?.id == unrelated && edges.first?.kindRawValue == "future-kind")+        #expect(try base.task(base.source.id, in: observer.context).name == "source")+    }++    @Test(arguments: ["source", "endpoint"])+    func savedRevisionChangeDuringPreparationRejectsBeforeGraphApply(changed: String) async throws {+        let base = try TaskLinkCommitDiskFixture()+        let peer = try base.observer()+        let fixture = TaskLinkWriteFixture(base: base, preparation: { _ in+            let id = changed == "source" ? base.source.id : base.target.id+            try base.task(id, in: peer.context).name = "outside saved change"+            try peer.context.save()+        })+        let args = try fixture.addition()+        let result = await fixture.execute(args)+        try fixture.assertOutcome(result, "rejected")+        let decoded = try base.decode(result)+        #expect((decoded["error"] as? [String: Any])?["code"] as? String == "REVISION_CONFLICT")+        #expect((decoded["currentRecord"] as? [String: Any])?["graphCoverage"] as? String == "available")+        let observer = try base.observer()+        #expect(try observer.context.fetchCount(FetchDescriptor<TaskLinkOccurrence>()) == 1)+        #expect(try fixture.receipts(for: args, in: observer.context).first?.stateRawValue == "rejected")+    }++    @Test(arguments: ["cycle", "missing"])+    func validShapeDomainRejectionRetainsKeyAndNoDomainEffects(fault: String) async throws {+        let base = try TaskLinkCommitDiskFixture()+        let fixture = TaskLinkWriteFixture(base: base)+        var args = try fixture.addition(type: "blocks")+        if fault == "missing" {+            let absent = UUID()+            args["linkChanges"] = [["action": "add", "type": "relates-to", "targetTaskId": absent.uuidString]]+            args["endpointPreconditions"] = [["taskId": absent.uuidString,+                "expectedRevision": "r1:" + String(repeating: "a", count: 64)]]+        }+        let first = await fixture.execute(args)+        try fixture.assertOutcome(first, "rejected")+        #expect((try base.decode(first)["error"] as? [String: Any])?["code"] as? String != "PERSISTENCE_UNAVAILABLE")+        let observer = try base.observer()+        #expect(try observer.context.fetchCount(FetchDescriptor<TaskLinkOccurrence>()) == 1)+        #expect(try fixture.receipts(for: args, in: observer.context).first?.resultJSON == first.content.first?.text)+        let replay = await fixture.execute(args)+        #expect(first.content.first?.text == replay.content.first?.text)+    }++    @Test(arguments: ["save", "encode"])+    func failedTerminalCommitRollsBackFieldsAndGraphTogether(failure: String) async throws {+        let base = try TaskLinkCommitDiskFixture()+        let fixture = TaskLinkWriteFixture(base: base, save: { context, stage in+            if case .commit = stage, failure == "save" { throw TaskLinkCommitDiskFixture.Failure.injected }+            try context.save()+        }, encode: { envelope in+            if failure == "encode", envelope["outcome"] as? String == "committed" {+                throw TaskLinkCommitDiskFixture.Failure.injected+            }+            return try MCPWriteOutcome.encode(envelope)+        })+        var args = try fixture.addition()+        args["name"] = "must rollback"+        let result = await fixture.execute(args)+        try fixture.assertOutcome(result, "rejected")+        let observer = try base.observer()+        #expect(try base.task(base.source.id, in: observer.context).name == "source")+        #expect(try observer.context.fetchCount(FetchDescriptor<TaskLinkOccurrence>()) == 1)+        #expect(try fixture.receipts(for: args, in: observer.context).first?.stateRawValue == "rejected")+    }++    @Test(arguments: [false, true])+    func dirtyAfterPreparationPreservesDraftAndAcceptedReconciliation(throwing: Bool) async throws {+        let base = try TaskLinkCommitDiskFixture()+        var prepared = false+        let fixture = TaskLinkWriteFixture(base: base, preparation: { _ in+            prepared = true+            base.source.name = "UI draft"+            if throwing { throw TaskLinkCommitDiskFixture.Failure.injected }+        })+        let args = try fixture.addition()+        let result = await fixture.execute(args)+        try fixture.assertOutcome(result, "uncertain")+        #expect(prepared && base.source.name == "UI draft" && base.owner.context.hasChanges)+        let observer = try base.observer()+        #expect(try base.task(base.source.id, in: observer.context).name == "source")+        #expect(try observer.context.fetchCount(FetchDescriptor<TaskLinkOccurrence>()) == 1)+        #expect(try fixture.receipts(for: args, in: observer.context).first?.stateRawValue == "accepted")+    }+}+#endif
Transit/TransitTests/TaskLinkWriteRepairTests.swift Changed +94 / -0
diff --git a/Transit/TransitTests/TaskLinkWriteRepairTests.swift b/Transit/TransitTests/TaskLinkWriteRepairTests.swiftnew file mode 100644index 00000000..d3c73395--- /dev/null+++ b/Transit/TransitTests/TaskLinkWriteRepairTests.swift@@ -0,0 +1,94 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct TaskLinkWriteRepairTests {+    @Test(arguments: ["self", "unknown", "dangling", "equivalent"])+    func exactRepairPreservesOtherPhysicalRowsAndSupportsFreshKeyNoOp(fault: String) async throws {+        let base = try TaskLinkCommitDiskFixture()+        let sourceID = base.source.id+        let targetID = base.target.id+        let edgeID = UUID()+        base.owner.context.delete(base.edge)+        let kind = fault == "unknown" ? "future-kind" : "dependency"+        let opposite = fault == "self" ? sourceID : (fault == "dangling" ? UUID() : targetID)+        let row = TaskLinkOccurrence(id: edgeID, kindRawValue: kind, sourceTaskID: sourceID,+                                     targetTaskID: opposite, createdAt: base.instant)+        base.owner.context.insert(row)+        let otherID = UUID()+        if fault == "equivalent" {+            base.owner.context.insert(TaskLinkOccurrence(id: otherID, kindRawValue: kind,+                sourceTaskID: sourceID, targetTaskID: opposite, createdAt: base.instant))+        }+        try base.owner.context.save()+        let fixture = TaskLinkWriteFixture(base: base)+        let value = TaskLinkOccurrenceValue(physicalKey: Data(), id: edgeID, kind: kind,+            source: sourceID, target: opposite, createdAt: base.instant)+        var args: [String: Any] = ["taskId": sourceID.uuidString, "expectedRevision": try fixture.revision(sourceID),+            "idempotencyKey": "repair", "linkChanges": [["action": "remove", "edgeId": edgeID.uuidString,+                "occurrenceRevision": try TaskLinkGraph.occurrenceRevision(value)]],+            "endpointPreconditions": fault == "self" || fault == "dangling" ? [] : [+                ["taskId": targetID.uuidString, "expectedRevision": try fixture.revision(targetID)]]]+        try fixture.assertOutcome(await fixture.execute(args), "committed")+        let observed = try base.observer()+        let edges = try observed.context.fetch(FetchDescriptor<TaskLinkOccurrence>())+        #expect(edges.count == (fault == "equivalent" ? 1 : 0))+        #expect(edges.allSatisfy { $0.id == otherID })+        let before = try fixture.revision(sourceID)+        let evidence = try observed.context.fetch(FetchDescriptor<TaskLinkRemovalEvidence>())+            .filter { $0.edgeId == edgeID }+        let original = try #require(evidence.count == 1 ? evidence.first : nil)+        #expect(original.kindRawValue == kind && original.sourceTaskID == sourceID && original.targetTaskID == opposite)+        args["idempotencyKey"] = "repair-noop"+        args["expectedRevision"] = before+        args["endpointPreconditions"] = [] as [[String: String]]+        try fixture.assertOutcome(await fixture.execute(args), "committed")+        #expect(try fixture.revision(sourceID) == before)+        let reopened = try base.observer()+        let unchanged = try reopened.context.fetch(FetchDescriptor<TaskLinkRemovalEvidence>())+            .filter { $0.edgeId == edgeID }+        #expect(unchanged.count == 1 && unchanged.first?.id == original.id)+        #expect(unchanged.first?.removedAt == original.removedAt)+    }++    @Test func chosenCreationUUIDCollisionRejectsWithoutDomainInsertion() async throws {+        let base = try TaskLinkCommitDiskFixture()+        let collision = base.source.id+        let fixture = TaskLinkWriteFixture(base: base, newTaskID: { collision })+        let projectID = try #require(base.source.project?.id)+        let args: [String: Any] = ["name": "collision", "type": "feature", "projectId": projectID.uuidString,+            "idempotencyKey": "collision", "linkChanges": [["action": "add", "type": "relates-to",+                "targetTaskId": base.target.id.uuidString]], "endpointPreconditions": [+                    ["taskId": base.target.id.uuidString, "expectedRevision": try fixture.revision(base.target.id)]]]+        let result = await fixture.execute(args, tool: "create_task")+        try fixture.assertOutcome(result, "rejected")+        #expect((try base.decode(result)["error"] as? [String: Any])?["code"] as? String+            == "DUPLICATE_TASK_IDENTIFIER")+        let observer = try base.observer()+        #expect(try observer.context.fetchCount(FetchDescriptor<TransitTask>()) == 2)+        #expect(try observer.context.fetchCount(FetchDescriptor<TaskLinkOccurrence>()) == 1)+        #expect(try fixture.receipts(for: args, in: observer.context).first?.stateRawValue == "rejected")+    }++    @Test func retainedReplayDoesNotValidateOrSaveDirtyGraphDraft() async throws {+        let base = try TaskLinkCommitDiskFixture()+        var preparations = 0+        let fixture = TaskLinkWriteFixture(base: base, preparation: { _ in preparations += 1 })+        let args = try fixture.addition()+        let first = await fixture.execute(args)+        try fixture.assertOutcome(first, "committed")+        base.source.name = "unsaved source"+        base.owner.context.insert(TaskLinkOccurrence(id: UUID(), kindRawValue: "future-kind",+            sourceTaskID: base.source.id, targetTaskID: UUID(), createdAt: Date()))+        let replay = await fixture.execute(args)+        #expect(replay.content.first?.text == first.content.first?.text)+        #expect(preparations == 1 && base.source.name == "unsaved source" && base.owner.context.hasChanges)+        let observer = try base.observer()+        #expect(try base.task(base.source.id, in: observer.context).name == "source")+        #expect(try observer.context.fetchCount(FetchDescriptor<TaskLinkOccurrence>()) == 2)+    }+}+#endif
Transit/TransitTests/TestModelContainer.swift Changed +2 / -1
diff --git a/Transit/TransitTests/TestModelContainer.swift b/Transit/TransitTests/TestModelContainer.swiftindex cdf062f8..048d2e10 100644--- a/Transit/TransitTests/TestModelContainer.swift+++ b/Transit/TransitTests/TestModelContainer.swift@@ -20,7 +20,8 @@ struct TestModelContainer {      init() throws {         let schema = Schema([-            Project.self, TransitTask.self, Comment.self, Milestone.self, SyncHeartbeat.self, MCPWriteReceipt.self+            Project.self, TransitTask.self, Comment.self, Milestone.self, SyncHeartbeat.self, MCPWriteReceipt.self,+            TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self         ])         let config = ModelConfiguration(             "TransitTests-\(UUID().uuidString)",
Transit/TransitUITests/TaskLinkNativeUITests.swift Changed +48 / -0
diff --git a/Transit/TransitUITests/TaskLinkNativeUITests.swift b/Transit/TransitUITests/TaskLinkNativeUITests.swiftnew file mode 100644index 00000000..1bdc437e--- /dev/null+++ b/Transit/TransitUITests/TaskLinkNativeUITests.swift@@ -0,0 +1,48 @@+import XCTest++final class TaskLinkNativeUITests: XCTestCase {+    private let targetID = "00000000-0000-0000-0000-000000173402"++    override func setUpWithError() throws { continueAfterFailure = false }++    @MainActor func testSavedRelationshipOpensExactUUIDDestination() throws {+        let app = launch(scenario: "taskLinks")+        let button = app.buttons["task-links.target.\(targetID)"]+        reveal(button, in: app)+        XCTAssertTrue(button.waitForExistence(timeout: 5))+        button.tap()+        let destination = app.staticTexts["task-links.observation.\(targetID)"]+        reveal(destination, in: app)+        XCTAssertTrue(destination.waitForExistence(timeout: 5))+    }++    @MainActor func testAmbiguousDestinationIsDiagnosedWithoutArbitraryNavigation() throws {+        let app = launch(scenario: "taskLinksAmbiguous")+        let diagnostic = app.staticTexts["task-links.diagnostic.ambiguous_endpoint"]+        reveal(diagnostic, in: app)+        XCTAssertTrue(diagnostic.waitForExistence(timeout: 5))+        XCTAssertFalse(app.buttons["task-links.target.\(targetID)"].exists)+        XCTAssertFalse(app.staticTexts["task-links.observation.\(targetID)"].exists)+    }++    @MainActor private func launch(scenario: String) -> XCUIApplication {+        let app = XCUIApplication()+        app.launchEnvironment["TRANSIT_PERSISTENCE_MODE"] = "ui-test"+        app.launchEnvironment["TRANSIT_UI_TEST_SCENARIO"] = scenario+        app.launch()+        let source = app.staticTexts["Linked Source"]+        XCTAssertTrue(source.waitForExistence(timeout: 5))+        source.tap()+        return app+    }++    @MainActor private func reveal(_ element: XCUIElement, in app: XCUIApplication) {+        for _ in 0..<6 where !element.isHittable {+            #if os(macOS)+            app.scrollViews.firstMatch.scroll(byDeltaX: 0, deltaY: -300)+            #else+            app.swipeUp()+            #endif+        }+    }+}
specs/development-isolation/path-guard-source-checkpoint.json Changed +17 / -0
diff --git a/specs/development-isolation/path-guard-source-checkpoint.json b/specs/development-isolation/path-guard-source-checkpoint.jsonnew file mode 100644index 00000000..9cf77c65--- /dev/null+++ b/specs/development-isolation/path-guard-source-checkpoint.json@@ -0,0 +1,17 @@+{+  "parent": "a7afeb81a2a54f2d8aa30f67d86d248faf3c3de0",+  "FoundationBehaviorReproduced": true,+  "SwiftRegressionExecuted": false,+  "fullHarnessExecuted": false,+  "lint": {+    "files": 407,+    "violations": 0+  },+  "sandboxesUnchanged": true,+  "fileSHA256": {+    "Makefile": "43b2d9dafff57d65d7111f631b8688ba46d93bf86d087b0b3718bd23dd123e0d",+    "tests/development-isolation/DisposableStorePath.swift": "bd1e917bd90dd8baf2bc2c9351ae80339dff311ba97ab7a53080d29f03e4de30",+    "tests/development-isolation/MigrationProbe.swift": "153b4af7b2a2e7d5cf66f47d500b72ce12111a89a353f1a708787f41474f9787",+    "tests/development-isolation/run.py": "850c10145b296d4e28146778f9fbfc902fb5dc051560da21e7f7ca6a5f26fa4a"+  }+}
specs/development-isolation/t1734-source-checkpoint.json Changed +48 / -0
diff --git a/specs/development-isolation/t1734-source-checkpoint.json b/specs/development-isolation/t1734-source-checkpoint.jsonnew file mode 100644index 00000000..69f07eeb--- /dev/null+++ b/specs/development-isolation/t1734-source-checkpoint.json@@ -0,0 +1,48 @@+{+  "parent": "594c54987146b39257f26b1d152999fb452e8f6b",+  "verifiedIsolationSource": "9ba4297b9747673f3a39486e7ff66ced16f8b741",+  "staticGuardsPassed": true,+  "ownedSwiftLint": {+    "files": 15,+    "violations": 0+  },+  "fullLint": {+    "files": 406,+    "violations": 3,+    "allInUnchangedOwnerFixture": true+  },+  "MCPModelsAndOwnerFixturesUnchanged": true,+  "branchRuntimeVerified": false,+  "fileSHA256": {+    "Transit/Transit/TransitApp.swift": "d6cf9dcb0ae63527b1c87554ce4b57b25c5cbeed26609e148b63ed9379a7514d",+    "Transit/Transit.xcodeproj/project.pbxproj": "207934daaf68fae13c31519b428b8100e552a0a99353b0a8525ae6a4e2bd79cd",+    "Makefile": "b820f4365bcd368424b5e1b6a0970a59c5e57075f68ae35ab7a756a200ddde53",+    "Transit/TransitTests/TaskLinkMigrationTests.swift": "d4a3835743695dae4ddde3174ef56143e0ab1d83da10aa653b2d0f8b7b78af59",+    "Transit/TransitTests/TestModelContainer.swift": "e8ace9bf519754289926bfc517c0fe4c9071f8e8dc3d05ccafa3df72a08387f5",+    "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/Writes/MCPWriteReceiptStore.swift": "1956f3368c974edab3a5c46a206c58544b8e125dd3a18917e2c7fee5f4041c9b",+    "Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift": "4ee5f5bf7bcee684825a74c04528b8281b22f285dae3c9426230989bf1e1be83",+    "Transit/Transit/MCP/Writes/MCPWriteOutcome.swift": "e124654549a55eb2299ca9b6a5f392b8160afba3b44e30d2b0c1cdcca579d628",+    "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"+  }+}
tests/mcp-write-probe/CoordinatorProbe.swift Changed +2 / -1
diff --git a/tests/mcp-write-probe/CoordinatorProbe.swift b/tests/mcp-write-probe/CoordinatorProbe.swiftindex 06699886..05224358 100644--- a/tests/mcp-write-probe/CoordinatorProbe.swift+++ b/tests/mcp-write-probe/CoordinatorProbe.swift@@ -10,7 +10,8 @@ struct MCPWriteCoordinatorProbe {         defer { try? FileManager.default.removeItem(at: directory) }         let schema = Schema([             Project.self, TransitTask.self, Comment.self, Milestone.self,-            SyncHeartbeat.self, MCPWriteReceipt.self+            SyncHeartbeat.self, MCPWriteReceipt.self,+            TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self         ])         let configuration = ModelConfiguration(             schema: schema, url: directory.appendingPathComponent("probe.store"),
tests/mcp-write-probe/FoundationProbe.swift Changed +6 / -5
diff --git a/tests/mcp-write-probe/FoundationProbe.swift b/tests/mcp-write-probe/FoundationProbe.swiftindex ca90eb2c..91b3859e 100644--- a/tests/mcp-write-probe/FoundationProbe.swift+++ b/tests/mcp-write-probe/FoundationProbe.swift@@ -19,15 +19,15 @@ struct MCPWriteFoundationProbe {         let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "red")         let task = TransitTask(name: "T", type: .feature, project: project, displayID: .permanent(1))         let comment = Comment(content: "C", authorName: "A", isAgent: false, task: task)-        let original = try MCPRecordSnapshot.task(task) { _ in [comment] }+        let original = try MCPRecordSnapshot.task(task, incidence: []) { _ in [comment] }         project.name = "excluded"-        let excluded = try MCPRecordSnapshot.task(task) { _ in [comment] }+        let excluded = try MCPRecordSnapshot.task(task, incidence: []) { _ in [comment] }         precondition(original.revision == excluded.revision)         comment.content = "changed"-        let changed = try MCPRecordSnapshot.task(task) { _ in [comment] }+        let changed = try MCPRecordSnapshot.task(task, incidence: []) { _ in [comment] }         precondition(original.revision != changed.revision)         comment.content = "C"-        let restored = try MCPRecordSnapshot.task(task) { _ in [comment] }+        let restored = try MCPRecordSnapshot.task(task, incidence: []) { _ in [comment] }         precondition(original.revision == restored.revision)         print("PASS canonical roundtrip and content revisions")         try receiptStorage()@@ -52,7 +52,8 @@ struct MCPWriteFoundationProbe {      @MainActor static func receiptStorage() throws {         let schema = Schema([Project.self, TransitTask.self, Comment.self, Milestone.self,-                             SyncHeartbeat.self, MCPWriteReceipt.self])+                             SyncHeartbeat.self, MCPWriteReceipt.self,+                             TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self])         let configuration = ModelConfiguration("receipt-probe", schema: schema,                                                isStoredInMemoryOnly: true, cloudKitDatabase: .none)         let container = try ModelContainer(for: schema, configurations: configuration)
tests/mcp-write-probe/Probe.swift Changed +5 / -1
diff --git a/tests/mcp-write-probe/Probe.swift b/tests/mcp-write-probe/Probe.swiftindex 1f4602ab..808487a5 100644--- a/tests/mcp-write-probe/Probe.swift+++ b/tests/mcp-write-probe/Probe.swift@@ -13,7 +13,11 @@ struct MCPWriteDiskProbe {         var models: [any PersistentModel.Type] = [             Project.self, TransitTask.self, Comment.self, Milestone.self, SyncHeartbeat.self         ]-        if mode != "seed-old" { models.append(MCPWriteReceipt.self) }+        if mode != "seed-old" {+            models.append(MCPWriteReceipt.self)+            models.append(TaskLinkOccurrence.self)+            models.append(TaskLinkRemovalEvidence.self)+        }         let schema = Schema(models)         let configuration = ModelConfiguration(schema: schema, url: url,                                                allowsSave: mode != "readonly", cloudKitDatabase: .none)
tests/mcp-write-probe/ServiceProbe.swift Changed +2 / -1
diff --git a/tests/mcp-write-probe/ServiceProbe.swift b/tests/mcp-write-probe/ServiceProbe.swiftindex 7683de73..11d0b95f 100644--- a/tests/mcp-write-probe/ServiceProbe.swift+++ b/tests/mcp-write-probe/ServiceProbe.swift@@ -6,7 +6,8 @@ struct MCPWriteServiceProbe {     // swiftlint:disable:next function_body_length     @MainActor static func main() async throws {         let schema = Schema([Project.self, TransitTask.self, Comment.self, Milestone.self,-                             SyncHeartbeat.self, MCPWriteReceipt.self])+                             SyncHeartbeat.self, MCPWriteReceipt.self,+                             TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self])         let config = ModelConfiguration("service-probe", schema: schema,                                         isStoredInMemoryOnly: true, cloudKitDatabase: .none)         let container = try ModelContainer(for: schema, configurations: config)
tests/typed-task-links/audit_schema_sources.py Changed +75 / -0
diff --git a/tests/typed-task-links/audit_schema_sources.py b/tests/typed-task-links/audit_schema_sources.pynew file mode 100644index 00000000..f1f6b6fd--- /dev/null+++ b/tests/typed-task-links/audit_schema_sources.py@@ -0,0 +1,75 @@+"""Source inventory/RED guard only; no compilation, store, or CloudKit access.++python3 tests/typed-task-links/audit_schema_sources.py+python3 tests/typed-task-links/audit_schema_sources.py --check++--check requires source registrations in the audited current-schema factories.+It deliberately fails while task2 models/registrations are absent. A source PASS+cannot prove migration, SwiftData inferred schema, or server record registration.+"""++import argparse+import json+import pathlib+import re+++CURRENT = {+    "Transit/Transit/TransitApp.swift",+    "Transit/TransitTests/TestModelContainer.swift",+    "Transit/TransitTests/MCPWritePersistenceProbeTests.swift",+    "tests/mcp-write-probe/ServiceProbe.swift",+    "tests/mcp-write-probe/CoordinatorProbe.swift",+    "tests/mcp-write-probe/FoundationProbe.swift",+}+LINKS = {"TaskLinkOccurrence", "TaskLinkRemovalEvidence"}+++def main():+    parser = argparse.ArgumentParser(description=__doc__)+    parser.add_argument("--check", action="store_true")+    args = parser.parse_args()+    root = pathlib.Path(__file__).resolve().parents[2]+    inventory = []+    missing = []+    seen = set()+    for base in (root / "Transit", root / "tests/mcp-write-probe", root / "tests/development-isolation"):+        for path in sorted(base.rglob("*.swift")):+            source = path.read_text()+            relative = str(path.relative_to(root))+            for match in re.finditer(r"(?<!\w)Schema\s*\(\s*\[([\s\S]*?)\]\s*\)", source):+                models = sorted(set(re.findall(r"(?:\w+\.)?(\w+)\.self", match.group(1))))+                current = relative in CURRENT+                seen.add(relative)+                absent = sorted(LINKS - set(models)) if current else []+                inventory.append(dict(path=relative, line=source.count("\n", 0, match.start()) + 1,+                                      models=models, scope="current parity" if current else "limited/control",+                                      missingLinkSourceRegistrations=absent))+                if absent:+                    missing.append(relative)+    dynamic = root / "tests/mcp-write-probe/Probe.swift"+    source = dynamic.read_text()+    registrations = sorted(set(re.findall(r"(?:\w+\.)?(\w+)\.self", source)))+    # Dynamic mode-specific registration needs owner review as well as presence:+    # seed-old intentionally remains pre-receipt/pre-link; current modes add links.+    inventory.append(dict(path=str(dynamic.relative_to(root)), scope="dynamic current modes / seed-old legacy",+                          modelsMentioned=registrations, manualModeBranchReviewRequired=True,+                          missingLinkSourceRegistrations=sorted(LINKS - set(registrations))))+    if not LINKS.issubset(registrations):+        missing.append(str(dynamic.relative_to(root)))+    missing.extend(sorted(CURRENT - seen))+    result = dict(evidence="static source tokens only", inventory=inventory,+                  containerFactory="receives caller schema; no model registration",+                  productionModelFilesPresent=all((root / "Transit/Transit/Models" / (name + ".swift")).is_file()+                                                  for name in LINKS),+                  currentSourceParityMissing=sorted(set(missing)),+                  excluded="JSONSchema; custom limited/control schemas do not mint graph coverage",+                  developmentIsolation="MigrationProbe historical/current isolation fixture remains graph-free",+                  cloudKitServerEvidence=False)+    print(json.dumps(result, indent=2))+    if args.check and (missing or not result["productionModelFilesPresent"]):+        raise SystemExit(1)+++if __name__ == "__main__":+    main()
tests/typed-task-links/development-cloudkit/Smoke.swift Changed +213 / -0
diff --git a/tests/typed-task-links/development-cloudkit/Smoke.swift b/tests/typed-task-links/development-cloudkit/Smoke.swiftnew file mode 100644index 00000000..9357e877--- /dev/null+++ b/tests/typed-task-links/development-cloudkit/Smoke.swift@@ -0,0 +1,213 @@+import CloudKit+import Foundation+import SwiftData++// Deliberately excluded from app/test targets. Task2 must supply the real model+// declarations and these explicit scalar initializers before compilation.+@MainActor @main+struct TaskLinkDevelopmentSmoke {+    struct Mapping: Decodable {+        let recordType: String+        let exemplarRecordName: String+        let fields: [String: String]+    }++    struct Contract: Decodable {+        let containerID: String+        let zoneName: String+        let ownerName: String+        let uuidRepresentation: String+        let reservedDevelopmentEnvironment: Bool+        let occurrence: Mapping+        let removal: Mapping+    }++    enum Failure: Error { case invalid(String) }++    static func require(_ condition: Bool, _ message: String) throws {+        if !condition { throw Failure.invalid(message) }+    }++    static func main() async throws {+        let arguments = CommandLine.arguments+        try require(arguments.count == 3, "Expected reviewed contract and fresh private store directory")+        try require(ProcessInfo.processInfo.environment["T1734_DEV_SMOKE_CLEARED"] == "1",+                    "Reserved development host/slot clearance required")+        let contractBytes = try Data(contentsOf: URL(fileURLWithPath: arguments[1]))+        let contract = try JSONDecoder().decode(Contract.self, from: contractBytes)+        try require(contract.reservedDevelopmentEnvironment && contract.containerID.hasPrefix("iCloud."),+                    "Reserved development contract required")+        try require(["uuid-string", "uuid-data"].contains(contract.uuidRepresentation), "Unsupported UUID mapping")+        let directory = URL(fileURLWithPath: arguments[2]).standardizedFileURL+        try require(!FileManager.default.fileExists(atPath: directory.path), "Fresh store required")+        let parent = directory.deletingLastPathComponent()+        let home = URL(fileURLWithPath: NSHomeDirectory())+        let privateTemp = home.appendingPathComponent("tmp")+        try require(home.path.hasSuffix("/Library/Containers/me.nore.ig.Transit.development.cloudkit-smoke/Data"),+                    "Reserved smoke-host sandbox required")+        try require(parent == privateTemp && directory.lastPathComponent.hasPrefix("T1734Dev-"),+                    "Store must be in smoke-host private tmp")+        try require(parent.resolvingSymlinksInPath().path == parent.path, "Symlink parent forbidden")+        try require((try? FileManager.default.destinationOfSymbolicLink(atPath: directory.path)) == nil,+                    "Symlink store root forbidden")+        let database = CKContainer(identifier: contract.containerID).privateCloudDatabase+        let zone = CKRecordZone.ID(zoneName: contract.zoneName, ownerName: contract.ownerName)+        // Existing operator-pinned exemplars prevent creating a missing schema+        // as a side effect of the test's first SwiftData save.+        let occurrenceFields = ["id", "kindRawValue", "sourceTaskID", "targetTaskID", "createdAt"]+        let removalFields = occurrenceFields + ["edgeId", "occurrenceRevision", "removedAt"]+        try await validateExemplar(contract.occurrence, fields: occurrenceFields, database: database, zone: zone)+        try await validateExemplar(contract.removal, fields: removalFields, database: database, zone: zone)+        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)+        // Scalar-only models have no task relationships; register exactly these+        // two existing development record types to avoid initializing others.+        let schema = Schema([TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self])+        let configuration = ModelConfiguration(schema: schema, url: directory.appendingPathComponent("smoke.store"),+                                               cloudKitDatabase: .private(contract.containerID))+        let container = try ModelContainer(for: schema, configurations: configuration)+        let context = ModelContext(container)+        context.autosaveEnabled = false+        try await verifyDeletion(context: context, database: database, zone: zone,+                                 contract: contract, directory: directory)+        // Retain all synthetic store/evidence files; no cleanup or direct CK delete.+        withExtendedLifetime(container) {}+    }++    static func validateExemplar(_ mapping: Mapping, fields: [String], database: CKDatabase,+                                 zone: CKRecordZone.ID) async throws {+        try require(Set(mapping.fields.keys) == Set(fields), "Complete field mapping required")+        try require(Set(mapping.fields.values).count == fields.count, "Distinct server fields required")+        let recordID = CKRecord.ID(recordName: mapping.exemplarRecordName, zoneID: zone)+        let record = try await database.configuredWith(configuration: networkPolicy()) { scoped in+            try await scoped.record(for: recordID)+        }+        try require(record.recordType == mapping.recordType, "Existing development record type mismatch")+        for field in fields {+            try require(record[mapping.fields[field]!] != nil, "Existing server field missing: \(field)")+        }+    }++    // The single storage/export/deletion sequence intentionally shows the whole smoke contract.+    // swiftlint:disable:next function_body_length+    static func verifyDeletion(context: ModelContext, database: CKDatabase, zone: CKRecordZone.ID,+                               contract: Contract, directory: URL) async throws {+        let edgeID = UUID(), removalID = UUID(), sourceID = UUID(), targetID = UUID()+        let created = Date(timeIntervalSince1970: floor(Date.now.timeIntervalSince1970))+        let occurrence = TaskLinkOccurrence(id: edgeID, kindRawValue: "association", sourceTaskID: sourceID,+                                            targetTaskID: targetID, createdAt: created)+        try require(occurrence.id == edgeID && occurrence.kindRawValue == "association"+                    && occurrence.sourceTaskID == sourceID && occurrence.targetTaskID == targetID+                    && occurrence.createdAt == created, "Local occurrence scalar fields mismatch")+        let expected: [String: Any] = ["id": edgeID, "kindRawValue": "association", "sourceTaskID": sourceID,+                                       "targetTaskID": targetID, "createdAt": created]+        context.insert(occurrence)+        try context.save()+        let clock = ContinuousClock()+        let deadline = clock.now.advanced(by: .seconds(120))+        var token: CKServerChangeToken?+        var activeRecordID: CKRecord.ID?+        var visits = 0+        while activeRecordID == nil {+            try require(clock.now < deadline && visits < 64, "Occurrence export deadline/budget exceeded")+            let previous = token+            let page = try await database.configuredWith(configuration: networkPolicy()) { scoped in+                try await scoped.recordZoneChanges(inZoneWith: zone, since: previous, resultsLimit: 100)+            }+            token = page.changeToken+            visits += 1+            for change in page.modificationResultsByID.values {+                let record = try change.get().record+                if record.recordType == contract.occurrence.recordType,+                   matchesUUID(record[contract.occurrence.fields["id"]!], edgeID, contract.uuidRepresentation) {+                    try assertFields(record, mapping: contract.occurrence, expected: expected, contract: contract)+                    activeRecordID = record.recordID+                }+            }+            if !page.moreComing && activeRecordID == nil { try await Task.sleep(for: .seconds(1)) }+        }+        guard let originalRecordID = activeRecordID else { throw Failure.invalid("Occurrence record absent") }+        let removed = Date(timeIntervalSince1970: floor(Date.now.timeIntervalSince1970))+        let revision = "l1:" + String(repeating: "0", count: 64) // Storage smoke, not fingerprint verification.+        let evidence = TaskLinkRemovalEvidence(id: removalID, edgeId: edgeID, kindRawValue: "association",+                                              sourceTaskID: sourceID, targetTaskID: targetID, createdAt: created,+                                              occurrenceRevision: revision, removedAt: removed)+        context.delete(occurrence)+        context.insert(evidence)+        try context.save()+        var removalExpected = expected+        removalExpected["id"] = removalID+        removalExpected["edgeId"] = edgeID+        removalExpected["occurrenceRevision"] = revision+        removalExpected["removedAt"] = removed+        var deletionObserved = false, evidenceObserved = false+        while !deletionObserved || !evidenceObserved {+            try require(clock.now < deadline && visits < 64, "Platform deletion/export deadline/budget exceeded")+            let previous = token+            let page = try await database.configuredWith(configuration: networkPolicy()) { scoped in+                try await scoped.recordZoneChanges(inZoneWith: zone, since: previous, resultsLimit: 100)+            }+            token = page.changeToken+            visits += 1+            deletionObserved = deletionObserved || page.deletions.contains {+                $0.recordID == originalRecordID && $0.recordType == contract.occurrence.recordType+            }+            for change in page.modificationResultsByID.values {+                let record = try change.get().record+                if record.recordType == contract.removal.recordType,+                   matchesUUID(record[contract.removal.fields["id"]!], removalID, contract.uuidRepresentation) {+                    try assertFields(record, mapping: contract.removal, expected: removalExpected, contract: contract)+                    evidenceObserved = true+                }+            }+            if !page.moreComing && (!deletionObserved || !evidenceObserved) {+                try await Task.sleep(for: .seconds(1))+            }+        }+        var activeFetch = FetchDescriptor<TaskLinkOccurrence>(predicate: #Predicate { $0.id == edgeID })+        activeFetch.fetchLimit = 2+        try require(try context.fetch(activeFetch).isEmpty, "Run's local occurrence not deleted")+        var removalFetch = FetchDescriptor<TaskLinkRemovalEvidence>(predicate: #Predicate { $0.id == removalID })+        removalFetch.fetchLimit = 2+        let rows = try context.fetch(removalFetch)+        try require(rows.count == 1 && rows[0].id == removalID && rows[0].edgeId == edgeID,+                    "Local exact removal evidence missing")+        try require(rows[0].kindRawValue == "association" && rows[0].sourceTaskID == sourceID+                    && rows[0].targetTaskID == targetID && rows[0].createdAt == created+                    && rows[0].occurrenceRevision == revision && rows[0].removedAt == removed,+                    "Local removal scalar fields mismatch")+        let result: [String: Any] = ["edgeID": edgeID.uuidString, "removalID": removalID.uuidString,+                                    "recordName": originalRecordID.recordName, "zone": zone.zoneName,+                                    "platformDeletionObserved": deletionObserved,+                                    "evidenceExportObserved": evidenceObserved,+                                    "globalConvergenceClaim": false, "cloudKitAtomicityClaim": false]+        try JSONSerialization.data(withJSONObject: result, options: [.sortedKeys])+            .write(to: directory.appendingPathComponent("result.json"), options: .withoutOverwriting)+    }++    static func matchesUUID(_ value: CKRecordValue?, _ expected: UUID, _ representation: String) -> Bool {+        if representation == "uuid-string" { return (value as? String).flatMap(UUID.init(uuidString:)) == expected }+        var bytes = expected.uuid+        return value as? Data == withUnsafeBytes(of: &bytes) { Data($0) }+    }++    static func networkPolicy() -> CKOperation.Configuration {+        let configuration = CKOperation.Configuration()+        configuration.timeoutIntervalForRequest = 5+        configuration.timeoutIntervalForResource = 10+        return configuration+    }++    static func assertFields(_ record: CKRecord, mapping: Mapping, expected: [String: Any],+                             contract: Contract) throws {+        for (field, value) in expected {+            let saved = record[mapping.fields[field]!]+            if let uuid = value as? UUID {+                try require(matchesUUID(saved, uuid, contract.uuidRepresentation), "UUID field mismatch: \(field)")+            } else if let date = value as? Date {+                try require(saved as? Date == date, "Date field mismatch: \(field)")+            } else if let string = value as? String {+                try require(saved as? String == string, "String field mismatch: \(field)")+            } else { throw Failure.invalid("Unsupported field: \(field)") }+        }+    }+}
tests/typed-task-links/development-cloudkit/preflight.py Changed +103 / -0
diff --git a/tests/typed-task-links/development-cloudkit/preflight.py b/tests/typed-task-links/development-cloudkit/preflight.pynew file mode 100644index 00000000..badd1d11--- /dev/null+++ b/tests/typed-task-links/development-cloudkit/preflight.py@@ -0,0 +1,103 @@+"""Reserved development smoke preflight. Default validates only; --run launches.++Future task2-only invocation after operator setup and parent environment/slot clearance:+  python3 tests/typed-task-links/development-cloudkit/preflight.py \+    RESERVED_SMOKE.app REVIEWED_CONTRACT.json EXACT_REVIEWED_SHA256++Append --run only when external execution is cleared. Never uses Transit.app.+No compilation, signing changes, schema initialization or production promotion.+"""++import argparse+import hashlib+import json+import os+import pathlib+import plistlib+import subprocess+import uuid+++def require(condition, message):+    if not condition:+        raise RuntimeError(message)+++def main():+    parser = argparse.ArgumentParser(description=__doc__)+    parser.add_argument("app", type=pathlib.Path)+    parser.add_argument("contract", type=pathlib.Path)+    parser.add_argument("sha256")+    parser.add_argument("--run", action="store_true")+    args = parser.parse_args()+    app = args.app.resolve()+    raw = args.contract.read_bytes()+    require(hashlib.sha256(raw).hexdigest() == args.sha256, "Reviewed contract hash mismatch")+    contract = json.loads(raw)+    require(contract["reservedDevelopmentEnvironment"] is True, "Reserved development contract required")+    info = plistlib.loads((app / "Contents/Info.plist").read_bytes())+    identity = "me.nore.ig.Transit.development.cloudkit-smoke"+    require(info["CFBundleIdentifier"] == identity, "Dedicated smoke-host identity required")+    require(info["CFBundleExecutable"] == "TaskLinkDevelopmentSmoke", "Dedicated executable required")+    subprocess.run(["/usr/bin/codesign", "--verify", "--strict", str(app)], check=True)+    signature = subprocess.run(["/usr/bin/codesign", "-d", "--entitlements", ":-", str(app)],+                               capture_output=True, check=True)+    entitlements = plistlib.loads(signature.stdout)+    require(entitlements.get("com.apple.developer.icloud-container-environment") == "Development",+            "Production CloudKit environment forbidden")+    require(entitlements.get("com.apple.developer.icloud-container-identifiers") == [contract["containerID"]],+            "Exactly the reserved contract container required")+    require(entitlements.get("com.apple.developer.icloud-services") == ["CloudKit"], "Only CloudKit service allowed")+    require(entitlements.get("com.apple.security.get-task-allow") is True, "Development signing required")+    require(entitlements.get("com.apple.security.app-sandbox") is True, "Dedicated sandbox required")+    require(not any("aps-environment" in key or "application-groups" in key for key in entitlements),+            "Push/app-group entitlements forbidden")+    root = pathlib.Path.home() / "Library/Containers" / identity / "Data/tmp" / ("T1734Dev-" + str(uuid.uuid4()))+    require(not root.exists() and not root.is_symlink(), "Fresh synthetic root required")+    evidence = dict(host=str(app), contractSHA256=args.sha256, root=str(root),+                    cloudEnvironment="Development", container=contract["containerID"], launched=args.run)+    print(json.dumps(evidence, indent=2), flush=True)+    if args.run:+        environment = dict(os.environ, T1734_DEV_SMOKE_CLEARED="1")+        require(root.parent.is_dir() and root.parent.resolve() == root.parent,+                "Provisioned canonical smoke-host private tmp required")+        private_contract = root.parent / ("T1734Contract-" + str(uuid.uuid4()) + ".json")+        with private_contract.open("xb") as stream:+            stream.write(raw)  # Exact reviewed bytes, readable in the smoke sandbox.+        child = subprocess.Popen([str(app / "Contents/MacOS/TaskLinkDevelopmentSmoke"),+                                  str(private_contract), str(root)], env=environment)+        try:+            exit_code = child.wait(timeout=180)+        except subprocess.TimeoutExpired:+            sample_path = root.parent / ("T1734Timeout-" + str(uuid.uuid4()) + ".sample.txt")+            sample_evidence = dict(pid=child.pid, output=str(sample_path))+            try:+                sample = subprocess.run(["/usr/bin/sample", str(child.pid), "2", "10",+                                         "-file", str(sample_path)],+                                        capture_output=True, text=True, timeout=8, check=False)+                sample_evidence.update(exitCode=sample.returncode, stdout=sample.stdout, stderr=sample.stderr)+            except (OSError, subprocess.TimeoutExpired) as error:+                sample_evidence["error"] = str(error)+            try:+                with sample_path.with_suffix(".json").open("x") as stream:+                    stream.write(json.dumps(sample_evidence, indent=2) + "\n")+            except OSError as error:+                sample_evidence["evidenceWriteError"] = str(error)+            print(json.dumps(dict(timeoutSample=sample_evidence), indent=2), flush=True)+            # Only the exact child launched here; never another app or host.+            child.terminate()+            try:+                child.wait(timeout=10)+            except subprocess.TimeoutExpired:+                child.kill()+                child.wait(timeout=5)+            raise RuntimeError(f"Smoke deadline exceeded; owned PID {child.pid} terminated")+        inspection = subprocess.run(["/bin/ps", "-p", str(child.pid), "-o", "pid=,command="],+                                    capture_output=True, text=True)+        require(inspection.returncode == 1 and not inspection.stdout.strip() and not inspection.stderr.strip(),+                "Owned PID drain not proved; stop for parent inspection")+        require(exit_code == 0, f"Smoke failed with exit {exit_code}; retained fixture evidence")+++if __name__ == "__main__":+    main()
tests/typed-task-links/pending-schema-registration.patch Changed +98 / -0
diff --git a/tests/typed-task-links/pending-schema-registration.patch b/tests/typed-task-links/pending-schema-registration.patchnew file mode 100644index 00000000..d95a3f8b--- /dev/null+++ b/tests/typed-task-links/pending-schema-registration.patch@@ -0,0 +1,98 @@+--- a/Transit/Transit/TransitApp.swift++++ b/Transit/Transit/TransitApp.swift+@@ -50,7 +50,8 @@+         self.syncManager = syncManager+ +         let schema = Schema([+-            Project.self, TransitTask.self, Comment.self, Milestone.self, SyncHeartbeat.self, MCPWriteReceipt.self++            Project.self, TransitTask.self, Comment.self, Milestone.self, SyncHeartbeat.self, MCPWriteReceipt.self,++            TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self+         ])+         let config: ModelConfiguration+         if mode != .production {+--- a/Transit/TransitTests/TestModelContainer.swift++++ b/Transit/TransitTests/TestModelContainer.swift+@@ -20,7 +20,8 @@+ +     init() throws {+         let schema = Schema([+-            Project.self, TransitTask.self, Comment.self, Milestone.self, SyncHeartbeat.self, MCPWriteReceipt.self++            Project.self, TransitTask.self, Comment.self, Milestone.self, SyncHeartbeat.self, MCPWriteReceipt.self,++            TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self+         ])+         let config = ModelConfiguration(+             "TransitTests-\(UUID().uuidString)",+--- a/Transit/TransitTests/MCPWritePersistenceProbeTests.swift++++ b/Transit/TransitTests/MCPWritePersistenceProbeTests.swift+@@ -7,7 +7,8 @@+ struct MCPWritePersistenceProbeTests {+     private var schema: Schema {+         Schema([Project.self, TransitTask.self, Comment.self, Milestone.self,+-                SyncHeartbeat.self, MCPWriteReceipt.self])++                SyncHeartbeat.self, MCPWriteReceipt.self,++                TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self])+     }+ +     private func diskFixture(at url: URL, writable: Bool = true) throws -> TestModelContainer {+--- a/tests/mcp-write-probe/ServiceProbe.swift++++ b/tests/mcp-write-probe/ServiceProbe.swift+@@ -6,7 +6,8 @@+     // swiftlint:disable:next function_body_length+     @MainActor static func main() async throws {+         let schema = Schema([Project.self, TransitTask.self, Comment.self, Milestone.self,+-                             SyncHeartbeat.self, MCPWriteReceipt.self])++                             SyncHeartbeat.self, MCPWriteReceipt.self,++                             TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self])+         let config = ModelConfiguration("service-probe", schema: schema,+                                         isStoredInMemoryOnly: true, cloudKitDatabase: .none)+         let container = try ModelContainer(for: schema, configurations: config)+--- a/tests/mcp-write-probe/FoundationProbe.swift++++ b/tests/mcp-write-probe/FoundationProbe.swift+@@ -52,7 +52,8 @@+ +     @MainActor static func receiptStorage() throws {+         let schema = Schema([Project.self, TransitTask.self, Comment.self, Milestone.self,+-                             SyncHeartbeat.self, MCPWriteReceipt.self])++                             SyncHeartbeat.self, MCPWriteReceipt.self,++                             TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self])+         let configuration = ModelConfiguration("receipt-probe", schema: schema,+                                                isStoredInMemoryOnly: true, cloudKitDatabase: .none)+         let container = try ModelContainer(for: schema, configurations: configuration)+--- a/tests/mcp-write-probe/CoordinatorProbe.swift++++ b/tests/mcp-write-probe/CoordinatorProbe.swift+@@ -10,7 +10,8 @@+         defer { try? FileManager.default.removeItem(at: directory) }+         let schema = Schema([+             Project.self, TransitTask.self, Comment.self, Milestone.self,+-            SyncHeartbeat.self, MCPWriteReceipt.self++            SyncHeartbeat.self, MCPWriteReceipt.self,++            TaskLinkOccurrence.self, TaskLinkRemovalEvidence.self+         ])+         let configuration = ModelConfiguration(+             schema: schema, url: directory.appendingPathComponent("probe.store"),+--- a/tests/mcp-write-probe/Probe.swift++++ b/tests/mcp-write-probe/Probe.swift+@@ -13,7 +13,11 @@+         var models: [any PersistentModel.Type] = [+             Project.self, TransitTask.self, Comment.self, Milestone.self, SyncHeartbeat.self+         ]+-        if mode != "seed-old" { models.append(MCPWriteReceipt.self) }++        if mode != "seed-old" {++            models.append(MCPWriteReceipt.self)++            models.append(TaskLinkOccurrence.self)++            models.append(TaskLinkRemovalEvidence.self)++        }+         let schema = Schema(models)+         let configuration = ModelConfiguration(schema: schema, url: url,+                                                allowsSave: mode != "readonly", cloudKitDatabase: .none)+--- a/Makefile++++ b/Makefile+@@ -145,7 +145,7 @@+ # Nested macro sandboxing is unavailable in some already-sandboxed runners.+ # Set MCP_PROBE_SWIFT_FLAGS=-disable-sandbox there; the outer runner policy stays active.+ MCP_PROBE_SWIFT_FLAGS ?=+-MCP_PROBE_MODELS = Transit/Transit/Models/{Project,TransitTask,Comment,Milestone,SyncHeartbeat,DisplayID,TaskPriority,TaskStatus,TaskType,MilestoneStatus,MCPWriteReceipt}.swift++MCP_PROBE_MODELS = Transit/Transit/Models/{Project,TransitTask,Comment,Milestone,SyncHeartbeat,DisplayID,TaskPriority,TaskStatus,TaskType,MilestoneStatus,MCPWriteReceipt,TaskLinkOccurrence,TaskLinkRemovalEvidence}.swift+ + # These standalone executables never launch Transit. Runtime children use a+ # network-denying sandbox and synthetic stores confined to DerivedData/tmp.
tests/typed-task-links/prepare_capture_run.py Changed +49 / -0
diff --git a/tests/typed-task-links/prepare_capture_run.py b/tests/typed-task-links/prepare_capture_run.pynew file mode 100644index 00000000..be77d073--- /dev/null+++ b/tests/typed-task-links/prepare_capture_run.py@@ -0,0 +1,49 @@+"""Prepare only saved graph capture tests behind the shared signed unit-host guard; never launches."""++import json+import pathlib+import plistlib+import sys++from prepare_unit_run import require, validated_unit_run+++def main():+    require(len(sys.argv) == 3, "Build-products path and RED/GREEN run tag required")+    tag = sys.argv[2]+    require(tag in ("red", "green", "accounting"), "Exact RED/GREEN run tag required")+    products = pathlib.Path(sys.argv[1]).resolve()+    derived = products / f"T1734Capture-{tag}.xctestrun"+    result = products / f"T1734Capture-{tag}.xcresult"+    preflight = products / f"t1734-capture-{tag}-preflight.json"+    for output in (derived, result, preflight):+        require(not output.exists() and not output.is_symlink(), f"Fresh output required: {output}")+    configuration, unit, host, info, entitlements, source = validated_unit_run(products)+    suites = ["TaskLinkReadCaptureTests", "TaskLinkReadCaptureBoundaryTests", "TaskLinkPlanTests",+              "MCPReadCaptureBuilderTests", "MCPReadCaptureScopeTests", "MCPReadCoordinatorTests"]+    if tag == "accounting":+        suites = ["TaskLinkReadCaptureBoundaryTests"]+    unit["OnlyTestIdentifiers"] = suites+    environment = unit["EnvironmentVariables"]+    for flag in ("T1734_TRANSACTION_DIAGNOSTIC", "T1734_TRANSACTION_ABORT_DIAGNOSTIC",+                 "T1734_GRAPH_BOUNDARY_RED"):+        environment.pop(flag, None)+    environment.pop("T1734_OUTSIDE_WRITER_OBSERVATIONS", None)+    command = ["xcodebuild", "test-without-building", "-xctestrun", str(derived),+               "-destination", "platform=macOS,arch=arm64", "-parallel-testing-enabled", "NO",+               *[f"-only-testing:TransitTests/{suite}" for suite in suites],+               "-resultBundlePath", str(result)]+    evidence = dict(host=str(host), bundleID=info["CFBundleIdentifier"], entitlements=entitlements,+                    sourceXctestrun=str(source), suites=suites, expectedExpandedCases=7 if tag == "accounting" else 52,+                    expectedSkips=0, launched=False, outsideWriterExclusion=False,+                    primitiveDiagnosticsExcluded=True, derivedXctestrun=str(derived),+                    resultBundlePath=str(result), expectedCommand=command)+    with derived.open("xb") as stream:+        plistlib.dump(configuration, stream)+    with preflight.open("x") as stream:+        stream.write(json.dumps(evidence, indent=2) + "\n")+    print(json.dumps(evidence, indent=2))+++if __name__ == "__main__":+    main()
tests/typed-task-links/prepare_evidence_run.py Changed +46 / -0
diff --git a/tests/typed-task-links/prepare_evidence_run.py b/tests/typed-task-links/prepare_evidence_run.pynew file mode 100644index 00000000..25fe26ba--- /dev/null+++ b/tests/typed-task-links/prepare_evidence_run.py@@ -0,0 +1,46 @@+"""Prepare only bounded repair-evidence maintenance tests behind the shared signed unit-host guard; never launches."""++import json+import pathlib+import plistlib+import sys++from prepare_unit_run import require, validated_unit_run+++def main():+    require(len(sys.argv) == 3, "Build-products path and RED/GREEN run tag required")+    tag = sys.argv[2]+    require(tag in ("red", "green"), "Exact RED/GREEN run tag required")+    products = pathlib.Path(sys.argv[1]).resolve()+    derived = products / f"T1734Evidence-{tag}.xctestrun"+    result = products / f"T1734Evidence-{tag}.xcresult"+    preflight = products / f"t1734-evidence-{tag}-preflight.json"+    for output in (derived, result, preflight):+        require(not output.exists() and not output.is_symlink(), f"Fresh output required: {output}")+    configuration, unit, host, info, entitlements, source = validated_unit_run(products)+    suites = ["TaskLinkRemovalEvidenceTests"]+    unit["OnlyTestIdentifiers"] = suites+    environment = unit["EnvironmentVariables"]+    for flag in ("T1734_TRANSACTION_DIAGNOSTIC", "T1734_TRANSACTION_ABORT_DIAGNOSTIC",+                 "T1734_GRAPH_BOUNDARY_RED"):+        environment.pop(flag, None)+    environment.pop("T1734_OUTSIDE_WRITER_OBSERVATIONS", None)+    command = ["xcodebuild", "test-without-building", "-xctestrun", str(derived),+               "-destination", "platform=macOS,arch=arm64", "-parallel-testing-enabled", "NO",+               *[f"-only-testing:TransitTests/{suite}" for suite in suites],+               "-resultBundlePath", str(result)]+    evidence = dict(host=str(host), bundleID=info["CFBundleIdentifier"], entitlements=entitlements,+                    sourceXctestrun=str(source), suites=suites, expectedExpandedCases=7,+                    expectedSkips=0, launched=False, outsideWriterExclusion=False,+                    primitiveDiagnosticsExcluded=True, derivedXctestrun=str(derived),+                    resultBundlePath=str(result), expectedCommand=command)+    with derived.open("xb") as stream:+        plistlib.dump(configuration, stream)+    with preflight.open("x") as stream:+        stream.write(json.dumps(evidence, indent=2) + "\n")+    print(json.dumps(evidence, indent=2))+++if __name__ == "__main__":+    main()
tests/typed-task-links/prepare_foundation_run.py Changed +46 / -0
diff --git a/tests/typed-task-links/prepare_foundation_run.py b/tests/typed-task-links/prepare_foundation_run.pynew file mode 100644index 00000000..8bf7d675--- /dev/null+++ b/tests/typed-task-links/prepare_foundation_run.py@@ -0,0 +1,46 @@+"""Prepare only integrated disk foundation and compatibility tests behind the shared signed unit-host guard; never launches."""++import json+import pathlib+import plistlib+import sys++from prepare_unit_run import require, validated_unit_run+++def main():+    require(len(sys.argv) == 3, "Build-products path and RED/GREEN run tag required")+    tag = sys.argv[2]+    require(tag in ("red", "green"), "Exact RED/GREEN run tag required")+    products = pathlib.Path(sys.argv[1]).resolve()+    derived = products / f"T1734Foundation-{tag}.xctestrun"+    result = products / f"T1734Foundation-{tag}.xcresult"+    preflight = products / f"t1734-foundation-{tag}-preflight.json"+    for output in (derived, result, preflight):+        require(not output.exists() and not output.is_symlink(), f"Fresh output required: {output}")+    configuration, unit, host, info, entitlements, source = validated_unit_run(products)+    suites = ["TaskLinkFoundationIntegrationTests"]+    unit["OnlyTestIdentifiers"] = suites+    environment = unit["EnvironmentVariables"]+    for flag in ("T1734_TRANSACTION_DIAGNOSTIC", "T1734_TRANSACTION_ABORT_DIAGNOSTIC",+                 "T1734_GRAPH_BOUNDARY_RED"):+        environment.pop(flag, None)+    environment.pop("T1734_OUTSIDE_WRITER_OBSERVATIONS", None)+    command = ["xcodebuild", "test-without-building", "-xctestrun", str(derived),+               "-destination", "platform=macOS,arch=arm64", "-parallel-testing-enabled", "NO",+               *[f"-only-testing:TransitTests/{suite}" for suite in suites],+               "-resultBundlePath", str(result)]+    evidence = dict(host=str(host), bundleID=info["CFBundleIdentifier"], entitlements=entitlements,+                    sourceXctestrun=str(source), suites=suites, expectedExpandedCases=3,+                    expectedSkips=0, launched=False, outsideWriterExclusion=False,+                    primitiveDiagnosticsExcluded=True, derivedXctestrun=str(derived),+                    resultBundlePath=str(result), expectedCommand=command)+    with derived.open("xb") as stream:+        plistlib.dump(configuration, stream)+    with preflight.open("x") as stream:+        stream.write(json.dumps(evidence, indent=2) + "\n")+    print(json.dumps(evidence, indent=2))+++if __name__ == "__main__":+    main()
tests/typed-task-links/prepare_graph_run.py Changed +46 / -0
diff --git a/tests/typed-task-links/prepare_graph_run.py b/tests/typed-task-links/prepare_graph_run.pynew file mode 100644index 00000000..4a1a9ade--- /dev/null+++ b/tests/typed-task-links/prepare_graph_run.py@@ -0,0 +1,46 @@+"""Prepare only value graph tests behind the shared signed unit-host guard; never launches."""++import json+import pathlib+import plistlib+import sys++from prepare_unit_run import require, validated_unit_run+++def main():+    require(len(sys.argv) == 3, "Build-products path and RED/GREEN run tag required")+    tag = sys.argv[2]+    require(tag in ("red", "plan-red", "green", "green-repair"), "Exact RED/GREEN run tag required")+    products = pathlib.Path(sys.argv[1]).resolve()+    derived = products / f"T1734Graph-{tag}.xctestrun"+    result = products / f"T1734Graph-{tag}.xcresult"+    preflight = products / f"t1734-graph-{tag}-preflight.json"+    for output in (derived, result, preflight):+        require(not output.exists() and not output.is_symlink(), f"Fresh output required: {output}")+    configuration, unit, host, info, entitlements, source = validated_unit_run(products)+    suites = ["TaskLinkGraphTests", "TaskLinkGraphGeneratedTests", "TaskLinkPlanTests", "TaskLinkGraphServiceTests"]+    unit["OnlyTestIdentifiers"] = suites+    environment = unit["EnvironmentVariables"]+    for flag in ("T1734_TRANSACTION_DIAGNOSTIC", "T1734_TRANSACTION_ABORT_DIAGNOSTIC",+                 "T1734_GRAPH_BOUNDARY_RED"):+        environment.pop(flag, None)+    environment.pop("T1734_OUTSIDE_WRITER_OBSERVATIONS", None)+    command = ["xcodebuild", "test-without-building", "-xctestrun", str(derived),+               "-destination", "platform=macOS,arch=arm64", "-parallel-testing-enabled", "NO",+               *[f"-only-testing:TransitTests/{suite}" for suite in suites],+               "-resultBundlePath", str(result)]+    evidence = dict(host=str(host), bundleID=info["CFBundleIdentifier"], entitlements=entitlements,+                    sourceXctestrun=str(source), suites=suites, expectedExpandedCases=44,+                    expectedSkips=0, launched=False, outsideWriterExclusion=False,+                    primitiveDiagnosticsExcluded=True, derivedXctestrun=str(derived),+                    resultBundlePath=str(result), expectedCommand=command)+    with derived.open("xb") as stream:+        plistlib.dump(configuration, stream)+    with preflight.open("x") as stream:+        stream.write(json.dumps(evidence, indent=2) + "\n")+    print(json.dumps(evidence, indent=2))+++if __name__ == "__main__":+    main()
tests/typed-task-links/prepare_native_run.py Changed +46 / -0
diff --git a/tests/typed-task-links/prepare_native_run.py b/tests/typed-task-links/prepare_native_run.pynew file mode 100644index 00000000..d2f23a86--- /dev/null+++ b/tests/typed-task-links/prepare_native_run.py@@ -0,0 +1,46 @@+"""Prepare only saved native projection and navigation tests behind the shared signed unit-host guard; never launches."""++import json+import pathlib+import plistlib+import sys++from prepare_unit_run import require, validated_unit_run+++def main():+    require(len(sys.argv) == 3, "Build-products path and RED/GREEN run tag required")+    tag = sys.argv[2]+    require(tag in ("red", "green"), "Exact RED/GREEN run tag required")+    products = pathlib.Path(sys.argv[1]).resolve()+    derived = products / f"T1734Native-{tag}.xctestrun"+    result = products / f"T1734Native-{tag}.xcresult"+    preflight = products / f"t1734-native-{tag}-preflight.json"+    for output in (derived, result, preflight):+        require(not output.exists() and not output.is_symlink(), f"Fresh output required: {output}")+    configuration, unit, host, info, entitlements, source = validated_unit_run(products)+    suites = ["TaskLinkNativeProjectionTests"]+    unit["OnlyTestIdentifiers"] = suites+    environment = unit["EnvironmentVariables"]+    for flag in ("T1734_TRANSACTION_DIAGNOSTIC", "T1734_TRANSACTION_ABORT_DIAGNOSTIC",+                 "T1734_GRAPH_BOUNDARY_RED"):+        environment.pop(flag, None)+    environment.pop("T1734_OUTSIDE_WRITER_OBSERVATIONS", None)+    command = ["xcodebuild", "test-without-building", "-xctestrun", str(derived),+               "-destination", "platform=macOS,arch=arm64", "-parallel-testing-enabled", "NO",+               *[f"-only-testing:TransitTests/{suite}" for suite in suites],+               "-resultBundlePath", str(result)]+    evidence = dict(host=str(host), bundleID=info["CFBundleIdentifier"], entitlements=entitlements,+                    sourceXctestrun=str(source), suites=suites, expectedExpandedCases=8,+                    expectedSkips=0, launched=False, outsideWriterExclusion=False,+                    primitiveDiagnosticsExcluded=True, derivedXctestrun=str(derived),+                    resultBundlePath=str(result), expectedCommand=command)+    with derived.open("xb") as stream:+        plistlib.dump(configuration, stream)+    with preflight.open("x") as stream:+        stream.write(json.dumps(evidence, indent=2) + "\n")+    print(json.dumps(evidence, indent=2))+++if __name__ == "__main__":+    main()
tests/typed-task-links/prepare_participating_run.py Changed +63 / -0
diff --git a/tests/typed-task-links/prepare_participating_run.py b/tests/typed-task-links/prepare_participating_run.pynew file mode 100644index 00000000..e4a2ec6a--- /dev/null+++ b/tests/typed-task-links/prepare_participating_run.py@@ -0,0 +1,63 @@+"""Prepare the amended task3 cases from fresh signed shared Transit Debug products.++This never launches a host. After the parent assigns a bounded exclusive slot:+  python3 tests/typed-task-links/prepare_participating_run.py FRESH_BUILD_PRODUCTS+  xcodebuild test-without-building -xctestrun FRESH_BUILD_PRODUCTS/T1734Participating.xctestrun \+    -destination 'platform=macOS,arch=arm64' -parallel-testing-enabled NO \+    -only-testing:TransitTests/TaskLinkProtectedBoundaryTests \+    -only-testing:TransitTests/TaskLinkParticipatingBoundaryTests \+    -resultBundlePath FRESH_BUILD_PRODUCTS/T1734Participating.xcresult++Expected inventory: 15 expanded cases, zero skips, across two selected suites.+The existing-policy stale-source case is an actual-SUT RED expectation until+runtime proves otherwise. The two outside-writer cases observe allowed races,+not projection diagnostics. Primitive diagnostics are excluded from this job.+Use the parent's timeout/sample/owned-PID drain wrapper around xcodebuild.+The parent launcher also sanitizes inherited T1734 flags; this helper sets the+outside-writer flag only in the derived run file. Prepare once, then consume+that file: do not rerun preparation against its already reserved output paths.+"""++import json+import pathlib+import plistlib+import sys++from prepare_unit_run import require, validated_unit_run+++def main():+    require(len(sys.argv) == 2, "One fresh build-products path required")+    products = pathlib.Path(sys.argv[1]).resolve()+    derived = products / "T1734Participating.xctestrun"+    result = products / "T1734Participating.xcresult"+    preflight = products / "t1734-participating-preflight.json"+    for output in (derived, result, preflight):+        require(not output.exists() and not output.is_symlink(), f"Fresh output required: {output}")+    configuration, unit, host, info, entitlements, source = validated_unit_run(products)+    suites = ["TaskLinkProtectedBoundaryTests", "TaskLinkParticipatingBoundaryTests"]+    unit["OnlyTestIdentifiers"] = suites+    environment = unit["EnvironmentVariables"]+    for flag in ("T1734_TRANSACTION_DIAGNOSTIC", "T1734_TRANSACTION_ABORT_DIAGNOSTIC",+                 "T1734_GRAPH_BOUNDARY_RED"):+        environment.pop(flag, None)+    environment["T1734_OUTSIDE_WRITER_OBSERVATIONS"] = "1"+    command = ["xcodebuild", "test-without-building", "-xctestrun", str(derived),+               "-destination", "platform=macOS,arch=arm64", "-parallel-testing-enabled", "NO",+               "-only-testing:TransitTests/TaskLinkProtectedBoundaryTests",+               "-only-testing:TransitTests/TaskLinkParticipatingBoundaryTests",+               "-resultBundlePath", str(result)]+    evidence = dict(host=str(host), bundleID=info["CFBundleIdentifier"], entitlements=entitlements,+                    sourceXctestrun=str(source), suites=suites, expectedExpandedCases=15,+                    expectedSkips=0, launched=False, outsideWriterExclusion=False,+                    primitiveDiagnosticsExcluded=True, derivedXctestrun=str(derived),+                    resultBundlePath=str(result), expectedCommand=command)+    with derived.open("xb") as stream:+        plistlib.dump(configuration, stream)+    with preflight.open("x") as stream:+        stream.write(json.dumps(evidence, indent=2) + "\n")+    print(json.dumps(evidence, indent=2))+++if __name__ == "__main__":+    main()
tests/typed-task-links/prepare_query_run.py Changed +50 / -0
diff --git a/tests/typed-task-links/prepare_query_run.py b/tests/typed-task-links/prepare_query_run.pynew file mode 100644index 00000000..3697a697--- /dev/null+++ b/tests/typed-task-links/prepare_query_run.py@@ -0,0 +1,50 @@+"""Prepare only frozen task-link query tests behind the shared signed unit-host guard; never launches."""++import json+import pathlib+import plistlib+import sys++from prepare_unit_run import require, validated_unit_run+++def main():+    require(len(sys.argv) == 3, "Build-products path and RED/GREEN run tag required")+    tag = sys.argv[2]+    require(tag in ("red", "green", "green-boundary"), "Exact RED/GREEN run tag required")+    products = pathlib.Path(sys.argv[1]).resolve()+    derived = products / f"T1734LinkQuery-{tag}.xctestrun"+    result = products / f"T1734LinkQuery-{tag}.xcresult"+    preflight = products / f"t1734-link-query-{tag}-preflight.json"+    for output in (derived, result, preflight):+        require(not output.exists() and not output.is_symlink(), f"Fresh output required: {output}")+    configuration, unit, host, info, entitlements, source = validated_unit_run(products)+    suites = ["TaskLinkQueryTests"]+    expected = 16+    if tag == "green-boundary":+        suites += ["TaskLinkQueryBoundaryTests", "MCPTaskQueryRevisionTests", "MCPReadProjectionTests"]+        expected = 42+    unit["OnlyTestIdentifiers"] = suites+    environment = unit["EnvironmentVariables"]+    for flag in ("T1734_TRANSACTION_DIAGNOSTIC", "T1734_TRANSACTION_ABORT_DIAGNOSTIC",+                 "T1734_GRAPH_BOUNDARY_RED"):+        environment.pop(flag, None)+    environment.pop("T1734_OUTSIDE_WRITER_OBSERVATIONS", None)+    command = ["xcodebuild", "test-without-building", "-xctestrun", str(derived),+               "-destination", "platform=macOS,arch=arm64", "-parallel-testing-enabled", "NO",+               *[f"-only-testing:TransitTests/{suite}" for suite in suites],+               "-resultBundlePath", str(result)]+    evidence = dict(host=str(host), bundleID=info["CFBundleIdentifier"], entitlements=entitlements,+                    sourceXctestrun=str(source), suites=suites, expectedExpandedCases=expected,+                    expectedSkips=0, launched=False, outsideWriterExclusion=False,+                    primitiveDiagnosticsExcluded=True, derivedXctestrun=str(derived),+                    resultBundlePath=str(result), expectedCommand=command)+    with derived.open("xb") as stream:+        plistlib.dump(configuration, stream)+    with preflight.open("x") as stream:+        stream.write(json.dumps(evidence, indent=2) + "\n")+    print(json.dumps(evidence, indent=2))+++if __name__ == "__main__":+    main()
tests/typed-task-links/prepare_revision_compatibility_run.py Changed +48 / -0
diff --git a/tests/typed-task-links/prepare_revision_compatibility_run.py b/tests/typed-task-links/prepare_revision_compatibility_run.pynew file mode 100644index 00000000..1adb28bd--- /dev/null+++ b/tests/typed-task-links/prepare_revision_compatibility_run.py@@ -0,0 +1,48 @@+"""Prepare only changed revision/capture/batch/owned-scope compatibility suites behind the shared signed unit-host guard; never launches."""++import json+import pathlib+import plistlib+import sys++from prepare_unit_run import require, validated_unit_run+++def main():+    require(len(sys.argv) == 3, "Build-products path and RED/GREEN run tag required")+    tag = sys.argv[2]+    require(tag in ("red", "green"), "Exact RED/GREEN run tag required")+    products = pathlib.Path(sys.argv[1]).resolve()+    derived = products / f"T1734RevisionCompatibility-{tag}.xctestrun"+    result = products / f"T1734RevisionCompatibility-{tag}.xcresult"+    preflight = products / f"t1734-revision-compatibility-{tag}-preflight.json"+    for output in (derived, result, preflight):+        require(not output.exists() and not output.is_symlink(), f"Fresh output required: {output}")+    configuration, unit, host, info, entitlements, source = validated_unit_run(products)+    suites = ["TaskLinkProtectedBoundaryTests", "TaskLinkParticipatingBoundaryTests",+              "TaskLinkOwnedScopeTests", "TaskLinkReadCaptureBoundaryTests",+              "MCPRecordRevisionTests", "MCPTaskQueryRevisionTests", "MCPBatchTaskPreviewTests"]+    unit["OnlyTestIdentifiers"] = suites+    environment = unit["EnvironmentVariables"]+    for flag in ("T1734_TRANSACTION_DIAGNOSTIC", "T1734_TRANSACTION_ABORT_DIAGNOSTIC",+                 "T1734_GRAPH_BOUNDARY_RED"):+        environment.pop(flag, None)+    environment["T1734_OUTSIDE_WRITER_OBSERVATIONS"] = "1"+    command = ["xcodebuild", "test-without-building", "-xctestrun", str(derived),+               "-destination", "platform=macOS,arch=arm64", "-parallel-testing-enabled", "NO",+               *[f"-only-testing:TransitTests/{suite}" for suite in suites],+               "-resultBundlePath", str(result)]+    evidence = dict(host=str(host), bundleID=info["CFBundleIdentifier"], entitlements=entitlements,+                    sourceXctestrun=str(source), suites=suites, expectedExpandedCases=84,+                    expectedSkips=0, launched=False, outsideWriterExclusion=False,+                    primitiveDiagnosticsExcluded=True, derivedXctestrun=str(derived),+                    resultBundlePath=str(result), expectedCommand=command)+    with derived.open("xb") as stream:+        plistlib.dump(configuration, stream)+    with preflight.open("x") as stream:+        stream.write(json.dumps(evidence, indent=2) + "\n")+    print(json.dumps(evidence, indent=2))+++if __name__ == "__main__":+    main()
tests/typed-task-links/prepare_revision_run.py Changed +46 / -0
diff --git a/tests/typed-task-links/prepare_revision_run.py b/tests/typed-task-links/prepare_revision_run.pynew file mode 100644index 00000000..e114f223--- /dev/null+++ b/tests/typed-task-links/prepare_revision_run.py@@ -0,0 +1,46 @@+"""Prepare only current task revision tests behind the shared signed unit-host guard; never launches."""++import json+import pathlib+import plistlib+import sys++from prepare_unit_run import require, validated_unit_run+++def main():+    require(len(sys.argv) == 3, "Build-products path and RED/GREEN run tag required")+    tag = sys.argv[2]+    require(tag in ("red", "green"), "Exact RED/GREEN run tag required")+    products = pathlib.Path(sys.argv[1]).resolve()+    derived = products / f"T1734Revision-{tag}.xctestrun"+    result = products / f"T1734Revision-{tag}.xcresult"+    preflight = products / f"t1734-revision-{tag}-preflight.json"+    for output in (derived, result, preflight):+        require(not output.exists() and not output.is_symlink(), f"Fresh output required: {output}")+    configuration, unit, host, info, entitlements, source = validated_unit_run(products)+    suites = ["TaskLinkRevisionTests", "TaskLinkOwnedPhaseTests"]+    unit["OnlyTestIdentifiers"] = suites+    environment = unit["EnvironmentVariables"]+    for flag in ("T1734_TRANSACTION_DIAGNOSTIC", "T1734_TRANSACTION_ABORT_DIAGNOSTIC",+                 "T1734_GRAPH_BOUNDARY_RED"):+        environment.pop(flag, None)+    environment.pop("T1734_OUTSIDE_WRITER_OBSERVATIONS", None)+    command = ["xcodebuild", "test-without-building", "-xctestrun", str(derived),+               "-destination", "platform=macOS,arch=arm64", "-parallel-testing-enabled", "NO",+               *[f"-only-testing:TransitTests/{suite}" for suite in suites],+               "-resultBundlePath", str(result)]+    evidence = dict(host=str(host), bundleID=info["CFBundleIdentifier"], entitlements=entitlements,+                    sourceXctestrun=str(source), suites=suites, expectedExpandedCases=17,+                    expectedSkips=0, launched=False, outsideWriterExclusion=False,+                    primitiveDiagnosticsExcluded=True, derivedXctestrun=str(derived),+                    resultBundlePath=str(result), expectedCommand=command)+    with derived.open("xb") as stream:+        plistlib.dump(configuration, stream)+    with preflight.open("x") as stream:+        stream.write(json.dumps(evidence, indent=2) + "\n")+    print(json.dumps(evidence, indent=2))+++if __name__ == "__main__":+    main()
tests/typed-task-links/prepare_scope_run.py Changed +65 / -0
diff --git a/tests/typed-task-links/prepare_scope_run.py b/tests/typed-task-links/prepare_scope_run.pynew file mode 100644index 00000000..1212aa10--- /dev/null+++ b/tests/typed-task-links/prepare_scope_run.py@@ -0,0 +1,65 @@+"""Prepare the amended task3 cases from fresh signed shared Transit Debug products.++This never launches a host. After the parent assigns a bounded exclusive slot:+  python3 tests/typed-task-links/prepare_scope_run.py FRESH_BUILD_PRODUCTS+  xcodebuild test-without-building -xctestrun FRESH_BUILD_PRODUCTS/T1734Scope.xctestrun \+    -destination 'platform=macOS,arch=arm64' -parallel-testing-enabled NO \+    -only-testing:TransitTests/TaskLinkProtectedBoundaryTests \+    -only-testing:TransitTests/TaskLinkParticipatingBoundaryTests \+    -only-testing:TransitTests/TaskLinkOwnedScopeTests \+    -resultBundlePath FRESH_BUILD_PRODUCTS/T1734Scope.xcresult++Expected inventory: 30 expanded cases, zero skips, across three selected suites.+The existing-policy stale-source case is a baseline compatibility control that+already passed; this job adds owned-scope verification. Outside-writer cases observe allowed races,+not projection diagnostics. Primitive diagnostics are excluded from this job.+Use the parent's timeout/sample/owned-PID drain wrapper around xcodebuild.+The parent launcher also sanitizes inherited T1734 flags; this helper sets the+outside-writer flag only in the derived run file. Prepare once, then consume+that file: do not rerun preparation against its already reserved output paths.+"""++import json+import pathlib+import plistlib+import sys++from prepare_unit_run import require, validated_unit_run+++def main():+    require(len(sys.argv) == 2, "One fresh build-products path required")+    products = pathlib.Path(sys.argv[1]).resolve()+    derived = products / "T1734Scope.xctestrun"+    result = products / "T1734Scope.xcresult"+    preflight = products / "t1734-scope-preflight.json"+    for output in (derived, result, preflight):+        require(not output.exists() and not output.is_symlink(), f"Fresh output required: {output}")+    configuration, unit, host, info, entitlements, source = validated_unit_run(products)+    suites = ["TaskLinkProtectedBoundaryTests", "TaskLinkParticipatingBoundaryTests", "TaskLinkOwnedScopeTests"]+    unit["OnlyTestIdentifiers"] = suites+    environment = unit["EnvironmentVariables"]+    for flag in ("T1734_TRANSACTION_DIAGNOSTIC", "T1734_TRANSACTION_ABORT_DIAGNOSTIC",+                 "T1734_GRAPH_BOUNDARY_RED"):+        environment.pop(flag, None)+    environment["T1734_OUTSIDE_WRITER_OBSERVATIONS"] = "1"+    command = ["xcodebuild", "test-without-building", "-xctestrun", str(derived),+               "-destination", "platform=macOS,arch=arm64", "-parallel-testing-enabled", "NO",+               "-only-testing:TransitTests/TaskLinkProtectedBoundaryTests",+               "-only-testing:TransitTests/TaskLinkParticipatingBoundaryTests",+               "-only-testing:TransitTests/TaskLinkOwnedScopeTests",+               "-resultBundlePath", str(result)]+    evidence = dict(host=str(host), bundleID=info["CFBundleIdentifier"], entitlements=entitlements,+                    sourceXctestrun=str(source), suites=suites, expectedExpandedCases=30,+                    expectedSkips=0, launched=False, outsideWriterExclusion=False,+                    primitiveDiagnosticsExcluded=True, derivedXctestrun=str(derived),+                    resultBundlePath=str(result), expectedCommand=command)+    with derived.open("xb") as stream:+        plistlib.dump(configuration, stream)+    with preflight.open("x") as stream:+        stream.write(json.dumps(evidence, indent=2) + "\n")+    print(json.dumps(evidence, indent=2))+++if __name__ == "__main__":+    main()
tests/typed-task-links/prepare_unit_run.py Changed +116 / -0
diff --git a/tests/typed-task-links/prepare_unit_run.py b/tests/typed-task-links/prepare_unit_run.pynew file mode 100644index 00000000..fe13960e--- /dev/null+++ b/tests/typed-task-links/prepare_unit_run.py@@ -0,0 +1,116 @@+"""Prepare the focused migration run after parent handoff and exclusive slot release.++Run from the ticket checkout with a fresh DerivedData directory and locally+resolved packages. The shared Transit Debug scheme supplies the isolated host;+TransitDevelopment is not the unit-test scheme. This helper never launches it.++    xcodebuild build-for-testing -project Transit/Transit.xcodeproj \+      -scheme Transit -configuration Debug -destination 'platform=macOS,arch=arm64' \+      -parallel-testing-enabled NO -disableAutomaticPackageResolution \+      -derivedDataPath DerivedData/t1734-migration-red-run1+    python3 tests/typed-task-links/prepare_unit_run.py \+      DerivedData/t1734-migration-red-run1/Build/Products+    xcodebuild test-without-building \+      -xctestrun DerivedData/t1734-migration-red-run1/Build/Products/T1734Migration.xctestrun \+      -destination 'platform=macOS,arch=arm64' -parallel-testing-enabled NO \+      -only-testing:TransitTests/TaskLinkMigrationTests \+      -resultBundlePath DerivedData/t1734-migration-red-run1/Build/Products/T1734Migration.xcresult++Expected source inventory: two declarations, three parameter-expanded cases.+Missing-model assertions are prospective capability RED, not migration evidence.+Do not reuse a directory containing this helper's prior outputs or result bundle.+"""++import json+import pathlib+import plistlib+import subprocess+import sys+++def require(condition, message):+    """Fail closed even if Python is invoked with optimization enabled."""+    if not condition:+        raise RuntimeError(message)+++def validated_unit_run(products):+    """Revalidate signed host and return the existing unit-only migration selection."""+    host = products / "Debug/Transit.app"+    info = plistlib.loads((host / "Contents/Info.plist").read_bytes())+    require(info["CFBundleIdentifier"] == "me.nore.ig.Transit.development", "Unexpected host identity")+    require(info["CFBundleExecutable"] == "Transit", "Unexpected host executable")+    subprocess.run(["/usr/bin/codesign", "--verify", "--strict", str(host)], check=True)+    signature = subprocess.run(+        ["/usr/bin/codesign", "-d", "--entitlements", ":-", str(host)],+        capture_output=True, check=True,+    )+    entitlements = plistlib.loads(signature.stdout)+    require(not any("icloud" in key or "aps-environment" in key or "application-groups" in key+                    for key in entitlements), f"Unsafe entitlements: {entitlements}")+    require(entitlements.get("com.apple.security.get-task-allow") is True, "Development signing required")++    files = list(products.glob("Transit_*.xctestrun"))+    require(len(files) == 1, f"One shared Transit run file required: {files}")+    configuration = plistlib.loads(files[0].read_bytes())+    if "TestConfigurations" in configuration:+        targets = [target for item in configuration["TestConfigurations"] for target in item["TestTargets"]]+    else:+        targets = [value for key, value in configuration.items()+                   if not key.startswith("__") and isinstance(value, dict)]+    units = [target for target in targets if target.get("BlueprintName") == "TransitTests"]+    require(len(units) == 1, "Exactly one TransitTests unit target required")+    unit = units[0]+    require(unit.get("IsUITestBundle", False) is False, "UI test target forbidden")+    require(pathlib.Path(unit["TestHostPath"].replace("__TESTROOT__", str(products))).resolve() == host,+            "Unit target must use this exact development host")+    environment = unit.setdefault("EnvironmentVariables", {})+    require(environment.get("TRANSIT_PERSISTENCE_MODE") == "unit-test", "Unit-test persistence required")+    environment.update(TRANSIT_ISOLATION_SMOKE="1", TRANSIT_SMOKE_HOST_PATH=str(host))+    unit["OnlyTestIdentifiers"] = ["TaskLinkMigrationTests"]+    require(not unit.get("SkipTestIdentifiers"), "Unexpected skipped tests; review source run configuration")++    # Keep only the verified unit target; do not carry UI targets into the run.+    if "TestConfigurations" in configuration:+        selected = []+        for item in configuration["TestConfigurations"]:+            if any(target is unit for target in item["TestTargets"]):+                item["TestTargets"] = [unit]+                selected.append(item)+        configuration["TestConfigurations"] = selected+    else:+        configuration = {key: value for key, value in configuration.items()+                         if key.startswith("__") or value is unit}++    return configuration, unit, host, info, entitlements, files[0]+++def main():+    require(len(sys.argv) == 2, "Usage: prepare_unit_run.py BUILD_PRODUCTS")+    products = pathlib.Path(sys.argv[1]).resolve()+    derived = products / "T1734Migration.xctestrun"+    evidence_path = products / "t1734-migration-preflight.json"+    result = products / "T1734Migration.xcresult"+    for output in (derived, evidence_path, result):+        require(not output.exists(), f"Fresh output path required: {output}")++    configuration, unit, host, info, entitlements, source_file = validated_unit_run(products)+    environment = unit["EnvironmentVariables"]++    evidence = dict(+        bundleID=info["CFBundleIdentifier"], host=str(host), entitlements=entitlements,+        scheme="Transit", configuration="Debug", mode=environment["TRANSIT_PERSISTENCE_MODE"],+        startupGuard=dict(TRANSIT_ISOLATION_SMOKE=environment["TRANSIT_ISOLATION_SMOKE"],+                          TRANSIT_SMOKE_HOST_PATH=environment["TRANSIT_SMOKE_HOST_PATH"]),+        sourceXctestrun=str(source_file), derivedXctestrun=str(derived), resultBundle=str(result),+        suites=["TaskLinkMigrationTests"], expectedCases=3, parallel=False, launched=False,+    )+    with derived.open("xb") as stream:+        plistlib.dump(configuration, stream)+    with evidence_path.open("x") as stream:+        stream.write(json.dumps(evidence, indent=2) + "\n")+    print(json.dumps(evidence, indent=2))+++if __name__ == "__main__":+    main()
tests/typed-task-links/prepare_wire_run.py Changed +46 / -0
diff --git a/tests/typed-task-links/prepare_wire_run.py b/tests/typed-task-links/prepare_wire_run.pynew file mode 100644index 00000000..b4f309ca--- /dev/null+++ b/tests/typed-task-links/prepare_wire_run.py@@ -0,0 +1,46 @@+"""Prepare only standalone typed-link wire tests behind the shared signed unit-host guard; never launches."""++import json+import pathlib+import plistlib+import sys++from prepare_unit_run import require, validated_unit_run+++def main():+    require(len(sys.argv) == 3, "Build-products path and RED/GREEN run tag required")+    tag = sys.argv[2]+    require(tag in ("red", "green"), "Exact RED/GREEN run tag required")+    products = pathlib.Path(sys.argv[1]).resolve()+    derived = products / f"T1734Wire-{tag}.xctestrun"+    result = products / f"T1734Wire-{tag}.xcresult"+    preflight = products / f"t1734-wire-{tag}-preflight.json"+    for output in (derived, result, preflight):+        require(not output.exists() and not output.is_symlink(), f"Fresh output required: {output}")+    configuration, unit, host, info, entitlements, source = validated_unit_run(products)+    suites = ["TaskLinkWireTests"]+    unit["OnlyTestIdentifiers"] = suites+    environment = unit["EnvironmentVariables"]+    for flag in ("T1734_TRANSACTION_DIAGNOSTIC", "T1734_TRANSACTION_ABORT_DIAGNOSTIC",+                 "T1734_GRAPH_BOUNDARY_RED"):+        environment.pop(flag, None)+    environment.pop("T1734_OUTSIDE_WRITER_OBSERVATIONS", None)+    command = ["xcodebuild", "test-without-building", "-xctestrun", str(derived),+               "-destination", "platform=macOS,arch=arm64", "-parallel-testing-enabled", "NO",+               *[f"-only-testing:TransitTests/{suite}" for suite in suites],+               "-resultBundlePath", str(result)]+    evidence = dict(host=str(host), bundleID=info["CFBundleIdentifier"], entitlements=entitlements,+                    sourceXctestrun=str(source), suites=suites, expectedExpandedCases=28,+                    expectedSkips=0, launched=False, outsideWriterExclusion=False,+                    primitiveDiagnosticsExcluded=True, derivedXctestrun=str(derived),+                    resultBundlePath=str(result), expectedCommand=command)+    with derived.open("xb") as stream:+        plistlib.dump(configuration, stream)+    with preflight.open("x") as stream:+        stream.write(json.dumps(evidence, indent=2) + "\n")+    print(json.dumps(evidence, indent=2))+++if __name__ == "__main__":+    main()
tests/typed-task-links/prepare_writes_run.py Changed +50 / -0
diff --git a/tests/typed-task-links/prepare_writes_run.py b/tests/typed-task-links/prepare_writes_run.pynew file mode 100644index 00000000..4a8ddea3--- /dev/null+++ b/tests/typed-task-links/prepare_writes_run.py@@ -0,0 +1,50 @@+"""Prepare only protected standalone typed-link integration tests behind the shared signed unit-host guard; never launches."""++import json+import pathlib+import plistlib+import sys++from prepare_unit_run import require, validated_unit_run+++def main():+    require(len(sys.argv) == 3, "Build-products path and RED/GREEN run tag required")+    tag = sys.argv[2]+    require(tag in ("red", "green", "green-keyfix", "green-repair"), "Exact RED/GREEN run tag required")+    products = pathlib.Path(sys.argv[1]).resolve()+    derived = products / f"T1734Writes-{tag}.xctestrun"+    result = products / f"T1734Writes-{tag}.xcresult"+    preflight = products / f"t1734-writes-{tag}-preflight.json"+    for output in (derived, result, preflight):+        require(not output.exists() and not output.is_symlink(), f"Fresh output required: {output}")+    configuration, unit, host, info, entitlements, source = validated_unit_run(products)+    suites = ["TaskLinkWriteIntegrationTests"]+    expected = 15+    if tag == "green-repair":+        suites += ["TaskLinkWriteRepairTests", "TaskLinkWireTests"]+        expected = 49+    unit["OnlyTestIdentifiers"] = suites+    environment = unit["EnvironmentVariables"]+    for flag in ("T1734_TRANSACTION_DIAGNOSTIC", "T1734_TRANSACTION_ABORT_DIAGNOSTIC",+                 "T1734_GRAPH_BOUNDARY_RED"):+        environment.pop(flag, None)+    environment.pop("T1734_OUTSIDE_WRITER_OBSERVATIONS", None)+    command = ["xcodebuild", "test-without-building", "-xctestrun", str(derived),+               "-destination", "platform=macOS,arch=arm64", "-parallel-testing-enabled", "NO",+               *[f"-only-testing:TransitTests/{suite}" for suite in suites],+               "-resultBundlePath", str(result)]+    evidence = dict(host=str(host), bundleID=info["CFBundleIdentifier"], entitlements=entitlements,+                    sourceXctestrun=str(source), suites=suites, expectedExpandedCases=expected,+                    expectedSkips=0, launched=False, outsideWriterExclusion=False,+                    primitiveDiagnosticsExcluded=True, derivedXctestrun=str(derived),+                    resultBundlePath=str(result), expectedCommand=command)+    with derived.open("xb") as stream:+        plistlib.dump(configuration, stream)+    with preflight.open("x") as stream:+        stream.write(json.dumps(evidence, indent=2) + "\n")+    print(json.dumps(evidence, indent=2))+++if __name__ == "__main__":+    main()
tests/typed-task-links/run_closed_store.py Changed +137 / -0
diff --git a/tests/typed-task-links/run_closed_store.py b/tests/typed-task-links/run_closed_store.pynew file mode 100644index 00000000..c5603f07--- /dev/null+++ b/tests/typed-task-links/run_closed_store.py@@ -0,0 +1,137 @@+"""Prepare four isolated runs; launch ONLY with --run in the parent's heavy slot.++After a fresh shared Transit Debug build-for-testing (see prepare_unit_run.py):+  python3 tests/typed-task-links/run_closed_store.py BUILD_PRODUCTS++For execution, use another fresh build directory and append --run. This always+invokes the existing signed-host preflight first, never bypassing its checks.+Runs seed -> legacy reopen -> current-schema upgrade -> current-schema reopen.+No cleanup deletes stores. Original SQLite/WAL/SHM and JSON evidence remain in+the development app's private Data/tmp directory for inspection after drain.+"""++import argparse+import copy+import json+import pathlib+import plistlib+import sqlite3+import subprocess+import sys+import time+import uuid++from prepare_unit_run import require+++def drained(products, stage_pid=None):+    """Inspect only this build's host/test processes; never terminate anything."""+    deadline = time.monotonic() + 15+    while True:+        inspection = subprocess.run(["/bin/ps", "-axo", "pid=,command="],+                                    capture_output=True, text=True, check=True)+        roots = {str(products), str(products).removeprefix("/private")}+        paths = [root + suffix for root in roots for suffix in+                 ("/Debug/Transit.app/Contents/MacOS/Transit", "/Debug/TransitTests.xctest")]+        owned = [line for line in inspection.stdout.splitlines()+                 if any(path in line for path in paths)+                 or (stage_pid is not None and line.strip().split(maxsplit=1)[0] == str(stage_pid))]+        if not owned:+            return+        require(time.monotonic() < deadline, f"Owned processes not drained; parent inspection required: {owned}")+        time.sleep(0.25)+++def graph_rows(root):+    """Read-only physical counts, not graph projection or CloudKit evidence."""+    store = root / "pre-feature.store"+    with sqlite3.connect(store.as_uri() + "?mode=ro", uri=True) as connection:+        tables = {row[0] for row in connection.execute("SELECT name FROM sqlite_master WHERE type='table'")}+        counts = {}+        for entity in ("TaskLinkOccurrence", "TaskLinkRemovalEvidence"):+            matches = [name for name in tables if name.upper() == "Z" + entity.upper()]+            require(len(matches) == 1, f"Unrecognized SQLite schema for {entity}: {sorted(tables)}")+            name = matches[0]  # Allowlisted entity name above; no external SQL identifier.+            counts[entity] = connection.execute('SELECT COUNT(*) FROM "' + name + '"').fetchone()[0]+        require(all(count == 0 for count in counts.values()), f"Pre-feature graph rows are not empty: {counts}")+        return counts+++def main():+    parser = argparse.ArgumentParser(description=__doc__)+    parser.add_argument("products", type=pathlib.Path)+    parser.add_argument("--run", action="store_true", help="Explicitly launch after parent slot release")+    args = parser.parse_args()+    products = args.products.resolve()+    subprocess.run([sys.executable, str(pathlib.Path(__file__).with_name("prepare_unit_run.py")),+                    str(products)], check=True)+    base = plistlib.loads((products / "T1734Migration.xctestrun").read_bytes())+    token = str(uuid.uuid4()).upper()+    root = (pathlib.Path.home() / "Library/Containers/me.nore.ig.Transit.development/Data/tmp"+            / ("T1734Closed-" + token))+    require(not root.exists(), f"Fresh synthetic fixture root required: {root}")+    runs = []+    for stage in ("seed", "legacy", "upgrade", "reopen"):+        configuration = copy.deepcopy(base)+        if "TestConfigurations" in configuration:+            targets = [target for item in configuration["TestConfigurations"] for target in item["TestTargets"]]+        else:+            targets = [value for key, value in configuration.items()+                       if not key.startswith("__") and isinstance(value, dict)]+        require(len(targets) == 1 and targets[0]["BlueprintName"] == "TransitTests", "Unit-only base required")+        unit = targets[0]+        unit["OnlyTestIdentifiers"] = ["TaskLinkClosedStoreMigrationTests"]+        unit["EnvironmentVariables"].update(T1734_CLOSED_STAGE=stage, T1734_CLOSED_TOKEN=token)+        derived = products / ("T1734Closed-" + stage + ".xctestrun")+        result = products / ("T1734Closed-" + stage + ".xcresult")+        require(not result.exists(), f"Fresh result required: {result}")+        with derived.open("xb") as stream:+            plistlib.dump(configuration, stream)+        command = ["xcodebuild", "test-without-building", "-xctestrun", str(derived),+                   "-destination", "platform=macOS,arch=arm64", "-parallel-testing-enabled", "NO",+                   "-only-testing:TransitTests/TaskLinkClosedStoreMigrationTests",+                   "-resultBundlePath", str(result)]+        runs.append(dict(stage=stage, command=command, result=str(result)))+    plan = dict(token=token, root=str(root), runs=runs, expectedCasesPerStage=1,+                cloudKit="none", launched=args.run)+    with (products / "t1734-closed-plan.json").open("x") as stream:+        stream.write(json.dumps(plan, indent=2) + "\n")+    print(json.dumps(plan, indent=2), flush=True)+    if not args.run:+        return+    prior_pids = set()+    for run in runs:+        drained(products)+        outcome = subprocess.run(run["command"], timeout=150, check=False)+        drained(products)+        summary = subprocess.run(["xcrun", "xcresulttool", "get", "test-results", "summary",+                                  "--path", run["result"]], capture_output=True, text=True, check=True)+        counts = json.loads(summary.stdout)+        require(counts.get("totalTestCount") == 1 and counts.get("skippedTests") == 0+                and counts.get("passedTests", 0) + counts.get("failedTests", 0) == 1,+                f"Exactly one executed stage required; inspect result: {counts}")+        require((counts.get("passedTests") == 1 and counts.get("failedTests") == 0)+                if outcome.returncode == 0 else+                (counts.get("passedTests") == 0 and counts.get("failedTests") == 1),+                "Build exit and single-stage outcome disagree; inspect result")+        observation = root / (run["stage"] + ".json")+        require(observation.exists(), "No stage observation: inspect discovery/runtime failure, not capability RED")+        evidence = json.loads(observation.read_text())+        require(evidence["stage"] == run["stage"] and evidence["token"] == token+                and evidence["root"] == str(root), "Unexpected stage evidence")+        pid = evidence["pid"]+        require(type(pid) is int and pid > 0 and pid not in prior_pids, "Distinct stage host PID required")+        drained(products, stage_pid=pid)+        prior_pids.add(pid)+        with (products / ("t1734-closed-" + run["stage"] + "-drained.json")).open("x") as stream:+            stream.write(json.dumps(dict(observation=evidence, hostDrained=True,+                                         xcodebuildExit=outcome.returncode, testSummary=counts), indent=2) + "\n")+        require(outcome.returncode == 0, "Stage failed; inspect xcresult and missingLinkEntities; stop without cleanup")+        if run["stage"] in ("upgrade", "reopen"):+            counts = graph_rows(root)+            with (products / ("t1734-empty-graph-" + run["stage"] + ".json")).open("x") as stream:+                stream.write(json.dumps(counts, indent=2) + "\n")+++if __name__ == "__main__":+    main()
tests/typed-task-links/run_commit_diagnostic.py Changed +236 / -0
diff --git a/tests/typed-task-links/run_commit_diagnostic.py b/tests/typed-task-links/run_commit_diagnostic.pynew file mode 100644index 00000000..61fa8d1a--- /dev/null+++ b/tests/typed-task-links/run_commit_diagnostic.py@@ -0,0 +1,236 @@+"""Prepare exactly one opt-in primitive diagnostic; no launch without --run.++After the parent's guarded shared Transit Debug build and control run:+  python3 tests/typed-task-links/run_commit_diagnostic.py BUILD_PRODUCTS++Add --run in the assigned exclusive slot. Use fresh diagnostic outputs; a prior+preparation reserves them, so execution uses a fresh products copy/build.+The default single case documents a counterexample, never graph atomicity.+Use --diagnostic internal-save-abort for the internal-flush abort prerequisite;+its pass establishes abort durability only, not peer exclusion or atomicity.+"""++import argparse+import json+import os+import pathlib+import plistlib+import signal+import subprocess+import time++from prepare_unit_run import require, validated_unit_run+++IDENTIFIER = "TaskLinkCommitBoundaryTests/primitiveTransactionEarlierObservationCanBeInvalidatedByPeerSave()"+DIAGNOSTICS = {+    "read-first-peer": (IDENTIFIER, "T1734_TRANSACTION_DIAGNOSTIC"),+    "internal-save-abort": (+        "TaskLinkCommitBoundaryTests/primitiveTransactionInternalSaveMustRollBackOnClosureAbort()",+        "T1734_TRANSACTION_ABORT_DIAGNOSTIC"),+}+++def processes():+    result = subprocess.run(["/bin/ps", "-axww", "-o", "pid=,ppid=,command="],+                            capture_output=True, text=True, check=True, timeout=5)+    require(not result.stderr.strip(), "Process inspection diagnostic; stop without termination")+    rows = {}+    for line in result.stdout.splitlines():+        parts = line.strip().split(maxsplit=2)+        require(len(parts) == 3, "Incomplete process inspection; stop")+        rows[int(parts[0])] = (int(parts[1]), parts[2])+    require(os.getpid() in rows, "Process inspection unavailable; stop")+    return rows+++def host_processes(rows, executables, bundles):+    hosts = {}+    for pid, (_, command) in rows.items():+        if any(command == path or command.startswith(path + " ") for path in executables):+            hosts[pid] = command+        elif any(path in command for path in bundles):+            raise RuntimeError(f"Test-bundle process attribution unavailable, PID {pid}; retain for parent inspection")+    return hosts+++def stop_owned(pid, expected, products, reap=None):+    rows = processes()+    if pid not in rows:+        return+    require(rows[pid][1] == expected, f"PID {pid} identity changed; no signal sent")+    sample = products / ("T1734Diagnostic-timeout-" + str(pid) + ".sample.txt")+    require(not sample.exists(), "Fresh trace required")+    try:+        captured = subprocess.run(["/usr/bin/sample", str(pid), "2", "10", "-file", str(sample)],+                                  capture_output=True, text=True, timeout=8, check=False)+        evidence = dict(pid=pid, command=expected, exitCode=captured.returncode,+                        stdout=captured.stdout, stderr=captured.stderr)+    except (OSError, subprocess.TimeoutExpired) as error:+        evidence = dict(pid=pid, command=expected, error=str(error))+    try:+        with sample.with_suffix(".json").open("x") as stream:+            stream.write(json.dumps(evidence, indent=2) + "\n")+    except OSError as error:+        print(json.dumps(dict(sampleEvidence=evidence, evidenceWriteError=str(error))), flush=True)+    for action, seconds in ((signal.SIGTERM, 5), (signal.SIGKILL, 3)):+        rows = processes()+        if pid not in rows:+            return+        require(rows[pid][1] == expected, f"PID {pid} changed after sampling; no signal sent")+        os.kill(pid, action)+        deadline = time.monotonic() + seconds+        while time.monotonic() < deadline:+            if reap is not None:+                reap()+            if pid not in processes():+                return+            time.sleep(0.1)+    require(pid not in processes(), f"Owned PID {pid} not drained; parent inspection required")+++def stop_known_child(child, traces):+    """Popen proves child ownership even when host/process inspection fails."""+    if child.poll() is not None:+        return+    sample = traces / "inspection-failure-child.sample.txt"+    captured = dict(pid=child.pid, hostDrainProved=False)+    try:+        result = subprocess.run(["/usr/bin/sample", str(child.pid), "2", "10", "-file", str(sample)],+                                capture_output=True, text=True, timeout=8, check=False)+        captured.update(exitCode=result.returncode, stdout=result.stdout, stderr=result.stderr)+    except (OSError, subprocess.TimeoutExpired) as error:+        captured["error"] = str(error)+    try:+        with sample.with_suffix(".json").open("x") as stream:+            stream.write(json.dumps(captured, indent=2) + "\n")+    except OSError as error:+        print(json.dumps(dict(sampleEvidence=captured, evidenceWriteError=str(error))), flush=True)+    child.terminate()+    try:+        child.wait(timeout=5)+    except subprocess.TimeoutExpired:+        child.kill()+        child.wait(timeout=3)+++def main():+    parser = argparse.ArgumentParser(description=__doc__)+    parser.add_argument("products", type=pathlib.Path)+    parser.add_argument("--run", action="store_true")+    parser.add_argument("--diagnostic", choices=DIAGNOSTICS, default="read-first-peer")+    args = parser.parse_args()+    identifier, environment_flag = DIAGNOSTICS[args.diagnostic]+    original = args.products.absolute()+    products = args.products.resolve()+    derived = products / "T1734CommitDiagnostic.xctestrun"+    result = products / "T1734CommitDiagnostic.xcresult"+    evidence_path = products / "t1734-commit-diagnostic-preflight.json"+    log_path = products / "t1734-commit-diagnostic.log"+    result_json = products / "t1734-commit-diagnostic-result.json"+    summary_path = products / "t1734-commit-diagnostic-summary.json"+    tree_path = products / "t1734-commit-diagnostic-tests.json"+    traces = products / "T1734CommitDiagnostic-traces"+    for output in (derived, result, evidence_path, log_path, result_json, summary_path, tree_path, traces):+        require(not output.exists() and not output.is_symlink(), f"Fresh output required: {output}")+    configuration, unit, host, info, entitlements, source = validated_unit_run(products)+    unit["OnlyTestIdentifiers"] = [identifier]+    for _, flag in DIAGNOSTICS.values():+        unit["EnvironmentVariables"].pop(flag, None)+    unit["EnvironmentVariables"][environment_flag] = "1"+    roots = {str(original), str(products), str(products).removeprefix("/private")}+    executables = {root + "/Debug/Transit.app/Contents/MacOS/Transit" for root in roots}+    bundles = {root + "/Debug/TransitTests.xctest" for root in roots}+    require(not host_processes(processes(), executables, bundles), "Existing build host; no launch allowed")+    with derived.open("xb") as stream:+        plistlib.dump(configuration, stream)+    command = ["xcodebuild", "test-without-building", "-xctestrun", str(derived),+               "-destination", "platform=macOS,arch=arm64", "-parallel-testing-enabled", "NO",+               "-only-testing:TransitTests/" + identifier, "-resultBundlePath", str(result)]+    evidence = dict(host=str(host), bundleID=info["CFBundleIdentifier"], entitlements=entitlements,+                    sourceXctestrun=str(source), command=command, launched=args.run,+                    timeoutSeconds=60, expectedCases=1, diagnostic=args.diagnostic, atomicityProof=False)+    with evidence_path.open("x") as stream:+        stream.write(json.dumps(evidence, indent=2) + "\n")+    print(json.dumps(evidence, indent=2), flush=True)+    if not args.run:+        return+    traces.mkdir()+    with log_path.open("x") as log:+        child = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)+        try:+            owned = {}+            deadline = time.monotonic() + 60+            while child.poll() is None and time.monotonic() < deadline:+                owned.update(host_processes(processes(), executables, bundles))+                time.sleep(0.25)+            timed_out = child.poll() is None+            drain_deadline = time.monotonic() + 5+            while time.monotonic() < drain_deadline:+                live_hosts = host_processes(processes(), executables, bundles)+                owned.update(live_hosts)+                if not live_hosts and child.poll() is not None:+                    break+                time.sleep(0.1)+            live = processes()+            stalled = {pid: command_line for pid, command_line in owned.items() if pid in live}+            if timed_out or stalled:+                # Exact signed host paths, absent before launch and observed during+                # this run. Never kill another build, a process group or user app.+                for pid, command_line in stalled.items():+                    stop_owned(pid, command_line, traces)+                if child.poll() is None:+                    row = processes().get(child.pid)+                    require(row is not None and row[0] == os.getpid()+                            and pathlib.Path(row[1].split(maxsplit=1)[0]).name == "xcodebuild"+                            and str(derived) in row[1] and "-xctestrun" in row[1],+                            "Owned xcodebuild command unavailable; stop for parent inspection")+                    stop_owned(child.pid, row[1], traces, reap=child.poll)+                    child.wait(timeout=5)+                raise RuntimeError("Diagnostic timeout/teardown stall; traces retained, no atomicity proof")+            require(not host_processes(processes(), executables, bundles), "Host drain not established")+            require(not any(pid in processes() for pid in owned), "Recorded host PID drain not established")+            summary = subprocess.run(["xcrun", "xcresulttool", "get", "test-results", "summary", "--path", str(result)],+                                     capture_output=True, text=True, check=True, timeout=15)+            with summary_path.open("x") as stream:+                stream.write(summary.stdout)+            tree_result = subprocess.run(["xcrun", "xcresulttool", "get", "test-results", "tests",+                                          "--path", str(result)],+                                         capture_output=True, text=True, check=True, timeout=15)+            with tree_path.open("x") as stream:+                stream.write(tree_result.stdout)+            tree = json.loads(tree_result.stdout)+            nodes = list(tree["testNodes"])+            cases = []+            while nodes:+                node = nodes.pop()+                nodes.extend(node.get("children", []))+                if node.get("nodeType") == "Test Case":+                    cases.append(node)+            require(len(cases) == 1 and cases[0].get("nodeIdentifier") == identifier,+                    "Exact diagnostic case not executed; inspect retained tree")+            counts = json.loads(summary.stdout)+            require(counts.get("totalTestCount") == 1 and counts.get("skippedTests") == 0,+                    "Exactly one executed diagnostic required; inspect discovery/result failure")+            if (args.diagnostic == "internal-save-abort" and child.returncode == 65+                    and counts.get("failedTests") == 1 and counts.get("passedTests") == 0+                    and cases[0].get("result") == "Failed"):+                with result_json.open("x") as stream:+                    stream.write(json.dumps(dict(summary=counts, hostDrained=True, diagnostic=args.diagnostic,+                                                 abortDurabilityObserved=False, exactCaseFailed=True,+                                                 atomicityProof=False), indent=2) + "\n")+                raise RuntimeError("Abort prerequisite failed; inspect exact issues before candidate disposition")+            require(cases[0].get("result") == "Passed", "Diagnostic case not passed; inspect retained tree")+            require(child.returncode == 0 and counts.get("passedTests") == 1 and counts.get("failedTests") == 0,+                    "Diagnostic failed; inspect retained result, no atomicity proof")+            with result_json.open("x") as stream:+                stream.write(json.dumps(dict(summary=counts, hostDrained=True, diagnostic=args.diagnostic,+                                             counterexampleObserved=args.diagnostic == "read-first-peer",+                                             abortDurabilityObserved=args.diagnostic == "internal-save-abort",+                                             atomicityProof=False), indent=2) + "\n")+        finally:+            stop_known_child(child, traces)+++if __name__ == "__main__":+    main()

Docs (31)

CHANGELOG.md Changed +2 / -0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 870b540d..59e75889 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-1734: Add saved typed task relationships, guarded standalone link edits, precise removal-only repair, dependency/blocker and duplicate-chain diagnostics, frozen relationship queries and read-only native navigation. Link authoring is available through protected standalone MCP writes; native editing is outside this feature. Current task revisions cover active link incidence, including empty incidence; historical receipts retain their original bytes. Participating local writes save task/link/removal changes with their terminal receipt while preserving unsaved drafts. All 22 tasks and local platform checks pass; consolidation and live CloudKit verification remain separate work.+ - 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.
CLAUDE.md Changed +7 / -3
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8a8765a7..22179bb8 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -57,13 +57,15 @@ xcodebuild test -project Transit/Transit.xcodeproj -scheme Transit \  ### Data Model -Six SwiftData entities:+Eight SwiftData entities: - **Project** → has many **Tasks** and many **Milestones** - **TransitTask** → belongs to one Project, optionally belongs to one Milestone, has many Comments - **Milestone** → belongs to one Project, has many Tasks. Statuses: open / done / abandoned - **Comment** → belongs to one Task. Has `authorName`, `isAgent` flag, and `content` - **SyncHeartbeat** → singleton record whose `lastBeat` timestamp triggers CloudKit sync cycles - **MCPWriteReceipt** → same-store accepted/terminal write state and saved replay result, scoped to the originating local store even when synced+- **TaskLinkOccurrence** → immutable scalar UUID/kind/endpoints/time for each physical active relationship; no task relationships or delete cascades+- **TaskLinkRemovalEvidence** → separate immutable occurrence fingerprint and removal time, recognized for seven days; no automatic task consolidation  Both tasks and milestones have a UUID and a separate `permanentDisplayId` integer for human-facing use (T-1, M-3), allocated via CloudKit counter records with optimistic locking and provisional fallback when offline. @@ -107,6 +109,7 @@ All business logic lives in `Services/`, not in views: - **ContainerFactory** — creates ModelContainer with graceful fallback to in-memory on error - **ConnectivityMonitor** — NWPathMonitor wrapper, triggers display ID promotion for both tasks and milestones on connectivity restore - **QuickActionService** — home screen quick action handling+- **Task links** (`Services/TaskLinks/`) — saved value graph projection, direct blocker/duplicate assessments, proposed delta validation, exact repair evidence and bounded cleanup. Physical UUID collisions and dangling occurrences remain visible; task deletion does not silently cascade links. - **EditMerge** (`EditMerge.swift`, plus `TaskEditMerge`/`ProjectEditMerge`/`MilestoneEditMerge`) — three-way merge (load-time baseline vs. form vs. live model) used by the task, project, and milestone editors so a save writes only the fields the user changed and same-field conflicts are surfaced instead of silently resolved. The merge retains the original, edited, and live snapshots so conflict consent is scoped to the exact values the alert showed and is re-validated when the button is pressed. Each editor supplies a field enum, a snapshot (including per-field `replacing(_:withValueFrom:)`), an applier, and load-once draft state (a value-type form where appropriate).  ### Navigation@@ -148,6 +151,7 @@ Key implementation files: - `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/Links/` — typed relationship query options and saved graph result projection; protected standalone wire/owned-apply adapters live in `MCP/Writes/TaskLink*`. - `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`)@@ -208,11 +212,11 @@ Services follow a consistent pattern: mutate in memory, then `save()`, rolling b ## Test Infrastructure  - **Swift Testing** framework (not XCTest) for unit tests-- **TestModelContainer** fixture (`TransitTests/TestModelContainer.swift`) — creates an isolated in-memory container with `cloudKitDatabase: .none` and an explicit `Schema` including all five models. All three properties (schema, in-memory, no CloudKit) are required to avoid conflicts.+- **TestModelContainer** fixture (`TransitTests/TestModelContainer.swift`) — creates an isolated in-memory container with `cloudKitDatabase: .none` and an explicit `Schema` including all eight current entities (Project, TransitTask, Comment, Milestone, SyncHeartbeat, MCPWriteReceipt, TaskLinkOccurrence and TaskLinkRemovalEvidence). All three properties (schema, in-memory, no CloudKit) are required to avoid conflicts. - Each test constructs `let testContainer = try TestModelContainer()` and derives `testContainer.context`; helpers that create SwiftData storage should return or store the owning fixture rather than only a context/service - Custom-schema and multi-context tests use `TestModelContainer(schema:configurations:)`; direct `ModelContainer` construction and raw container/context factories in test sources are rejected by the ownership guard run from `make lint` - SwiftData test suites must use `@Suite(.serialized)` to prevent concurrent access issues-- UI tests use `TRANSIT_UI_TEST_SCENARIO` environment variable (`empty` or `board`) for deterministic seeded data+- UI tests use `TRANSIT_UI_TEST_SCENARIO` environment variable (`empty`, `board`, `duplicateDisplayIds`, `taskLinks` or `taskLinksAmbiguous`) for deterministic seeded data - MCP tool handler tests use `MCPTestHelpers.swift` for common setup patterns  ## Key Design Decisions
docs/mcp-result-contract.md Changed +3 / -1
diff --git a/docs/mcp-result-contract.md b/docs/mcp-result-contract.mdindex 4808b654..a2f0fd8e 100644--- a/docs/mcp-result-contract.md+++ b/docs/mcp-result-contract.md@@ -38,7 +38,9 @@ Parser inputs allow at most 32 nested object/array containers (root container co  [Protected writes](mcp-write-contract.md) replay stored T2380 result JSON, original error state, revisions, acceptance and retry information without rewriting receipts, rereading current entities or extending expiry. A new JSON-RPC request ID changes only response correlation. Cursor continuations similarly reuse frozen text, logical pages, revisions and capture metadata; wrappers cannot remint revisions or extend retention. -Task `r1` includes canonical comment content/membership even when `includeComments:false` omits bodies. Parent project/milestone display labels are associated data outside task revision coverage. Compare saved mutation-owned fields to a full read at the same covered revision, not to later live labels.+Current task `r1` covers canonical task fields, comment content/membership and every incoming/outgoing physical active link tuple, including repeated and malformed imported tuples. `linkContract:task-links-v1` explicitly covers empty incidence too; tokens from the pre-link contract therefore conflict on fresh task writes even when no links exist. `includeComments:false` and omitted link bodies do not remove that evidence from revision coverage. Current results advertise `revisionCoverage:task-fields-comments-links-v1` and `graphCoverage:available` when captured evidence exists. Historical results retain their original token and bytes; explicit legacy results with absent graph evidence report missing coverage, never an invented empty graph.++Opposite endpoint labels/status, duplicate resolution, blocker assessment and seven-day removal-evidence expiry are observations outside the task content token. Full relationship observations come from the same frozen saved capture; cursor replay does not refresh them. Parent project/milestone display labels are also associated data outside task revision coverage. Compare saved mutation-owned fields to a full read at the same covered revision, not to later live labels.  | Protected path | Existing normalization authority | | --- | --- |
docs/mcp-write-contract.md Changed +14 / -2
diff --git a/docs/mcp-write-contract.md b/docs/mcp-write-contract.mdindex 4477008b..717d290a 100644--- a/docs/mcp-write-contract.md+++ b/docs/mcp-write-contract.md@@ -55,12 +55,24 @@ key may be accepted as new work. Unresolved bindings never expire under this pol deduplication is not provided, even when CloudKit synchronizes receipt records.  Revisions match `r1:[0-9a-f]{64}` and compare exact locally observed entity content. Task revisions-cover its own stored fields, assignments and comment content/membership; parent project/milestone-renames do not invalidate the task. Milestone revisions exclude its task collection; project revisions+cover its own stored fields, assignments, comment content/membership and every physical active+incident link tuple under task-links-v1, including empty incidence. Opposite endpoint labels/status+and removal-evidence expiry do not invalidate that content token; parent project/milestone renames+also remain outside coverage. Historic retained tokens/results are never reminted. Milestone revisions exclude its task collection; project revisions exclude child collections. No-ops keep their revision; restoring identical covered content restores 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. +## Standalone typed task links++`create_task` accepts optional addition-only `linkChanges`; `update_task` accepts up to50 explicit add/remove directives and exact `endpointPreconditions`. Public types are `blocks`, `blocked-by`, `relates-to`, `introduced-by` and `duplicate-of`. Direction matters for dependencies, attribution and duplicates; associations are symmetric. UUID endpoints remain canonical identities; duplicate links do not redirect writes or consolidate records.++An addition supplies `action:add`, `type` and `targetTaskId`. A removal supplies `action:remove`, exact `edgeId` and its `l1` occurrence fingerprint, never a replacement relationship set. The source uses its current graph-covered `r1`; guards for uniquely affected existing opposite endpoints use their current `r1`. Exact no-ops require the source guard but no unnecessary opposite guard. An exact malformed/dangling occurrence may be removed as repair without absorbing unrelated corruption. Separate immutable removal evidence recognizes an identical fresh-key removal no-op for seven days; expired/unavailable evidence fails closed. Re-additions receive new occurrence identities. No-op retries preserve timestamps and original evidence.++Whole input shape is validated before key acceptance. Saved reference/precondition/cycle/selector failures are accepted domain outcomes after exact retained replay lookup. The final phase resolves fresh saved state and applies task fields, physical link changes, separate removal evidence and terminal receipt in one owned local-context save. Participating MCP operations cannot interleave that synchronous phase; independent containers or sync/import writers may race, and projections diagnose available conflicts. This provides no global CloudKit atomicity or all-writer fence. UI drafts are neither returned by saved reads nor included in owned writes. Retained replay remains byte-identical and performs no repair or save.++`mutate_tasks` rejects `linkChanges` and `endpointPreconditions` throughout its whole-shape preflight, before any item is accepted. Existing non-link items still use graph-covered revisions and the participating owned-save policy. There is no link editor, automatic duplicate merge, relationship closure operation or deletion shortcut.+ ## Application batch task mutations  `mutate_tasks` is one `tools/call`, not transport batching. Wire-level JSON-RPC arrays remain rejected.
specs/OVERVIEW.md Changed +30 / -0
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex 13afb2c1..0f6b5a72 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -36,6 +36,7 @@ | [MCP Project Creation](#mcp-project-creation) | 2026-10-02 | Ready for Review | Create projects through MCP with validation and reusable project metadata | | [Batch Task Queries](#batch-task-queries) | 2026-10-03 | Done | MCP task detail selection, batch lookup, and frozen cursor pagination | | [MCP Write Safety](#mcp-write-safety) | 2026-10-03 | Done | Add retry-safe MCP writes, local revision preconditions, and structured saved outcomes |+| [Typed Task Links](#typed-task-links) | 2026-10-03 | Done | Saved typed task relationships with guarded edits, graph-covered revisions and frozen queries | | [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 |@@ -357,6 +358,35 @@ All 18 coding tasks are implemented and review findings are resolved. Verificati - [implementation.md](mcp-write-safety/implementation.md)  +## Typed Task Links++Saved typed task relationships with guarded edits, graph-covered revisions and frozen queries. All 22 approved tasks and 39 local-scope acceptance criteria are complete. Final runs passed 3,265 macOS unit, 1,403 iOS unit and 26 iOS UI case executions; five macOS opt-in stages remain explicitly disabled. Four independent review roles found no outstanding mandatory fix. T-2402 live CloudKit verification and T-2381 consolidation remain separate work.++- [decision_log.md](typed-task-links/decision_log.md)+- [design-review.md](typed-task-links/design-review.md)+- [design.md](typed-task-links/design.md)+- [explanation.md](typed-task-links/explanation.md)+- [final-handoff.md](typed-task-links/final-handoff.md)+- [implementation.md](typed-task-links/implementation.md)+- [isolation-integration-plan.md](typed-task-links/isolation-integration-plan.md)+- [local-review.md](typed-task-links/local-review.md)+- [pr254-native-corrections.md](typed-task-links/pr254-native-corrections.md)+- [migration-next-tests.md](typed-task-links/migration-next-tests.md)+- [prerequisites.md](typed-task-links/prerequisites.md)+- [red-boundary-review.md](typed-task-links/red-boundary-review.md)+- [requirements-review.md](typed-task-links/requirements-review.md)+- [requirements.md](typed-task-links/requirements.md)+- [scope-assessment.md](typed-task-links/scope-assessment.md)+- [task14-checkpoint.md](typed-task-links/task14-checkpoint.md)+- [task20-checkpoint.md](typed-task-links/task20-checkpoint.md)+- [task4-checkpoint.md](typed-task-links/task4-checkpoint.md)+- [tasks-review.md](typed-task-links/tasks-review.md)+- [tasks.md](typed-task-links/tasks.md)+- [verification-readiness.md](typed-task-links/verification-readiness.md)+++PR #254 native corrections at bbe3a25 passed fresh 20-case focused and full platform verification; four independent delta reviewers found no mandatory issue. See [PR correction handoff](typed-task-links/pr254-native-corrections.md).+ ## Structured MCP Results  Immutable source/presentation results, supported-link availability and modern-only MCP2026-07-28 lifecycle, with unchanged protected replay and frozen read evidence.
specs/development-isolation/path-guard-correction.md Changed +13 / -0
diff --git a/specs/development-isolation/path-guard-correction.md b/specs/development-isolation/path-guard-correction.mdnew file mode 100644index 00000000..4d21cf70--- /dev/null+++ b/specs/development-isolation/path-guard-correction.md@@ -0,0 +1,13 @@+# Disposable store path correction++Prepared against T1734 a7afeb81a2a54f2d8aa30f67d86d248faf3c3de0 after its offline prerequisite failed at MigrationProbe.swift:14 before any host launch. The owner worktree is unchanged. Scope is Makefile and offline fixture code only; App/project and live data are untouched.++Actual Foundation reproduction using the same /tmp/t1734-independent.7vkeiE/offline/tmp hierarchy shows the existing root /private/tmp/... canonicalizing to /tmp/..., while the nonexistent sequential/synthetic.store leaf remains /private/tmp/.... Python pathlib.resolve had already produced /private/tmp paths. The old full-leaf/root string prefix comparison therefore falsely rejects a contained new store. Both observed strings and the directory-only corrected comparison are recorded locally in verification/isolation-path-foundation-check.json.++DisposableStorePath now requires the expected synthetic.store name and existing root/parent directories, canonicalizes both existing directories, compares complete path components, then appends the new leaf. Existing and dangling leaf symlinks are explicitly rejected; parent symlinks must resolve inside the allowed root. The guard still runs before any ModelContainer/configuration construction and throws a diagnostic error rather than silently bypassing containment. Runtime network/live-container sandbox rules and compiler sandbox are unchanged.++Added a path-guard-only mode to the existing migration executable. Its source assertions cover equivalent roots, new/existing leaves, sibling-prefix collision, wrong name, missing directory, dangling/existing leaf symlink and parent escape. All fixture files/symlinks live within the disposable outer root. The runner requires this mode to succeed before configuration/migration cases. No ModelContainer is constructed by this mode.++Lightweight verification: exact Foundation path behavior reproduced via JXA using Foundation NSURL without compiling or launching an app; corrected directory comparison succeeds on that input. Python source parses; make lint/static guards pass (407 Swift files, zero violations); diff whitespace check passes. Swift regression code, compilation and full harness execution are deliberately pending a parent-assigned slot. No build, migration probe, host, test suite, live app, endpoint or settings operation ran during correction preparation.++T1734 should consume this single correction commit atop a7afeb81, then request an exclusive offline slot and rerun make test-development-isolation with a fresh /tmp DerivedData root, preserving compiler/runtime sandboxes. Inspect the pathGuard result and all configuration/migration results before any host stage. A failed guard or zero executed regression assertions is not readiness. The future signed-host smoke/focused task1 prerequisites remain in effect. Other isolation consumers can apply the same small fixture-only correction when their parent chooses; do not weaken guards or reuse stale compiled binaries.
specs/development-isolation/t1734-source-handoff.md Changed +20 / -0
diff --git a/specs/development-isolation/t1734-source-handoff.md b/specs/development-isolation/t1734-source-handoff.mdnew file mode 100644index 00000000..1c51f8a8--- /dev/null+++ b/specs/development-isolation/t1734-source-handoff.md@@ -0,0 +1,20 @@+# T1734 independent feasibility isolation component++Prepared on exact owner checkpoint 594c54987146b39257f26b1d152999fb452e8f6b in a separate fix/t1734-development-isolation checkout. The active task-6/transit-t1734 worktree is unchanged. Parent asked for this source-only component for the approved independent task1 feasibility preparation; no task2 CloudKit setup or later graph implementation is included.++Recommended integration: consume this single isolation-only commit, preserving all owner changes. It applies established 9ba4297 isolation through the narrow original-base adaptation from f7cbb04. App/project/startup changes are owned by the isolation owner. App/Makefile/project/SyncManager/Settings inputs match 201205bd; code hunks applied cleanly with no whole-App/project replacement. Existing helpers moved into a same-file extension for the type-length bound. All MCP/read plumbing, models, TaskLinkMigrationTests and TestModelContainer remain unchanged. Actual existing handler/server constructors are preserved; no absent T63 APIs, graph models or schema registration are introduced.++Source checks: git apply --check and git diff --check pass; static development identity/entitlements/unit-mode/guarded-allocator/smoke-target preflight passes. Changed/new isolation Swift files pass strict lint (15 files, zero violations). Required full make lint ran but fails on three pre-existing violations in unchanged TaskLinkMigrationTests.swift: superfluous function_body_length disable at source lines 84 and 134 (reported against declarations 85/135), plus orphaned doc comment at 131. Owner should remove those unnecessary comments; this component does not edit the fixture. Full lint is not claimed green. No build, executable probe, host or test run occurred, and no previous runtime result is claimed for this branch.++After owner consumes this component and fixes its baseline lint issues, parent must grant an exclusive verification slot. Run branch-local offline isolation checks and the dedicated signed-host smoke first:++```sh+make test-development-isolation+make test-isolated-host-smoke SMOKE_DERIVED_DATA=DerivedData/t1734-isolation-smoke-fresh+```++TransitIsolationSmoke uses TransitDevelopment Debug/arm64 and explicit unit-test mode. Its runner verifies signed identity/entitlements and exact host/environment before launch; app preflight rejects unsafe mode/path/memory/CloudKit/group configuration before ContainerFactory. Counters are disabled without constructing CKContainer/default/privateCloudDatabase. Sidecars remain development tmp; automatic MCP and cloud bootstrap are suppressed.++Only after the parent's focused-run clearance, prepare a fresh shared Transit Debug test binary selecting TransitTests/TaskLinkMigrationTests, verify its signed development bundle and derived xctestrun environment/path, and run test-without-building serially. Set TRANSIT_ISOLATION_SMOKE=1 and TRANSIT_SMOKE_HOST_PATH to that verified Transit.app bundle to enforce the startup preflight. Require the intended two declarations/three expanded cases in xcresult: two missing-model capability cases may supply expected RED, plus synthetic disk saved-state control. Zero discovered cases is not evidence. The control is not closed-store migration or CloudKit compatibility.++Live/default data, installed/client activation, MCP enablement, development CloudKit/schema provisioning and production schema remain held. Later foundation/schema/model integration still requires the owner/parent's prerequisite resolution and narrow App-owned patch; this independent isolation component does not declare those foundations ready. Evidence stays local and no routine document delivery is requested.
specs/typed-task-links/decision_log.md Changed +137 / -0
diff --git a/specs/typed-task-links/decision_log.md b/specs/typed-task-links/decision_log.mdnew file mode 100644index 00000000..73daaf6a--- /dev/null+++ b/specs/typed-task-links/decision_log.md@@ -0,0 +1,137 @@+# Typed task links — decision log++Deferred destination: **T-2402 — Set up isolated CloudKit integration testing**, created and freshly verified by the parent through the installed UI (Transit, Idea/Research). No duplicate live ticket write.++Current concurrency contract: ADR 4 supersedes the independent-writer/import predicate-fence portions of the earlier feasibility decisions. Historical approvals and raw runtime evidence remain intact.++## Approved amendment — defer CloudKit test isolation++Authority: owner `Sentinel_42e647a603ac81918cbb949ed1ca67bb`, "The CloudKit test isolation can be a separate ticket. Proceed without it for now". Parent owns creating that ticket; no duplicate live write is authorized here.++Move reserved Development account/container/host setup and live additive schema/export/platform-deletion verification out of T-1734's task2 completion gate. Retain the optional uncompiled/unexecuted smoke source for the separate ticket. Verified local GREEN at aa5f56a (fresh build/preflight, four distinct drained closed-store stages, preserved fields/receipt bytes/physical multiplicity, empty new tables and three expanded metadata/control cases) can complete the remaining task2 boundary after review. This is a scoped deferral, not successful remote verification.++Keep all local imported-conflict tests, CloudKit-compatible model shape, foundation ownership/integration prerequisites and blocked-by edges. Complete task2 only under its amended local boundary, then proceed to task3 RED. Task4 now implements the owner-approved participating-write coordination, immediate saved validation and owned domain/receipt save boundary described in ADR 4; the independent-writer/import atomic fence is superseded. Account/schema/client activation and production promotion remain separately authorized actions.++## Quick Decisions++| Date | Decision | Authority / rationale |+| --- | --- | --- |+| 2026-10-03 | Corrected requirements approved; proceed design only. | Owner `Sentinel_36dc8dafea7c81919e7b060518fc9009`, corrected document commit `748f474517d420498ccd9e54cf79f777e7763f57`. Live duplicate investigation remains with owner; no ambiguous ticket mutation. |+| 2026-10-03 | Defer T-2381, keep T-2382 active, expand/spec T-1734 first. | Owner request `Sentinel_491f1fff691c819189b3f7535e2465c3` and typo clarification `Sentinel_4165673ac91c8191befe3f7d137a6d8c`, verified by parent. |+| 2026-10-03 | Scope, full-spec route, name `typed-task-links`, and vocabulary `blocks`/`blocked-by`, `relates-to`, `introduced-by`, `duplicate-of` approved. | Owner `Sentinel_2f1bde004c10819186e2b02bbc23023e`; permits requirements work, not unseen requirements/design/tasks or implementation. |+| 2026-10-03 | Live T-1734 description expansion committed with original text preserved, followed by approved Spec transition and comment. | Description key `t1734-scope-expansion-20261003-7ce9e596`; transition key `t1734-spec-scopeapproved-20261003-a8c43269`, committed at `2026-10-03T12:52:23.794Z`. |+| 2026-10-03 | Review locally through internal independent peers; no external source disclosure. | Local peer-review-validator permits internal fallback for unavailable external agents. `PERSONAL_PROJECTS=1`, but no callable Codex/Kiro external reviewer tool is exposed; quiet window also forbids review CLIs. Skill-required critic precedes two independent peer perspectives. |+| 2026-10-03 | No heavy validation during Asterism quiet measurement window. | Parent direction; spec-only reads, writes, reasoning and lightweight MCP calls permitted. Build/typecheck/lint/runtime checks deferred to later authorized implementation. |+| 2026-10-03 | All public relation spellings use kebab-case: blocks, blocked-by, relates-to, introduced-by, duplicate-of. | Owner correction `Sentinel_54fa08e7dbb881919d2c718f23bfb0fe`; parent selected consistent kebab-case. This supersedes the duplicate spelling in the scope approval summary; there is no alias/backward compatibility for this unimplemented feature and no requirements approval implied. Historical Transit comments remain unchanged. |++## Approved product decisions++Owner `Sentinel_36dc8dafea7c81919e7b060518fc9009` approved corrected requirements `748f474517d420498ccd9e54cf79f777e7763f57`. The following observable contracts govern design; implementation remains gated.++| Choice | Proposal and rationale |+| --- | --- |+| Blockers | Only effective Done satisfies a direct dependency; Abandoned remains blocking. This matches T-1734's “blockers are not done” wording without treating dropped work as delivered. Unknown/corrupt blocker state cannot certify unblocked work. |+| Cross-project | Explicit same-store UUID links allowed across projects; no task/milestone moves. Relationships need not share the projects of their endpoints. |+| Duplicate | One outgoing duplicate-of per source; chains resolve to the last task with no duplicate-of. No automatic flattening, status change, write redirection or content merge. |+| Surfaces | MCP mutation/query plus read-only native task-detail visibility; native editor/App Intent parity deferred. No workflow/harness edits. |+| Attribution | Multiple explicit task attribution sources allowed; introduced-by conveys attribution only, not regression classification. PR fallback/regression fields stay with T-1732. |+| Link edits | Explicit additive/removal delta, omitted delta leaves links unchanged. No whole-set replacement; task creation plus links or property update plus link delta commits as one local protected operation. |+| Preconditions | Existing source task expectedRevision plus current task revisions for other affected existing endpoints; incoming/inverse changes must not bypass their covered revision evidence. Commit validation covers graph invariants with the complete proposed result. Retargeting duplicate-of is explicit remove/add. |+| Incomplete synced graphs | Invalid edges retained/reported; requested explicit removal may repair them. No automatic deletion, invented target or global convergence claim. |+| Query compatibility | Ordinary task queries gain relationship filtering. T-2382 reusable queries retain approved project/status options; graph filters remain unsupported, and absent graph coverage is explicit. Existing five-minute/eight-view/16-MiB accounting applies. |+| Batch boundary | Link mutations initially use standalone create/update only; batch link directives reject as unsupported shape. This preserves T-2384's approved schemas and avoids incidental endpoint overlap/revision chaining. |+| Imported dependency cycles | Exclude cycle participants and candidates with invalid direct evidence, without recursively propagating ancestry faults through Done blockers. |+| Removal identity | A new re-add creates a new occurrence identity. Exact invalid-occurrence removal may repair incrementally; ambiguous source/repair identities or existing affected endpoint UUIDs fail closed as repair unavailable. A missing endpoint needs no invented revision. Removal evidence has bounded retention separate from active content revisions. |+| Revision transition | Retain r1 syntax with explicitly graph-covered current hashing, including empty active incidence. Old pre-feature tokens conflict on fresh writes; historical exact receipt replay remains first and unchanged. |++### ADR 1 — Proposed revision boundary for inverse relationship edits++Status: approved observable contract; storage design pending.++**Context.** A relation visible from two tasks changes both task-detail observations. Guarding only the request source would permit silently changing another endpoint's observed incident links and would leave its record revision inconsistent with its detail payload.++**Proposal.** Current task revisions cover normalized active incident occurrence identity/type/endpoints in addition to existing fields/comments. New mutations supply source expectedRevision and current endpoint task preconditions for every other existing task whose active incident membership changes. Target labels/status, removed-evidence retention and recursively resolved canonical paths remain separately identified observation evidence, not source revision-owned fields. Fresh reads/commits identify graph-covered evidence; pre-feature tokens cannot authorize fresh writes. Historical exact receipt replay remains independent and unchanged.++**Alternatives.** A separate graph/link-set token could avoid revising task tokens but adds another independently versioned optimistic concurrency surface. One-source-only coverage is smaller but cannot guard inverse changes safely.++**Consequence.** Design must prove a local all-or-none domain/link/result save and choose migration/coverage-identification details within the proposed r1 format and fresh-token transition, without rewriting historic receipt/page evidence. This is a proposed observable contract, not a selected storage architecture or guarantee about unimported CloudKit changes.++## Requirements review resolutions++The design critic and both independent internal peers agreed on four P1 gaps in the initial draft: exact invalid-edge selectors, fresh revision coverage transition, batch compatibility and graph validation at commit. The draft now states the observable resolutions above. They also agreed on direct blocker-invalidity rules, explicit incoming/outgoing query behavior, occurrence identity/no-op semantics and saved-view compatibility. The owner approved these observable resolutions with the corrected requirements; they do not select a persistent storage design.++## Design decisions++### ADR 2 — Platform deletion separate from bounded repair evidence++Status: approved at `56e9ad5` by owner `Sentinel_775be6f4fc6c8191a9d7ccf1d0c04557`; seven-day horizon selected.++**Context.** The owner challenged an arbitrary30-day retention proposal (`Sentinel_69d82973f3b4819185f45cfc084147ea`). Personal-tool use does not justify an enterprise audit window. A single active/retired row whose retirement evidence expires couples garbage collection to link state and risks treating late imports as revived links.++**Decision proposed.** Delete the exact active occurrence and save small removal evidence in the same existing store/terminal-result commitment. Leave CloudKit deletion/history management with SwiftData/Core Data. Expire only convenience evidence; it cannot create an active occurrence. Recommend seven days to match existing receipt retention, not as a sync-convergence guarantee.++**Alternatives.** Indefinite application tombstones violate bounded repair-history intent and add a custom distributed protocol. No removal evidence loses approved exact-removal/no-op recognition. Thirty days has no demonstrated need. A separate non-CloudKit store would break the same-store atomic save boundary.++**Consequences.** One additional small entity/schema integration; exact unknown selectors after expiry fail closed. Remote imported conflicts stay explicit. The application never purges framework sync history on this horizon. The owner approved the seven-day horizon and reviewed architecture at checkpoint `56e9ad5`; the earlier retention question itself was not approval.++### ADR 3 — Extend the merged coordinator's clean-context policy++Status: approved at `56e9ad5` by owner `Sentinel_775be6f4fc6c8191a9d7ccf1d0c04557`.++**Context.** Existing coordinator baseline saves can publish pending UI edits; T-2384 owns clean-context policy work. A standalone link operation changes multiple task observations and must not flush or roll back drafts.++**Decision proposed.** Generalize the merged policy for link-bearing standalone create/update, preserve receipt-first read-only inspection while dirty, check every post-await success/error path, and validate proposed graph/preconditions immediately before the sole domain/result save.++**Alternatives.** A second coordinator duplicates retry/receipt semantics. A separate graph store cannot commit task/edge/result together. MainActor alone does not serialize store imports; an unproved fence is not an atomicity claim.++**Consequences.** Wait for foundation handoff and verify disk-backed save/import boundaries first. If proof fails, graph writes stay unavailable and the design must be revised before implementation continues.++| Minor design choice | Rationale |+| --- | --- |+| Scalar endpoints; no uniqueness/cascades | CloudKit compatibility and preserved dangling identity evidence. |+| l1 occurrence fingerprint of immutable values | Exact removal selector without exposing physical store identifiers; same-UUID physical collisions remain unavailable. |+| No new PBT dependency | Seeded Swift Testing graph generators plus independent reference algorithms fit the existing project. |++## Design gate outcome++Owner `Sentinel_775be6f4fc6c8191a9d7ccf1d0c04557` approved reviewed checkpoint `56e9ad5`, including seven-day removal recognition and the early migration/atomic-save feasibility gate. This authorizes task planning only. Approval relayed by parent with the immediately preceding design/seven-day/feasibility-gate request. The separate testing approval does not authorize T-1734 implementation. Live Transit writes remain paused; bookkeeping stays local.++## Task and conditional implementation approval++Owner `Sentinel_d1ba9360969c81918777711b2420bfc7` approved task checkpoint `18a268f7604889de6328e224ddf45d516ea8654b`: “Tasks approved. You can continue implementation when the code is ready for it.” Parent relayed this against the task/conditional implementation request `Sentinel_20c841bb16e48191b679d21c6a049161`. No further readiness approval is required. Compatible merged foundations, explicit shared-file handoffs and feasibility gates remain technical prerequisites. T-2382 holds the exclusive heavy-test slot; request a concrete isolated test slot when source is ready. Live mutations, client activation and deployment remain held.++## RED/ GREEN boundary reconciliation after actual closed-store evidence++Parent directs reconciliation without a new user approval gate. Internal design-critic review confirms focused missing-entity RED and process-separated seed/legacy controls plus missing-model upgrade RED. Successful eight-entity migration, completed scalar metadata assertions, source parity GREEN and real development CloudKit evidence belong to task2's completion gate; requiring them before task1 RED completion would demand GREEN circularly. No approved DAG contradiction was found.++The critic identifies one real task1 source-completeness gap: its third bullet requires substantive opt-in development schema/platform-deletion fixture source. The existing local precheck is explicitly insufficient. Prepare the real typed source outside default runs, with compilation deferred until task2 declarations and execution deferred until separately cleared development host/account/schema prerequisites. Once that source exists and is reviewed, task1's RED completion may unblock task2 source work; no successful external execution or model registration is required to complete RED. Task2 retains every local/external feasibility gate before task3.++Seven schema-factory and compile-list inventory is proposed in tests/typed-task-links/schema-registration-inventory.md and its adjacent unapplied patch at `b168ef1e6cce6622cdbf0700de78e41ef03046ce`. No handoff is inferred, and no shared source is edited until parent agrees the exact split. This context exposes no callable cross-thread messaging tool; the parent must route the concrete inventory to T-63/containment and identify current probe/fixture ownership. Task2's new model definitions are already approved scope, not a new feature decision. No source disclosure to an external reviewer, heavy run, live mutation or schema publication occurs in this reconciliation.++Final critic review confirms the substantive smoke source closes task1's remaining source gap; timeout sampling before exact-child teardown is prepared in `cffece1b597e975038d3b8deb023e89345ad949f`. Rune now marks task1 RED complete and returns task2 next. `red-boundary-review.md` records the evidence and preserved task2 completion gates. Task2 source is pending the agreed exact shared-file split; no shared production source has changed. This is RED completion, not local migration GREEN or external environment verification.++## ADR 4 — Participating Transit writes with detected outside-writer conflicts++Status: guarantee choice approved by owner `Sentinel_c95239aefa6481919303c2353b8a9e9c`; amended requirements/design/tasks approved by owner `Sentinel_08cb318218788191a85da25d1206979f` at `a64e595c439db6d62e46c85888f37130d53269fa`.++**Context.** Source inspection found no supported full-predicate fence in the current SwiftData DefaultStore architecture. The read-first transaction counterexample passed at `27fa36e`; the separate internal-save/closure-abort prerequisite failed six expectations at `c8bbd127`, while eight imported-policy controls passed. These are localized evidence about the tested approaches, not universal impossibility. Preserving protection against all independent writers/imports would require a persistence-foundation design change.++**Decision.** Parent presented the strict persistence-redesign alternative and recommended coordinating Transit writes, validating before saving, and detecting/reporting conflicts from other writers or sync, explicitly saying a race can temporarily leave inconsistent links (`Sentinel_6b01a4425ad08191936c423d1d1b2ada`). Owner answered: “Let's go with the simpler option.” Participating writes are executions through the shared MCPWriteCoordinator (standalone and T-2384 per-item batches), with a synchronous MainActor validation/apply/stage/save phase and clean checks around preparation. Same-context MainActor native/UI work cannot interleave that phase; unsaved drafts remain guarded. Independent containers, external native/App Intent paths and platform imports are outside that coordination guarantee.++**Preserved guarantees.** Reject unsafe/ambiguous saved evidence observed before applying; require current source/affected endpoint revisions; preserve explicit removal-only repair, precise occurrence identity, read-only dirty replay and all receipt/key/recovery rules. Save the originating task/link/removal/terminal result together in the same store. Preserve bounded captures and truthful saved conflict diagnostics; no automatic repair, original rewriting or permanent deletion shortcut.++**Tradeoff.** An outside writer may change an endpoint or insert cycle/cardinality/identity/removal conflicts after validation but before the originating save. The save may still commit; inconsistent evidence may remain until explicit repair. Subsequent saved projections derive current assessments and identify available invalid evidence; valid endpoint status changes are not labeled historical race conflicts, without rewriting its immutable terminal receipt or claiming no effect. This local race is acknowledged separately from unimported remote changes. There is no all-independent-writer atomic validation/save guarantee, persistence-redesign enablement gate, post-commit compensating rollback or global CloudKit atomicity claim.++**Evidence/task treatment.** Preserve raw counterexample/abort fixtures and retained results; recast them as documented limits rather than required failing completion gates. Tasks3/4 retain their stable IDs and Red/Green order but test/implement participating coordination, saved validation and all-or-none owned commitment. Their existing downstream edges now refer to that local implementation boundary. Do not mark incomplete tests/implementation complete merely from the scope amendment. T-2402 remains deferred. No new product decision is outstanding; final amended-document approval is the local Starwave iteration gate.++### Amendment review synthesis++Design-critic review preceded two independent internal peer-validation perspectives (correctness and scope/maintainability). External Codex/Kiro review tools are unavailable in this environment; the documented peer-review-validator fallback was used, without external source disclosure. The critic requested exact participant wording, removal of residual proven-boundary labels, and differentiation of ordinary status assessments from provable race faults; those changes were applied. Both peers found the final package coherent with no core blocker or new product decision. Raw limit evidence is not reclassified as atomicity success. Retained outcomes preserve their original observed/owned meaning even when later saved readback has different revisions or assessments.++Rune parses 22 tasks, with two complete, one in progress and 19 pending; stable IDs, statuses, streams, requirement references and dependency edges remain intact. All 39 acceptance criteria are covered. Next implementation step after final amended-document review: task3 source-only participating-phase/fresh-saved-resolution controls and allowed-race fixture amendment, followed by task4 minimum shared-policy owned-save integration. Actual graph diagnostics follow tasks5/6 and21/22. Heavy execution still requires a separately assigned drained slot; T-2402 remains deferred.++The narrower guarantee choice is already approved. Local Starwave requirements/design/tasks skills require final approval of edited documents; this review asks whether those documents correctly express that choice, not whether to choose the same tradeoff again.++## Amended-document approval and implementation continuation++Owner `Sentinel_08cb318218788191a85da25d1206979f` replied “Approved” to parent `Sentinel_8a8182fee7d88191be122baaf7e97604`, which explicitly asked for final approval of the amended requirements/design/tasks after phone delivery. Approved checkpoint `a64e595c439db6d62e46c85888f37130d53269fa`. Parent authorizes continuing existing implementation at task3 boundary-test amendment then task4 under the participating-writer guarantee. No further document/readiness approval is pending; do not restore the independent-import predicate fence or T-2402 gate. T-2382 currently owns the full macOS verification slot, so source preparation only; report a concrete focused runtime job when ready. Shared source editing ownership and live-data holds remain unchanged.
specs/typed-task-links/design-review.md Changed +40 / -0
diff --git a/specs/typed-task-links/design-review.md b/specs/typed-task-links/design-review.mdnew file mode 100644index 00000000..f948aed5--- /dev/null+++ b/specs/typed-task-links/design-review.md@@ -0,0 +1,40 @@+# Typed links — design review and approval gate++Requirements approved at `748f474517d420498ccd9e54cf79f777e7763f57` by owner `Sentinel_36dc8dafea7c81919e7b060518fc9009`. Local approval record is `eedfc95`; initial design/self-validation is `35d47c8`. Design was approved by owner `Sentinel_775be6f4fc6c8191a9d7ccf1d0c04557` against reviewed checkpoint `56e9ad5`, including seven-day recognition and early feasibility gate.++## Review method and findings++Applied the actual starwave design, explain-like and design-critic workflows. The documented peer-review-validator internal fallback supplied two independent read-only perspectives because external reviewer tools were unavailable. No source disclosure, review CLI, test/build, live ticket call or implementation occurred.++| Reviewer | Material finding | Resolution |+| --- | --- | --- |+| Design critic | MainActor/history checks do not close validation-to-save races with peer contexts/imports. | Explicit early implementation enablement gate: demonstrate a supported mechanism before dependent graph-write work; failure keeps writes unavailable and returns design for review. No safety proof claimed. |+| Design critic | Repair expiry semantics could silently imply stable diagnostics. | Separate active deletion from bounded recognition. Expiry may end evidence-based conflict warnings/change derived assessments, never create/reactivate rows or change active content tokens. |+| Design critic | Projection omitted removal evidence/evaluation instant; removed-edge no-op lacked source incidence; same-relation remove/add unclear. | Frozen evidence/time inputs, retained incidence/fingerprint check, same-relation replacement rejected except different duplicate target retarget. |+| Design critic final | Saved-state semantic contradictions cannot be shape validation before replay. | Syntactic contradictions reject before acceptance; saved lookup-dependent conflicts validate as domain outcomes after retained replay. |+| Correctness peer | SCC and `unblocked:false` semantics need precision. | Structurally resolvable dependency rows enter SCC without hiding physical conflicts; assessments distinguish unblocked/blocked/invalid/unavailable. False selects certified blocked only. |+| Scope peer | Test trace must cover expiry/import arrival order and cleanup ambiguity. | Explicit verification includes changed diagnostics/stable active tokens/frozen views, both import orders, expiry/cleanup timing and deferred malformed/ambiguous cleanup. |++Critic confirmed its five gaps addressed for presentation with the validation classification refinement above. Both peers found no blocking contradiction or scope absorption. No material review disagreement remains. The early commit mechanism is an enablement blocker, not implemented or proven by these reviews.++## Retention choice++The owner challenged arbitrary30days (`Sentinel_69d82973f3b4819185f45cfc084147ea`); that question approves neither30 nor7. Recommend **seven days of optional exact-removal recognition**, matching existing write receipts as a convenience reference. Actual active occurrence deletion happens immediately in the protected local commit; SwiftData/Core Data owns deletion propagation/history. The app does not purge that history on the evidence horizon or invent a distributed tombstone protocol.++After evidence expires, an unknown old removal selector is unavailable. A conflict diagnostic whose sole basis was the evidence can expire, affecting derived assessments of an already imported active row; expiry cannot recreate a deleted row. A frozen retained view uses its original evidence/time. No horizon establishes remote convergence or remove-wins.++## Evidence and limits++Local source audit covers schema factories, task snapshot consumers, native destination resolution and foundation interfaces. Official Apple documentation supports additive production schemas, lack of CloudKit uniqueness/relationship atomicity, saved-fetch flags and platform persistent history/deletion. None proves migration against the user's store, atomic graph validation/save or remote deletion convergence. Early authorized implementation must verify disk migration and a supported commit mechanism before dependent feature work.++Implementation also waits for compatible merged T-63/T-2382/T-2383/T-2384 foundations, shared-file ownership transfer, a refreshed live schema and its own tasks/implementation approvals. All live Transit mutations are paused by the parent while the owner investigates duplicated records; no repair/status/comment/delete/guard reset is authorized.++## Exact next approval through the parent++**“Does the T-1734 typed-task-links design look good? Please choose the bounded removal-recognition horizon (recommended seven days) and explicitly approve the design, including the early migration/commit-boundary feasibility gate. Approval authorizes tasks planning only; graph writes cannot be enabled by MainActor/generation checks alone.”**++Do not create tasks until that approval. Phone transfer outcome is reported separately from document approval.++## Design gate outcome++Owner `Sentinel_775be6f4fc6c8191a9d7ccf1d0c04557` approved reviewed checkpoint `56e9ad5`, including seven-day removal recognition and the early migration/atomic-save feasibility gate. This authorizes task planning only. The approval question above is historical; next gate is task-plan approval through the parent.
specs/typed-task-links/design.md Changed +147 / -0
diff --git a/specs/typed-task-links/design.md b/specs/typed-task-links/design.mdnew file mode 100644index 00000000..f30ade9f--- /dev/null+++ b/specs/typed-task-links/design.md@@ -0,0 +1,147 @@+# Typed task links — design++Deferred destination: **T-2402 — Set up isolated CloudKit integration testing**, created and freshly verified by the parent through the installed UI (Transit, Idea/Research). No duplicate live ticket write.++Status: amended design approved by owner `Sentinel_08cb318218788191a85da25d1206979f` at `a64e595c439db6d62e46c85888f37130d53269fa`, adopting the simpler guarantee selected in `Sentinel_c95239aefa6481919303c2353b8a9e9c`. CloudKit test isolation/live Development verification remains deferred to T-2402; no live verification, schema promotion or client activation is claimed.++## Overview++Add saved task-link occurrences, a value-only graph projection and standalone protected link deltas. The graph joins task revisions, ordinary captured queries and read-only native details; T-2381 consolidation remains a separate feature.++## Architecture and integration++Place `TaskLinkOccurrence.swift` and `TaskLinkRemovalEvidence.swift` in `Models`, `TaskLinkService.swift` and `TaskLinkGraph.swift` in `Services`, and wire DTO/parser code in `MCP/Links`. Native `TaskLinksSection.swift` lives in `Views/TaskDetail`. Domain graph types are available on macOS/iOS; MCP-specific adapters remain macOS-only. SwiftData models stay on their owning actor; only immutable Sendable values cross task boundaries.++Implementation starts from a newly verified compatible merged base, after T-63, T-2382, T-2383 and T-2384 owner handoffs. Compare their final interfaces and refresh the running tool schema before coding. Approved foundation specs are inputs, not files this ticket edits. T-63 owns common reads/server/types until explicit transfer; T-2384 owns `MCPWriteCoordinator`; T-2383 owns the modern result adapter. T-1734 integrates through those interfaces after transfer.++| Pattern / audited call sites | Needs equivalent | Integration |+| --- | --- | --- |+| `TransitApp.init` schema; `TestModelContainer.init`; `tests/mcp-write-probe/{Probe,ServiceProbe,CoordinatorProbe,FoundationProbe}.swift` schemas | yes | Add occurrence/removal-evidence models in every schema that exercises task snapshots/writes; retain custom limited-schema tests only when deliberately graph-free. |+| `ContainerFactory.makeContainer` | no | Receives updated schema; fallback durability restrictions remain. |+| `MCPRecordSnapshot.task(_:in:)`, `task(_:fetchComments:)`; `MCPToolHandler+TaskQuery`; `MCPWriteCommand` create/update/status/comment snapshots; probe snapshot call sites | yes | Require graph incidence input; no overload may silently mint graph-covered revisions from missing evidence. Graph-free historic fixtures explicitly use legacy coverage. |+| T-63 `MCPReadCaptureBuilder`, `CapturedReadView`, `ReadTask`, persistent-history validation/fence | yes | Capture occurrence rows and endpoint closure inside the same saved fence, including active-link and removal-evidence history changes; freeze graph projection and coverage alongside task/comment revisions. |+| T-63 prepared read / `MCPPreparedToolRead` publication | no new engine | Graph filtering, traversal, encoding and retained bytes consume the existing deadline/physical permit and publication gate. |+| T-2382 portfolio summary and reusable snapshot query | yes, compatibility only | Keep selected scope/counts and project/status filters. Preserve current revisions when captured; missing graph coverage is explicit. Reject graph options without live enrichment. |+| `MCPWriteCommand.validate`, create/update prepare/apply; `MCPWriteCoordinator.execute` and all acceptance/recovery/post-await paths | yes | Parse deltas; generalize the merged clean-context policy for standalone graph writes. Preserve receipt-first behavior and one commit owner. |+| T-2384 batch parser/preview executor | yes, rejection only | Reject `linkChanges` and endpoint preconditions before any item/key acceptance. Preview uses current graph-covered task revisions but gains no graph mutation. |+| `TaskService.findByID`, UUID resolver paths | yes for graph/protected identity | Count complete UUID matches for all selected/affected tasks; never use first-match. Unrelated App Intent parity is excluded. |+| `TaskDetailView` iOS Form/macOS `LiquidGlassSection`; Dashboard sheet; `TaskDetailWindowView` UUID window | yes | Saved DTO section; revalidate unique destination before navigation and in window resolution. iOS pushes saved destination using existing detail view. |+| Task/milestone deletion, task sharing/export, App Intents, copying | no new capability | No cascading link deletion, new exports or mutation parity. Scalar references retain dangling evidence. |+| Tool definitions and T-2383 result encoder | yes | Add ordinary query/standalone input schemas and graph fields; preserve frozen result parity and historical receipt bytes. |++Audit baseline is source SHA `201205bd4e786c7f152d8f99006b37da7da888c7` plus the approved foundation worktree contracts. Repeat this table against the implementation base to include any new call sites.++## Persistent model and migration++`TaskLinkOccurrence` is an immutable active CloudKit-synced entity in the same store as tasks and receipts. Scalar fields have defaults: `id: UUID`, `kindRawValue: String`, `sourceTaskID: UUID`, `targetTaskID: UUID`, `createdAt: Date`. `TaskLinkRemovalEvidence` is a second entity in that same store with defaulted scalar fields: `id: UUID`, `edgeId: UUID`, the immutable occurrence values/`occurrenceRevision`, and `removedAt: Date`. No unique attributes, required relationships, task backreferences, delete cascades or new store. New instances always receive an explicit fresh UUID/time; defaults support schema compatibility, not semantic validity.++| Public input | Stored kind / orientation |+| --- | --- |+| A `blocks` B | `dependency`, A → B |+| A `blocked-by` B | `dependency`, B → A |+| A `relates-to` B | `association`, UUID lexical minimum → maximum |+| A `introduced-by` B | `attribution`, A → B |+| A `duplicate-of` B | `duplicate`, A → B |++Endpoints/type/id are immutable after insertion. Removal deletes the precisely identified active row and inserts removal evidence in the same protected local save; a re-add inserts a distinct occurrence. Active rows alone define incidence. Fetch all physical rows and retain their `LocalRecordKey` in captured values. Different UUIDs for equivalent active relations are conflicts, not automatic deduplication. Multiple physical rows with the same occurrence UUID make exact repair unavailable; do not expose an arbitrary row as actionable. An active row accompanied by matching removal evidence is explicitly conflicting imported evidence, not a valid relation or an automatically deleted row.++Repair-evidence retention is **seven days after removal**, matching the established write-receipt lifetime. This is a convenience horizon for recognizing exact removed occurrences and no-op retries, not a sync safety window, audit trail or undo history. Logically expired evidence cannot authorize repair/no-op; exclude it from projection regardless of cleanup timing. Expiry can end a conflict diagnostic whose only evidence was that removed-occurrence record, and can therefore change derived blocker/canonical assessments for an already present imported active row. It never inserts/reactivates that row or changes active incidence/content tokens, and never certifies remote correctness. A small maintenance hook deletes expired evidence only in an owned clean autosave-disabled context, never a read/preview or the UI context. Defer malformed dates/ambiguous evidence identity. Deleting evidence cannot reactivate a link because its active occurrence was already deleted at the protected commit. After expiry, unknown removal selectors are repair unavailable; original-key retries still follow independent receipt rules.++SwiftData/Core Data owns synchronization of actual occurrence deletion and its internal history/tombstones. T-1734 does not purge framework history, rebuild its CloudKit records or add an application tombstone protocol. [Apple describes deletion transactions and cautions that history must not be purged before consumers finish](https://developer.apple.com/documentation/coredata/consuming-relevant-store-changes). This supports using platform deletion, not a proof of remote convergence in this application's sync edge cases. Delayed/conflicting imports still receive diagnostics and do not imply global remove-wins; the repair-evidence horizon never controls framework deletion propagation.++Migration adds these two entities without rewriting `TransitTask`, comments or receipts. Existing tasks have empty incidence. Update all container schemas consistently. Validate an on-disk pre-feature store upgraded to the new schema before building dependent features; CloudKit development schema verification and production promotion are separate authorized release steps, never application-launch side effects in this spec. [Apple's sync guidance](https://developer.apple.com/documentation/swiftdata/syncing-model-data-across-a-persons-devices) establishes additive production schemas, optional relationships and lack of unique enforcement; it does not prove this migration against the user's store.++## Graph projection and algorithms++`TaskLinkGraph.project(tasks:occurrences:removalEvidence:evaluationInstant:budget:) throws -> TaskLinkGraphView` consumes captured values indexed by UUID **to all physical matches**. A unique UUID resolves; zero/multiple matches produce separate missing/ambiguous diagnostics. Index incidence by both scalar endpoints. Normalize input orientation before equivalent-relation lookup; preserve raw malformed imported rows as diagnostics. Use one frozen evaluation instant for expiry across MCP/native projections. Malformed, missing required fields or ambiguous removal-evidence identities produce diagnostics and cannot authorize a no-op; no actionable occurrence is invented. Sorting is deterministic by kind, source UUID, target UUID, occurrence UUID and physical key for diagnostics.++Compute dependency strongly connected components once in O(V+E) using every recognized dependency occurrence with structurally valid, uniquely resolved endpoints. Preserve repeated/equivalent physical occurrences and their diagnostics; never remove cycle evidence by deduplicating them. Unresolvable dependency endpoints stay invalid direct evidence outside SCC membership. Cycle members fail unblocked selection. For a candidate outside a cycle, inspect direct blocker evidence only: every incoming dependency must be unique, valid and resolve to raw/effective Done; unknown raw status fails. Do not follow duplicate aliases or recursively propagate a Done blocker's ancestry errors. An unresolved candidate dependency or multiple equivalent occurrences makes its blocker assessment unavailable/blocked, not unblocked. Association/attribution/duplicate edges never block. `blockerAssessment` is `unblocked` for complete valid Done/no-blocker evidence, `blocked` for complete valid direct evidence containing a known non-Done blocker, or `invalid` for cycle/identity/occurrence/unknown-status faults. Acquisition failure is a failed read, not an assessment. Missing retained graph coverage is `unavailable`.++Duplicate resolution walks the unique outgoing chain from the selected task, retaining an ordered UUID path and visited set. Zero outgoing means that task is canonical; one valid edge continues; missing/ambiguous endpoint, conflicting occurrence, multiple outgoing edges or repeated identity produces no canonical result and a typed diagnostic. Done/Abandoned status does not stop the walk. No path flattening or write redirect occurs.++`TaskLinkPlan.validate(delta:source:preconditions:savedGraph:)` evaluates the complete proposed result. Additions touching an invalid affected graph cannot certify cardinality/cycle safety and reject. Removing exact occurrences with no additions is the repair path: require unambiguous existing affected endpoints and exact row evidence, but allow incremental reduction without demanding unrelated corruption be repaired. Duplicate retarget is removal plus addition validated on the resulting graph; mixed field updates remain in the same local commit and do not weaken graph guards.++Every loop checks the supplied operation deadline; graph size/bytes are charged to the existing capture budget. Use iterative traversal rather than recursion. Stop on repeated identity and fail the whole requested read if the required closure cannot be captured within budget. Do not introduce an unbounded independent fetch/traversal engine.++## Wire contracts and protected writes++Use public type strings exactly `blocks`, `blocked-by`, `relates-to`, `introduced-by`, `duplicate-of`; there are no alternate spellings. Existing camelCase schema field conventions remain.++```text+linkChanges: [+  { action: "add", type: <public type>, targetTaskId: <UUID> },+  { action: "remove", edgeId: <UUID>, occurrenceRevision: <opaque token> }+]+endpointPreconditions: [{ taskId: <UUID>, expectedRevision: <r1 token> }]+```++Maximum 50 total directives. A remove and add of the same normalized logical relation in one request is rejected, including an already-present add combined with removing its occurrence; use separate protected requests for re-add. Removing one duplicate target and adding a different target is the approved retarget exception. Create permits additions only; update requires source `expectedRevision`, even for a no-op. Endpoint preconditions have unique task IDs and no source duplicate. Require precisely the other existing endpoints whose active incident membership changes; extra or contradictory guards reject. Already-present additions require source revision but do not change membership of the opposite task. Shape validation rejects unknown fields/actions/type spelling, malformed UUID/token, oversize arrays and syntactically detectable contradictions before key acceptance. Conflicts that require mapping a saved edge selector to semantic endpoints are domain validation after retained replay/key acceptance, together with reference, cardinality and cycle validation. Omitted `linkChanges` leaves links unchanged.++An `occurrenceRevision` is `l1:<SHA256>` over canonical id/kind/source/target/creation values, excluding removal-evidence timestamps. It is issued only for a uniquely identified physical occurrence. Removal requires the row be incident to the source and the selector match immutable values; same occurrence UUID collisions are never resolved by the token. Matching unexpired removal evidence whose original occurrence was incident to the selected source and whose fingerprint matches yields the protected no-op without a new timestamp/removal record. Missing identity after retention or token mismatch yields repair unavailable/conflict; it does not remove by endpoints or semantic equivalence.++Use merged T-2384 coordinator policy as `MCPWriteExecutionPolicy` with clean-context guard and synchronous pre-apply validation, rather than a second coordinator. Its batch caller behavior remains intact. For graph directives, order is:++1. Validate shape, tool enablement, durable store and exact tool/store key binding. Inspect retained exact outcome before current task/link lookups, graph validation or fresh revisions. Dirty-context replay uses read-only durable receipt/sidecar inspection; never recover/repair/save during it.+2. For a new accepted operation require a clean shared context before any baseline/acceptance save. Refuse without domain effects if not clean. Acceptance receipt/sidecar rules remain T-2380's.+3. Perform existing asynchronous preparation/display-ID allocation. Check clean-context policy on **success and failure after every await**, before any save or rollback. Dirty state after acceptance reports uncertain/reconcile as the foundation defines and preserves UI edits.+4. Capture saved task/comment/occurrence evidence in a fresh autosave-disabled context, validate unique source/affected endpoint identities, compare graph-covered revisions and build the full plan. Immediately before apply, in one synchronous MainActor phase, re-fetch/refault authoritative affected rows and graph from saved evidence, validate current saved revisions and complete proposed invariants, then apply and stage/save without awaits. A changed or unavailable validation observation rejects/conflicts before domain effects. Independent writers or imports may still commit after this validation; subsequent saved projections report inconsistent evidence.+5. Insert/update task fields, delete/insert precisely attributable occurrences and insert removal evidence and terminal receipt, encode the terminal result, and save them once in the same local store. No endpoint task timestamp is bumped merely for an incident link; its covered token changes from incidence. On pre-save failure, rollback only coordinator-owned changes from a proven clean entry. On uncertain durability retain original-key reconciliation, never fabricate no-effect.++Participating writes are standalone and per-item batch executions routed through the shared `MCPWriteCoordinator` on its MainActor. Their synchronous validation/apply/encoding/domain-save phase has no await; asynchronous preparation remains outside it and every post-await path checks for dirty context. Native/UI work using the same shared MainActor context cannot interleave that phase, and unsaved drafts remain protected by the clean-context rules. Independent containers, App Intent/native paths outside this context, and platform sync/import writers are outside this coordination guarantee. Do not infer their participation from being part of Transit; no all-writer lock or new persistence owner is introduced.++The originating local save commits its task fields, attributable edge/removal evidence and terminal receipt together. Immediate saved validation provides an observation, not an atomic predicate fence against outside writers. Such a writer can invalidate an endpoint, insert a cycle/duplicate target or change exact repair evidence before this save, temporarily leaving inconsistent links that can remain until explicit repair. Valid endpoint status changes update blocker/canonical assessments; historical race attribution is not inferred. Graph projection preserves and reports available invalid evidence on subsequent saved reads under requirements 2.3/3.4/5.3–5.5; notification refresh uses existing saved/import invalidation, while retained captures keep their original evidence. No post-commit rollback, automatic repair or downgrade of a retained committed receipt occurs. Retained exact outcomes continue to replay after later conflicts/deletion. See ADR 4 for the guarantee boundary.++## Task revisions and output++Extend the one task snapshot builder with required incidence evidence and `revisionCoverage: "task-fields-comments-links-v1"`. Canonical covered fields add `linkContract: "task-links-v1"` and a sorted `incidentLinks` array, including `[]`; each active physical occurrence contributes id/kind/source/target. Do not normalize conflicting rows into one valid identity. For malformed/colliding evidence include deterministic multiplicity/raw endpoint/type evidence sufficient to prevent changes being hidden by the hash; preserve explicit diagnostics. `r1` syntax remains unchanged. Old tokens conflict for every fresh preconditioned task status/property/link write; project/milestone/comment token contracts retain their entity coverage.++Labels, endpoint status, duplicate path, blocker assessment and removal-retention timestamps are separate observation fields. They never enter a source task's incidence hash. Require full comment evidence for authoritative task revisions even when comment bodies are omitted. No task snapshot overload may label absent graph evidence as an empty incident set.++Full detail adds `links` (edgeId, occurrenceRevision when actionable, stored endpoint IDs, public type, outgoing/incoming direction, observed label), `linkDiagnostics`, `duplicateResolution` and `blockerAssessment`, with `graphCoverage`. Summary/body omission preserves coverage/token where that surface already supplies an authoritative revision; omission is not empty incidence. Capture metadata supplies the common snapshot/asOf boundary for labels/status and derived assessments. Historic receipt text/bytes remain immutable; T-2383 may report graph coverage unavailable in supplemental presentation without relabeling or reminting the original result.++## Saved captured queries and native details++Ordinary query options add `hasLinks: Bool`, `linkType`, `linkDirection: outgoing|incoming`, `linkTargetTaskId` and `unblocked: Bool`. Reject opposite-endpoint/direction without a type; reject direction on dependency/association types, whose named views fix orientation. Type/target filters require a matching valid edge; `hasLinks` reports recorded active incidence including invalid evidence, while detailed diagnostics distinguish validity. Combine predicates conjunctively with existing selectors; `unblocked:false` matches certified `blocked` assessments only; `invalid`/`unavailable` assessments match neither Boolean value and remain visible through diagnostics in ordinary unfiltered detail. Reusable T-2382 queries reject all these options before snapshot lookup/publication.++Extend the T-63 selected capture to include graph occurrence values plus required endpoint/status/identity closure. Selection membership is fixed before closure; closure tasks cannot become selected rows or change counts. Whole dependency graph evidence is required where imported-cycle membership cannot otherwise be established; bounded failure replaces incomplete success. The builder uses a fresh read context with `includePendingChanges = false`, freezes values and verifies its persistent-history/generation boundary including occurrence/removal-evidence inserts/updates/deletes. [Apple documents the fetch flag](https://developer.apple.com/documentation/swiftdata/fetchdescriptor/includependingchanges); it is not a substitute for a fresh context/fence.++T-63 prepares/freeze-encodes the complete tool result before late-publication checks; T-2383 consumes that frozen fragment. Added DTOs, graph indexes/closure, encoded results and retained graph evidence count toward the existing five-second read and 16-MiB/eight-view/five-minute retention policies. Cancellation does not release a lingering physical slot early. Cursor/snapshot publication remains behind the existing gate. A retained view lacking graph coverage yields explicit unavailable graph data; no live endpoint join.++`TaskLinkService.savedDetail(taskID:)` returns a value-only saved projection for native details using the same graph semantics. An unsaved source has no saved relationship section; explain it as unavailable until saved. For existing tasks, use saved endpoint names/statuses even while draft editors are open. Refresh on saved store/import notifications; cancel stale completions by selected task/generation, never replace a newer section with older output.++Match `TaskDetailView`'s iOS `Section/LabeledContent` and macOS `LiquidGlassSection/FormRow` patterns. Group incident views by public type and label incoming attribution/duplicate edges explicitly. Show unresolved identity/canonical diagnostics inline. On click, re-resolve exact UUID uniquely from saved state; macOS calls the existing UUID task window, whose resolver also rejects multiple matches; iOS pushes the existing detail view after revalidation. No guessed URL, inline editor, merge, close or undo action.++## Failures++| Boundary | Outcome / effects |+| --- | --- |+| Unsupported type/options, malformed or oversize delta | Existing invalid-input shape failure, unaccepted key, no effects. |+| Missing/ambiguous source or existing affected endpoint, unknown exact occurrence | Identifiable identity/repair unavailable; no domain effects. |+| Fresh task/occurrence precondition mismatch | Conflict with current saved graph-covered evidence when establishable; no domain effects. |+| New cycle, duplicate cardinality or uncertifiable affected graph | Accepted domain rejection; saved protected outcome, no domain effects. |+| Saved capture failure/deadline/capacity/fence failure | T-63 typed failure, no partial graph success or late publication. |+| Dirty UI context / uncertain commit or delivery | Foundation unavailable/uncertain with acceptance/reconciliation evidence; preserve drafts, retry original key. |+| Imported invalid graph | Read diagnostics; dependency/canonical assessments fail closed; exact removal-only repair remains available where identity is established. |++## Risks verified during authorized implementation++- Risk: additive SwiftData/CloudKit migration differs on production-shaped stores | Verify: first implementation spike opens a copied/synthetic pre-feature disk store; live Development schema/export/deletion verification is deferred under the owner amendment | If wrong: stop rollout and revise migration; never reset/delete the user's store. Local success does not certify remote compatibility or authorize production promotion.+- Risk: coordinator-owned task/link/removal/terminal-result changes do not save together or dirty drafts leak through | Verify: disk-backed participating-write, saved-validation, dirty-context and save/encoding failure tests before graph integration | If wrong: keep affected writes unavailable and fix the owned-save boundary.+- Risk: complete cycle/closure capture exceeds existing limits at realistic graph size | Verify: early bounded-read scaling fixture under the unchanged budgets | If wrong: return typed capacity/deadline failures and optimize bounded projection; no larger budget or partial unblocked guarantee without approval.++## Verification plan and traceability++No build/test/runtime validation occurs in this design phase. The implementation phase uses owning `TestModelContainer`, serialized Swift Testing and explicitly granted heavy-job slots. Start with migration, participating-write coordination and owned-save failure cases before dependent UI/query work. Keep independent-writer counterexamples as documented-limit tests, not an all-writer atomicity gate.++| Requirements | Component / meaningful verification |+| --- | --- |+| 1.1–1.5 | Normalizer/index/wire parser: all directions, reversed association idempotence, malformed/self links, same/different UUID collisions, cross-project identity and labels. |+| 2.1–2.4 | SCC/direct blocker projection: Done vs Abandoned/unknown, imported cycles, valid Done blocker with unrelated bad ancestry, no alias traversal. |+| 3.1–3.5 | Attribution and duplicate projection/plan: multiple sources, retarget, chains and terminal states, branching/dangling/cycles, no field/status redirection. |+| 4.1–4.6 | Parser/coordinator/plan: 50 bound, endpoint guards, mixed fields/edges, no-op, race after allocation, replay-first, exact tool/store binding, dirty context success/error/recovery and crash/delivery evidence. |+| 5.1–5.6 | Snapshot/occurrence/migration: empty-set token transition, incoming-token changes, excluded labels/status/removal times, removed re-add identity, expiry token stability plus changed derived diagnostics/assessments and frozen-view preservation, active/removal imports in both arrival orders, expiry/cleanup timing, malformed/ambiguous evidence deferred from cleanup, precise incremental repair, historic bytes preserved. |+| 6.1–6.6 | Capture/filter/encoding: direction predicates, closure scope, pending insert/edit/delete exclusion, failed fetches, frozen replay, missing coverage, retained bytes/deadline/lingering limits and structured/text parity. |+| 7.1–7.4 | Saved native section/window and schemas: saved labels, destination collision/revalidation, consistent native styling, batches reject graph input before acceptance, caller guidance. |+| 8.1–8.3 | Disk and multi-context integration fixtures spanning preceding rows; no store reset or global convergence claims. |++Use deterministic generated small graphs with seeded generators in Swift Testing (no new PBT library) to compare normalized incidence, SCC membership and duplicate resolution to a simple independent reference. Properties: inverse/reversed normalization equivalence; permutation-invariant projection/hash; cycle insertion rejection; valid exact removal changes only the selected occurrence; re-add identity differs; raw retained replay is invariant under later graph edits. Example fixtures cover dirty-context/crash/migration timing that generated pure graphs cannot establish.
specs/typed-task-links/explanation.md Changed +59 / -0
diff --git a/specs/typed-task-links/explanation.md b/specs/typed-task-links/explanation.mdnew file mode 100644index 00000000..ea2b12cc--- /dev/null+++ b/specs/typed-task-links/explanation.md@@ -0,0 +1,59 @@+# Typed links — design self-validation++Current contract: owner `Sentinel_c95239aefa6481919303c2353b8a9e9c` approved participating Transit writes with pre-save validation and outside-writer conflict reporting (decision_log.md ADR 4). The historical all-independent-writer/import validation-to-save fence and persistence-redesign completion gate below are superseded. Original tests, failures and approvals remain historical evidence; owned same-store domain/receipt saving and T-2402 deferral remain unchanged.++## Beginner level++### What this does++A link records a fact between two saved tasks. Dependencies answer whether direct prerequisites are Done; duplicate links point along a chain to its last task. Names are labels, while UUIDs identify tasks. If an identity is missing or ambiguous, Transit shows the problem rather than guessing.++### Why it matters++Agents can select work and understand duplicates without parsing prose. A guarded edit checks the saved version of every task whose visible link set changes. It saves the task, links and retry result together locally. Unsaved drafts stay private and can make a fresh write unavailable.++### Key concepts++An occurrence is one specific saved link. Removing it deletes that link; adding the same relationship later creates a new occurrence. Short-lived removal evidence helps recognize an exact retry. Expiring that evidence does not bring back the deleted link. A revision is a fingerprint of saved task fields, comments and active incident links; a snapshot is one frozen observation used throughout a read.++## Intermediate level++### Changes overview++Two scalar SwiftData entities hold immutable active occurrences and bounded repair evidence in the existing store. A value graph service drives normalization, dependency SCCs, duplicate walks, exact removal planning and native readback. Existing snapshot hashing, T-63 saved capture, T-2384 clean-context write policy and T-2383 result encoding gain explicit graph integration.++### Implementation approach++Normalize dependencies to blocker→blocked and associations by UUID ordering. Compare all physical identity matches. Delete the exact occurrence and insert its removal evidence in the same task/terminal-receipt save. Replay retained outcomes before looking up current tasks. After asynchronous preparation, validate the complete proposed graph and endpoint tokens again at a proven saved local commit boundary.++### Trade-offs++Endpoint task revisions avoid a second graph concurrency token but allow unrelated endpoint edits to conflict. Platform occurrence deletion avoids a custom sync tombstone protocol; the small separate evidence entity is necessary to retain bounded exact-removal recognition without tying expiry to the active graph. Refusing dirty-context writes preserves drafts at the cost of requiring the user to save or cancel first. Complete cycle evidence can cause bounded read failure on large graphs instead of partial unblocked claims.++## Expert level++### Technical details++Hash canonical incident occurrence tuples plus an explicit graph contract/empty array under existing r1 syntax. Physical multiplicity must remain visible; labels/status/derived paths and removal retention are not source-owned covered content. Link-only imports participate in the capture fence. UUID-key indexes retain all physical matches and SCC traversal stays iterative/budgeted. Reusable project/status snapshots cannot be live-enriched with graph data.++### Architecture impact++Schema/snapshot call-site parity is mandatory across app, tests and probes. Shared read/coordinator files remain foundation-owned until handoff. Receipt bytes are historical evidence and cannot be reminted at upgrade. Native relationship navigation must validate destination uniqueness both on click and at UUID window resolution.++### Potential issues++MainActor serialization alone does not exclude peer-context/store imports. A generation check followed by save is not independently proven atomic; the early implementation gate must establish the foundation's saved boundary or leave graph writes unavailable. SwiftData additive migration and remote deletion behavior require disk/development-sync evidence, not an inference from local tests. Repair evidence expiry cannot substitute for framework history retention or globally prevent delayed conflicting imports.++## Validation findings++### Gaps and logic checks++The initial single-row retirement proposal coupled active state to evidence expiry. The current design uses physical active-occurrence deletion and separate evidence, so cleanup cannot reactivate a link. Repair evidence expiry can end evidence-based conflict warnings and change derived assessments of an already imported active row; it neither reinserts a row nor proves remote correctness. Thirty days lacked a personal-tool use case; the approved seven-day repair horizon aligns receipts. The commit-boundary and migration assumptions cannot be proven in spec-only work and have early verification/fail-closed paths.++### Questions++The owner approved seven-day exact-removal recognition with design checkpoint `56e9ad5` (`Sentinel_775be6f4fc6c8191a9d7ccf1d0c04557`). Design review must challenge whether the selected commit fence can meet the approved local invariant without a second write engine.++### Recommendations applied++Keep removal evidence separate from platform deletion/history; reject unknown post-expiry selectors; include empty incidence in every current task token; recheck ambiguity during native navigation; sequence migration/commit-boundary validation before dependent feature work.
specs/typed-task-links/final-handoff.md Changed +65 / -0
diff --git a/specs/typed-task-links/final-handoff.md b/specs/typed-task-links/final-handoff.mdnew file mode 100644index 00000000..3fe6846a--- /dev/null+++ b/specs/typed-task-links/final-handoff.md@@ -0,0 +1,65 @@+# T-1734 local implementation handoff++Historical handoff for application/test source 81f78e7. Post-PR native corrections and fresh source bbe3a25 verification are recorded separately in [pr254-native-corrections.md](pr254-native-corrections.md): 4,694 passing platform case executions and five intentional macOS skips. The original outcomes below remain unchanged evidence.++All 22 approved Rune tasks are locally complete. `rune next specs/typed-task-links/tasks.md --format json` reports all tasks complete. Application/test source verified by the final platform runs is `81f78e7687029895faef4e0d914882f403962f26`; subsequent changes only record completion/evidence. Publication and main integration remain with the parent, outside this local implementation handoff.++## Final base and preservation++The typed branch is `T-1734/typed-task-links-final`, based on landed `origin/main` `e04c1268ee37bd4ae925d4d686954cf2121005c7`. Original worktrees/checkpoints remain preserved. Old `7d7271f0c86ed337ae52b0cb49fc152fea8f6a47` is retained by `T-1734/pre-landed-foundation-20261005`; the reconciled `9c8695e0070666b0902434c26b449881ba8d3023` had identical code/tests/Makefile and only three already-merged batch review documents differed. See [task14-checkpoint.md](task14-checkpoint.md). Canonical/main and canonical `.kiro` were untouched by T-1734; canonical/main is now e04, advanced outside this isolated work.++## Implemented acceptance scope++| Task pair | Local capability and executed coverage |+| --- | --- |+| 1–2 | Immutable scalar link/removal models; seven current schema factories; real process-separated six-entity seed/control → actual eight-entity upgrade/reopen; raw fields and receipt preservation. |+| 3–4 | Participating shared coordinator phase and opt-in owned same-store services; exact receipt binding/refetch/recovery; draft, save, encoding and replay boundaries. Existing baseline controls passed without inventing a cache defect. |+| 5–6 | Physical graph multiplicity, raw diagnostics, directed dependency SCCs, direct blocker assessment, complete proposed-plan validation and exact repair recognition. |+| 7–8 | Frozen saved graph closure, original read deadline, physical-slot/history fencing, populated index/result capacity accounting and no partial or late publication. |+| 9–10 | Explicit task-links-v1 r1 coverage, physical incidence canonicalization, empty-incidence transition, legacy missing coverage and unchanged historical receipt bytes. |+| 11–12 | Closed standalone wire deltas/preconditions, exact l1 selector, bounded public types and batch rejection; shipped batch tool name is `mutate_tasks`. |+| 13–14 | Final create UUID, saved endpoint/source checks, graph application after source precondition, one owned domain/evidence/receipt save, mixed changes, repair/no-op/replay and rollback. |+| 15–16 | Graph filtering before order/page/body selection; saved-only frozen results/cursors, current modern adapter parity and compatibility error surfaces without returning injected live values. |+| 17–18 | Bounded seven-day evidence cleanup with physical identity/fingerprint/date guards and owned rollback; active links and receipts are preserved. |+| 19–20 | Saved native relationship labels/diagnostics/blockers; unique saved UUID resolver at click and macOS window; cancellation/stale continuation/pending deletion controls; actual iOS relationship navigation and ambiguity UI tests. |+| 21–22 | Integrated real-handler/store/foundation regressions, final schema/contracts audit, full macOS/iOS unit and iOS UI verification. |++The 39 acceptance criteria remain mapped to these task pairs in [tasks.md](tasks.md), with requirements and design references preserved. Historical behavioral RED and compile-only failures remain distinct in [implementation.md](implementation.md), [task4-checkpoint.md](task4-checkpoint.md), and [task20-checkpoint.md](task20-checkpoint.md).++## Final verification++| Run | Expanded cases | Native declarations | Build / run | Runtime warnings |+| --- | --- | --- | --- | --- |+| Focused query/capture/wire compatibility | 170 pass, 0 fail/skip | 123 pass | 0 / 0 | 0 |+| Full macOS units | 3,253 pass, 0 fail, 5 intentionally disabled | 2,527 pass, 5 skip | 0 / 0 | 0 |+| Full iOS simulator units | 1,391 pass, 0 fail/skip | 1,323 pass | 0 / 0 | 0 |+| Full iOS simulator UI | 26 pass, 0 fail/skip | 23 pass | reused successful unchanged build / 0 | 0 |++Native flat compiled inventories have no discovery errors: macOS 2,532 declarations, iOS units 1,323 and UI 23. Expanded counts come from device/configuration summaries and retained native trees, not declaration totals. Full UI includes both relationship cases and the existing launch configurations.++`make lint` passed all ownership/create-schema/development-configuration guards and SwiftLint on 649 files with zero violations. Log: `/tmp/t1734-lint-81f78e7.log`. The final schema source audit passed all current registration paths, preserving intentionally graph-free historical controls. Its JSON is in the final macOS root below. Diff check passed.++The macOS build has one existing manual-target-order warning. The iOS build has 35 warning lines covering that warning, existing retroactive TaskStatus/TaskType Sendable conformances and unused values/results in existing tests. The build log retains exact locations; no platform runtime warning was reported.++### Evidence roots++All paths below are beneath `/var/folders/11/v0tnfm294kd9c6zll_ncmpkh0000gn/T/`:++- `t1734-query-compatibility-precedence.djxb5ue3`: `build.log`, `build-exit.txt`, `compiled-inventory.json`, `summary.json`, `tests.json`, `run-outcome.json`; host 69050 drained.+- `t1734-final-macos-corrected.7su76bgk`: build/enumeration/run command and exit files, `compiled-inventory.json`, `summary.json`, `tests.json`, `run-outcome.json`, `schema-audit.json`; runtime host 69279 drained naturally.+- `t1734-final-ios.ce22wn5q`: `signed-preflight.json`, `build-exit.json`, `build.log`, `TransitTests-compiled-inventory.json`, `TransitTests-summary.json`, `TransitTests-tests.json`, `TransitTests-exit.json`, `final-drain.json`, `owned-simulator-deletion.json`; unit host 71262 drained naturally. Owned simulator F16FC947-B7C9-4F00-A29A-D1744C20F8D4 shut down/deleted with exit 0 and no remaining owned processes.+- `t1734-final-ios-ui-bounded-census.r9nkfxdw`: unchanged-build proof, signed preflight, UI compiled inventory, `TransitUITests-summary.json`, `TransitUITests-tests.json`, `TransitUITests-exit.json`, `process-census-timeouts.jsonl`, `final-drain.json`, `owned-simulator-deletion.json`. All 27 recorded runtime hosts drained naturally, no timeout or sampled teardown. `final-recorded-pid-census.json` additionally proves all 29 recorded final macOS/iOS runtime PIDs are absent. Owned simulator 7A071F23-6A83-41A9-850F-8EF6B4DE983E shut down/deleted with exit 0 and no remaining owned processes.++### Preserved corrective evidence++The first final macOS pin cf33cb25 had 14 failures: eight query fixtures had only unsaved/mock seeds, five discarded injected storage-error hooks were lost, and graph's second task fetch erased injected malformed canonical data before selected serialization. Fixes explicitly inserted/saved only the read-fixture paths, restored error hooks while discarding successful live values, and reused the complete already-fetched saved task population within the capture fence. Assertions, budgets, dirty-write helpers and saved-only policy were preserved. A further selector-shape extraction and three controls preserve invalid/blank project validation before failing hooks. Final focused and full suites passed these corrections.++Two UI attempts stopped on a bounded process-census timeout rather than a test assertion: `t1734-final-ios.ce22wn5q` stopped during UI enumeration, and `t1734-final-ios-ui-retry.0daqwdp6` stopped during runtime. Both owned simulators were verified drained and deleted. Their partial logs/results are retained and are not full-UI success evidence. The final runner retries only transient `TimeoutExpired` inspection up to three five-second attempts; denial, nonzero/malformed output and PID ownership mismatch remain fail closed. Four first-attempt timeouts recovered in the final run, each logged; elapsed time remains charged to the original absolute 1,200-second runtime deadline. No source, assertion, setting or unit-run changes were needed.++## Practical limits and next ownership++- Development CloudKit setup, export and platform deletion verification are explicitly deferred to T-2402. No account/container/schema activity occurred.+- Atomicity is the approved participating local owned-save contract. Independent containers/importers can race; no global CloudKit or all-writer fence is claimed. Primitive counterexamples remain evidence of those particular primitives, not proof that all mechanisms are impossible.+- Native macOS click/window resolution is implemented and unit tested through the shared resolver. Actual native UI execution here is iOS; no macOS window UI execution is claimed.+- Five opt-in macOS cases remain intentionally disabled: the two primitive diagnostics, closed-store stage, development schema precheck, and outside-writer observation. Their earlier targeted evidence or explicit deferral is preserved.+- No push, PR, main merge, deployment, client activation or external source disclosure was performed. The parent owns final review/CHANGELOG/overview/archive and any separately authorized publication.
specs/typed-task-links/implementation.md Changed +321 / -0
diff --git a/specs/typed-task-links/implementation.md b/specs/typed-task-links/implementation.mdnew file mode 100644index 00000000..fe84236c--- /dev/null+++ b/specs/typed-task-links/implementation.md@@ -0,0 +1,321 @@+# Typed task links — implementation evidence++Current contract: owner `Sentinel_c95239aefa6481919303c2353b8a9e9c` approved participating Transit writes with pre-save validation and outside-writer conflict reporting (decision_log.md ADR 4). The historical all-independent-writer/import validation-to-save fence and persistence-redesign completion gate below are superseded. Original tests, failures and approvals remain historical evidence; owned same-store domain/receipt saving and T-2402 deferral remain unchanged.++## Current local implementation status++All 22 approved tasks are complete on `T-1734/typed-task-links-final`. The final verified application/test source is `bbe3a2560584f7fb822aa8006b20f08d22284ce4`, based on the four landed foundations at `e04c1268ee37bd4ae925d4d686954cf2121005c7`. PR #254 review prompted a five-file native correction: direction-relative incoming attribution/duplicate labels and cancellable 100-ms notification-burst coalescing after immediate generation invalidation. Initial loads remain immediate, obsolete providers never capture, and the complete saved graph remains available. Later commits are documentation only. Original worktrees and the pre-reconciliation branch remain preserved; canonical main and canonical `.kiro` were not edited locally by T-1734.++Fresh final isolated runs at bbe3a25 passed 3,265 expanded macOS unit cases, 1,403 iOS unit cases and 26 iOS UI cases: 4,694 passing case executions across platforms, zero failures, and five intentional macOS opt-in skips. Native declarations are 2,530 macOS passes plus five skips, 1,326 iOS unit passes and 23 UI passes. Focused native verification passed 20 expanded cases / seven declarations. Runtime warnings are empty; signing/build preflight and lint (652 files, zero violations) passed. All recorded hosts drained and the owned simulator was shut down/deleted. [pr254-native-corrections.md](pr254-native-corrections.md) records exact current outcomes; [final-handoff.md](final-handoff.md) preserves the earlier 81f78e7 source's 4,670 passes separately.++Four independent local review roles inspected the complete branch and corrective deltas through bbe3a25. All mandatory findings are resolved, including caller naming, captured-task refetch, project error precedence and native notification/label corrections. [local-review.md](local-review.md) records the findings, 39-criterion traceability and explicit qualifications. Live Development CloudKit setup/export/deletion and production schema promotion remain gated by T-2402; consolidation remains T-2381 work. PR publication/merge is a separate authorised workflow and performs no deployment, live writes or client activation.++## Beginner level++### What changed++Tasks can record five kinds of relationship: blocks, blocked-by, relates-to, introduced-by and duplicate-of. A link records an occurrence between two task UUIDs. Duplicate-of can identify a canonical task through a chain, but each original task keeps its identity, content and comments.++### Why it matters++Agents can select work using recorded dependencies and inspect duplicate relationships without combining several changing responses themselves. Native task details show saved relationship labels and diagnostics. Selecting a resolved relationship opens that exact saved task; ambiguous or missing destinations do not choose an arbitrary record.++### Key concepts++A revision is a content token used to reject edits based on old evidence. Current task revisions cover link membership as well as existing task fields and comments. A receipt preserves a protected write's original result for retry. A frozen query page preserves its original saved evidence even if tasks change later. These are local-store guarantees; they do not certify remote CloudKit convergence.++## Intermediate level++### Implementation approach++Two additive scalar SwiftData models store active occurrences and separate bounded removal evidence. All physical rows remain visible to value-only graph projection, including repeated UUIDs and malformed imports. Dependency assessment uses direct blockers: Done satisfies a valid blocker; Abandoned and other recognized non-Done statuses do not. Cycles, missing or colliding endpoints, unknown direct blocker status and conflicting evidence are reported explicitly. Duplicate resolution walks a directed chain and stops on repeated identity, cardinality or endpoint faults.++Standalone create/update link directives use the existing protected coordinator. The adapter resolves current source and affected endpoint revisions in a clean owned context, validates the entire proposed graph, stages task fields and exact occurrence changes, encodes the terminal result, then saves domain changes and receipt together. No-op additions/removals preserve timestamps and content tokens. Removal-only repair can reduce precisely identified corruption without silently deleting equivalent rows or adding unrelated changes. Batches retain their approved per-item fields and reject link directives before acceptance.++### Reads and compatibility++The MCP capture builder freezes selected task values, full graph closure, required comments and evaluation time inside the existing history/generation fence. Graph filters run before body serialization, ordering and page publication. Closure tasks support assessment without becoming selectable or changing portfolio totals. Current `r1` tokens explicitly cover empty incidence; old pre-feature tokens cannot authorize fresh preconditioned edits. Historical receipt bytes and results missing graph coverage are preserved rather than reminted.++### Trade-offs++Participating writes cannot interleave the synchronous final coordinator phase. Independent containers, external writers and imports can race with it and leave inconsistent saved links. Later reads report available faults; no automatic repair, post-commit rollback, task redirect or consolidation is introduced. Native sections use fresh saved value DTOs and generation/cancellation checks. Their observation is distinct from a fenced retained MCP snapshot.++## Expert level++### Technical details++The graph indexes domain UUIDs to every physical match and preserves raw occurrence tuples. Iterative strongly connected component traversal retains every structurally resolved physical dependency, so logical deduplication cannot hide cycle evidence. `l1` fingerprints include occurrence identity, kind, endpoints and immutable creation time. Current `r1` incidence includes identity/kind/endpoints with physical multiplicity; endpoint labels/status, removal expiry and derived assessments remain separately observed data. Authoritative snapshot entry points require explicit incidence coverage, including an explicitly empty set.++Owned write commitment refetches and binds the original receipt to its exact store scope, tool, key, payload, version and state. Source revalidation precedes staging; exact deletion additionally checks physical identity and immutable tuple/date bits. Allocation selects a new task UUID before graph validation and assigns it before insertion. Dirty shared contexts are checked before acceptance and after preparation success or error. Retained replay remains read-only and precedes current graph lookup; uncertain persistence retains original-key reconciliation instead of clearing durable guards.++Capture reuses the task population already fetched within the fence, avoiding a second fetch that could replace selected evidence before canonical serialization. The original five-second deadline reaches graph construction, body selection, filters and encoding. Existing physical read admission and five-minute/eight-view/16-MiB retention caps remain intact; graph backing values, index membership and diagnostics are charged. Deadline or capacity exhaustion produces a whole failure without late publication. Startup cleanup separately scans at most 512 evidence candidates, deletes at most 128 eligible uniquely identified rows and uses one owned save with rollback on failure.++### Architecture and limits++The extension joins the landed read capture, modern result, reusable portfolio and batch coordinator foundations. Saved native navigation checks uniqueness both at click and at macOS window resolution, then returns the exact physical model owned by the navigation context. Native saved projections invalidate the prior generation before a cancellable 100-ms same-source notification wait, recheck generation/source/cancellation before capture and publication, and retain immediate initial loads; they do not advertise the MCP capture's certified frozen boundary. Optional efficiency follow-ups include diagnostic indexing and notification coalescing, within the same budgets and freshness semantics.++Live Development CloudKit schema/export/deletion verification remains T-2402 work. Installed-client activation, production promotion and T-2381 consolidation are outside this local implementation. Local schema migration and scalar compatibility do not prove CloudKit-wide atomicity or convergence.+++## Completeness Assessment++**Fully implemented:** all 39 acceptance criteria within the approved participating-write/local-saved scope, covering the 22 tasks, additive migration/schema registration, graph/repair semantics, current revisions, protected owned writes, bounded frozen queries, evidence maintenance, native visibility/navigation and foundation compatibility. Final focused, full macOS, iOS unit and iOS UI outcomes are green; local review has no outstanding mandatory fix.++**Partially implemented:** none within that approved local scope. Native saved projection is intentionally described separately from the history-fenced retained MCP capture; concurrent inter-fetch native coherence is not certified. Actual UI execution here is iOS; macOS click/window uniqueness is implemented and covered by shared resolver unit controls.++**Deferred or outside scope:** T-2402 live CloudKit setup/export/platform deletion verification, installed-client activation/production promotion, global/all-independent-writer atomicity and T-2381 consolidation. They are not silently marked passed. Historical RED, compile-only failures, lost executor exit and interrupted UI diagnostic evidence remain recorded; definitive final platform results are in the final handoff.++## Historical implementation record++The following chronological record preserves original source pins, failures and approvals. Earlier readiness, external-environment and superseded independent-writer fence statements are historical; the current status and approved ADR 4 above govern this completed local implementation.++## Authority++Owner `Sentinel_d1ba9360969c81918777711b2420bfc7` approved tasks checkpoint `18a268f` and continuation once the code foundations are ready. Local approval commit `9449b9f` records that authority. Readiness is a technical prerequisite, not another user approval gate. Seven-day repair recognition and the migration/atomic-save/capture enablement gates remain binding.++## Foundation observation++Read-only local heads observed at implementation start:++| Owner | Head | Remaining integration condition |+| --- | --- | --- |+| T-63 | `7a2f4de913beaffe166aca8d705102096488ecaf` | Stage A isolated routing evidence passes; actual T-2382 module Stage B and modern adapter Stage C remain. Read/server/types/handler ownership not transferred to T-1734. |+| T-2382 | `cd20767592639c74ced5bd1569dfbccc0d3c868b` | Portfolio helpers and coordinated integration remain in progress. Historical head only; the exclusive slot has since passed to T-2383. |+| T-2383 | `912ddbca727065e5ee426ff165b286b8b9c7f58c` | Modern protocol/result adapter foundation and handoff remain in progress. |+| T-2384 | `6833e69e5754da07f4bf26b41bde87710d4d62c1` | Batch/write-coordinator work remains owner-controlled; no T-1734 coordinator integration yet. |++These are observed source heads, not a claim that all four foundations are verified or merged. Local main/origin remain `201205bd4e786c7f152d8f99006b37da7da888c7`. Do not import whole owner branches or resolve shared-file conflicts by restoring older blobs.++Independent task1 feasibility tests do not require all four foundations to merge. Read-only comparison of the initially proposed verified `b500543369ebbd53f01634fa829bf74a8fceabe5` component identifies the existing model/test fixture interfaces as unchanged and the isolated host's T-63 startup bindings as the transitive runtime dependency. `isolation-integration-plan.md` records that initial proposal; App/project/isolation files match containment `9ba4297`, and only overview docs overlap. Parent selected containment's narrower isolation-only component `3194e5a64dedb004dbfca3666bf590a552b676ee`; consumed as `e1c1ac4`, preserving all existing MCP/read/write/model/helper source. It avoids importing the full T-63 envelope and carries no ownership transfer. Fixture lint correction `d2cc0c6` and branch-local source guards/full lint pass (406 files, zero violations). No app runtime verification occurred. T-2383 holds the heavy slot.++## Safe independent preparation++Task1 RED source can be prepared in new isolated test files against existing SwiftData/model APIs. No graph-write implementation or new production model/schema registration occurs before foundation handoff. Existing `TestModelContainer` retains containers for process lifetime, so reopening a baseline schema in the same process demonstrates saved-state preservation, not a closed-store schema upgrade; full migration must prove that separately.++Prepared `Transit/TransitTests/TaskLinkMigrationTests.swift` has two test declarations and three anticipated expanded cases: two parameterized missing-model schema-capability checks, plus a synthetic six-entity disk saved-state control. The control preserves raw unknown enum fields, task/comment links, physical duplicate task UUID/display IDs and exact historic receipt JSON strings. Schema metadata assertions use the installed SwiftData public interfaces, not missing future model types. This is source preparation, not executed RED; it does not prove actual schema migration or development CloudKit compatibility.++The combined `rune next --phase --stream 1` invocation returned no ready tasks for this flat plan, while ordinary `rune next` and `rune streams --available` correctly returned task1. Execution uses the explicit task ID without changing the approved DAG. Task1 is in progress; no task is complete and task2 remains blocked.++Source preparation committed at `900aa605442acc7fdb43deab1ce93d229187c8ab`. A focused runtime run needs a fresh guarded shared Transit Debug build containing this test file; a previously built foundation test binary does not include it and cannot supply evidence. Require the xcresult to contain the intended two declarations/three expanded cases; zero discovered tests is not RED or GREEN.++## Test execution prerequisites++This branch contains the owner-delivered development-isolation harness; branch-local runtime verification is pending. Do not run a combined build/launch `make test-quick` before signed-host/prepared-xctestrun checks. Use the eventual shared Transit Debug unit-test scheme, verified identity `me.nore.ig.Transit.development`, no CloudKit/push/App Group entitlements, explicit isolated persistence and private result/DerivedData paths. `TransitDevelopment` is not the unit-test scheme.++Request a concrete focused slot after the runnable fixture and isolation integration are ready; T-2383 owns the slot now. Local disk tests must not contact CloudKit. The opt-in development-schema fixture additionally needs the approved environment/setup prerequisite; no default test run may initialize production schema or touch ticket records.++No app tests, builds or runtime RED/GREEN evidence are claimed at this checkpoint. Live Transit mutations, client activation, deployment and production schema promotion remain held. Canonical main and `.kiro` remain untouched.++Implementation evidence stays local. Owner `Sentinel_187b411b1d4c8191a3449aa38689b0b6` requested documents only for spec creation/review or an explicit request; no routine phone/report delivery occurs for this checkpoint.++Focused signed-host preflight preparation is committed at `b9d65b9e483ea59d65ed458851132184dab1331f`. `tests/typed-task-links/prepare_unit_run.py` prepares a fresh unit-only run file and local evidence after verifying development signing, safe entitlements, exact host path and unit-test persistence. It has not been executed. The exact queued commands and remaining evidence gates are in `verification-readiness.md`.++## First isolated execution — prerequisite failure++Parent released the exclusive heavy slot for `afeaf94667e8a925a07cd86e4543e018143aa48b`. Actual evidence root: `/tmp/t1734-independent.7vkeiE`; `source-head.txt`, `offline.log` and `offline-exit-status.txt` preserve the source and result. `make test-development-isolation` compiled the three standalone probes and passed the source configuration guard, then exited 2. The runner's sequential `seed-old` child exited -5 at `MigrationProbe.swift:14`, the disposable-path containment precondition, before creating its SwiftData container. This is an offline harness prerequisite failure, not typed-link registration RED or migration evidence. The exact path-normalization cause remains unverified; retain the fail-closed boundary for owner diagnosis.++The runner did not produce its final isolation-verification JSON. Its temporary synthetic directory was cleaned by its context manager. An existing `DisplayIDAllocator.swift:170` unnecessary-await warning is incidental and separate from the fatal precondition. Do not change allocator or containment owner source to mask this failure.++Stopped before dedicated host build/smoke, shared Debug build, codesign/xctestrun preflight and the focused three-case suite. No app host launched, no CloudKit account/schema operation or live-data access occurred. A post-run escalated process census found no owned probe/runner processes; no teardown cleanup was necessary. The exclusive heavy slot is released after drain. Task1 stays incomplete, and all downstream gates remain binding. Resume after the containment owner supplies a verified correction or safe path prerequisite; no additional user approval is required for the approved local checks.++## Corrected isolation execution — verified boundary and fixture compilation blocker++Parent supplied guard-preserving owner correction `33b006a12a2d534d420a8b2cbb10ecd3a458096f`, reviewed and consumed as `237c7e127aa768ce470d80bedc0a9098249f5de9`. It canonicalizes existing root/parent directories and compares path components before appending the synthetic leaf; exact filename, sibling-prefix and symlink escape rejection remain intact. Owner reproduced the existing-root/nonexistent-leaf `/tmp` versus `/private/tmp` mismatch. Earlier failure artifacts remain unchanged.++Exclusive-slot rerun evidence is `/tmp/t1734-independent.RNKK3q`, with immutable source identity, logs, statuses and `preserved-evidence-sha256.json`. Offline Make exit 0: policy/bootstrap pass, pathGuard exit 0 (aliases, new/existing leaves, sibling-prefix collision, wrong name, missing directory, leaf symlink and parent escape), actual isolated configuration exit 0, sequential invariant true, sequential/concurrent `open-new` exits 0 and concurrent old-process exit 0. Synthetic probes remain network/live-container denied.++Dedicated signed-host smoke Make exit 0. Artifact preflight records development bundle identity, valid signature, safe entitlements with no CloudKit/push/App Group keys and unit-test persistence. Actual runtime case verifies memory-only `/dev/null` persistence, cloudSync=false, disabledCounters=true and private `mcp-tests-…` sidecar. `smoke-summary.json` independently reports exactly one passed test, no failed/skipped tests. UIKit/XCTest's zero legacy tests is separate from the one executed Swift Testing case. Incidental destination-selection and App Intents service warnings are retained in the log; they did not fail the smoke.++Fresh shared Transit Debug build then exited 65 with two fixture compiler errors: `#expect(attribute.valueType == expectedType)` macro expansion cannot compare existential metatypes in its generated generic operation; `FetchDescriptor<Comment>` is ambiguous between Transit.Comment and Testing.Comment. The 25 listed failed compilation steps are not 25 independent errors. No prepared unit-run file, migration host launch or focused migration execution followed. These compiler failures are not behavioral RED; all three anticipated migration cases remain unexecuted.++Post-build escalated process census found no owned build/probe/smoke processes. No teardown cleanup was necessary; exclusive slot released after drain. Continue narrowly with the delegated test-source correction; preserve the successful isolation boundary without claiming it covers changed migration source. A fresh guarded unit build and focused serial run require the next parent-assigned slot. Task1 and downstream feasibility gates remain incomplete. No production/shared graph source, live Transit mutations, CloudKit account/schema publication or main changes occurred.++Narrow fixture correction committed at `88711a97f5f6ffb6a9def78139b2ba9c35190043`: compare metatype identity using ObjectIdentifier values and qualify all model Comment references as Transit.Comment. Review confirms these changes preserve intended assertions and the three-case inventory; no production files changed. Focused strict SwiftLint and diff/source checks pass, zero violations. Compilation/runtime verification of this correction is pending the next slot. The next queued job is a fresh shared Transit Debug build with locked packages, then the existing signed-unit preflight helper and serial TaskLinkMigrationTests run, using new paths as documented in verification-readiness.md. Do not reuse the failed unit binary as evidence. Offline and dedicated smoke evidence belong to source237c7e1; the correction changes only the migration fixture.++## Focused runtime boundary — honest capability RED and passing saved control++Parent reassigned the exclusive slot after T-2382 drain. Executed immutable source `4e44caa82dd66a995b6992fc949de236f4e16f99` with fresh evidence/DerivedData root `/tmp/t1734-focused.2GDqRp`; unchanged offline inputs retain their previous evidence without rerun. Fresh shared Debug build exit 0. Fresh signed-unit preflight exit 0 records exact development host, verified signature, get-task-allow=true, no CloudKit/push/App Group entitlement, unit-test persistence and in-process startup attestation. Its new run file contains only the verified unit target and TaskLinkMigrationTests; no UI test launched.++Serial focused run exit 65 is now behavioral registration-capability RED: parameter TaskLinkOccurrence fails at line14 because entitiesByName returns nil; parameter TaskLinkRemovalEvidence fails identically. The synthetic six-entity preFeatureDiskBaselinePreservesRawFieldsAndReceiptBytes control passes, including historic raw fields/receipt bytes and physical duplicate task UUID/display IDs. `migration-tests.json` explicitly enumerates both failed argument nodes and the passing control. Swift Testing reports two declarations/one suite; xcresult per-device results report two failed expanded runs plus one passed run. The top-level summary's totalTestCount=2 counts declarations, not the three expanded cases. No crash or zero-discovery failure occurred.++Artifacts: `unit-build.log`, `unit-preflight.log`, generated `t1734-migration-preflight.json`/`T1734Migration.xctestrun`, `migration.log`, `migration-summary.json`, `migration-tests.json`, `T1734Migration.xcresult`, exact exit-status files and `preserved-evidence-sha256.json`. Prior prerequisite-failure and passing isolation evidence remain unchanged. Incidental destination-selection/App Intents service warnings are separate from the two intended assertion failures.++Escalated post-run process census found no owned build/host/test processes. No stalled teardown or cleanup occurred; exclusive slot released after drain. Task1 remains in progress: metadata assertions beyond entity existence have not executed, the disk control is saved-context observation rather than closed-store additive schema upgrade, and process-separated migration/development CloudKit compatibility/full task1 coverage remain outstanding. Do not mark task1 complete or unblock task2 merely from this partial RED/control result. Migration, atomic-save and bounded-capture gates continue to protect later graph/write work. No live task mutations, CloudKit account/schema publication, production graph models, main merge/push or canonical .kiro changes occurred.++## Remaining task1 source preparation++Committed `7c4b28944975f7b945cb3f45af53bd6ee2672334`: test-owned process-separated seed/legacy/actual-schema-upgrade/reopen source; optional directory/schema/seed controls on the existing raw-field fixture; signed-unit preflight reuse with explicit --run orchestration, exact host-PID/path-alias drain checks and one-case xcresult validation; source schema inventory; opt-in local CloudKit precheck explicitly unable to satisfy the external gate. No production/shared registration changes. Focused strict SwiftLint, ownership guard and diff checks pass; Python ASTs valid. Source parity guard exit1 is intentional static RED: 19 inventory entries, seven current factories missing link registrations; saved at `/tmp/t1734-schema-audit-7c4b289.json`. None of the new Swift source has compiled or run.++`migration-next-tests.md` records the minimal queued job, stage expectations, exact task2 declaration/registration ownership and genuine external gate. Current source should pass seed/closed legacy control, then fail missing registrations at upgrade and stop. Actual local additive migration GREEN and opt-in development platform deletion remain unproven; task1 stays incomplete and task2 remains blocked. Parent holds production-seam coordination; unrelated foundation merges do not block this independent RED fixture. T-2383 currently holds the heavy slot; preparation ran source-only checks.++## Process-separated closed-store RED — verified local control++Parent assigned the scoped slot to immutable source `4ba0c6569ac914c91f9953e55ef832e247fd03f6`. Fresh guarded shared Debug build exit0; the runner's fresh signed-unit preflight passed before launch. Evidence root `/tmp/t1734-closed.zwjNwD` preserves exact source, build log/status, signed preflight, stage run files/results, plan, drained summaries, combined runtime log and `preserved-evidence-sha256.json`.++Three distinct isolated host processes executed exactly one non-skipped case each: seed PID46550 exit0/pass1; legacy reopen PID46572 exit0/pass1; current-schema upgrade PID46584 exit65/fail1. The runner established each preceding host's disappearance using both product-path aliases and exact recorded PID before advancing. Guarded development-container Data/tmp paths and symlink rejection ran before synthetic ModelContainer access in every stage. Legacy reopened the physically closed six-entity store and preserved the original pre-save raw fields/receipt bytes/physical duplicate identities. Upgrade also preserved those bytes but failed the intended `missing.isEmpty` assertion at line51 with TaskLinkOccurrence and TaskLinkRemovalEvidence absent from the actual current schema. This is closed-store registration-capability RED, not an eight-entity migration success.++Outer runner exit1 is its deliberate stop after stage exit65, not an incidental failed seed/control. Final reopen did not execute, and upgraded zero-link table counts were not claimed. No crash, missing observation, skipped or zero-discovered stage occurred. Destination/App Intents service warnings remain incidental and separate from the single intended upgrade assertion.++Preserved synthetic root: `/Users/arjen/Library/Containers/me.nore.ig.Transit.development/Data/tmp/T1734Closed-36AF407A-39F7-4842-AFD1-BD7B83246166`; original manifest, stage JSON and store/WAL/SHM are retained and hashed without deletion. The runner records each hostDrained=true; an independent escalated post-run census confirms no recorded host PID or owned build/test process remains. No stalled teardown/sample/cleanup was needed; exclusive slot released after drain. No real CloudKit account/schema action or live store access occurred.++The next paired local GREEN seam is the two task2 production model declarations plus coordinated actual-schema registrations and source-parity repair, then this same fresh guarded pipeline through successful upgrade/final reopen and empty physical link tables. Existing typed metadata tests must also reach their scalar/default/no-unique/no-relationship assertions. No new API is needed for current RED compilation and unrelated foundation merges do not block that local boundary. Parent must coordinate the exact task2 seam without silently completing task1 or bypassing its approved dependency. Task1 remains incomplete because full model/schema parity and the genuine opt-in development platform-deletion fixture are not established; task2's full gate additionally requires separate cleared development schema evidence. No graph-write enablement or atomic-save guarantee follows from these local controls.++## Reviewed RED completion; task2 ownership coordination++Internal design-critic confirms honest local RED and identifies no approved DAG contradiction. Substantive opt-in development smoke source closes the one real task1 source gap, at `31687b9a6d3acae953f831540928e4af71aae238` plus timeout sampling preparation `cffece1b597e975038d3b8deb023e89345ad949f`. It is excluded from default targets and uncompiled/unexecuted, with real task2 typed declarations and separately cleared environment still required. Critic reviewed exact run-UUID assertions and signed Development-only wrapper guards; no source blocker remains for RED completion.++Rune completed task1 and returns task2 next. All previous statements that task1 remains incomplete describe earlier checkpoints; current completion means RED source/prepared fixtures and demonstrated local failure/control evidence, not task2 GREEN. `red-boundary-review.md` records reconciliation. Task2 retains successful actual-schema upgrade/final reopen, scalar metadata/current schema parity, opt-in smoke compilation and actual cleared development schema/deletion verification before task3. Shared source work awaits parent-agreed ownership of the seven-factory patch and compile list; new model definitions remain approved task2 scope. Inventory/patch are prepared and unapplied, no owner agreement inferred. No heavy run, CloudKit operation, production declaration, shared App/probe edit or task-record mutation occurred during reconciliation.++## Task2 model source and granted registration additions++Rune marks task2 in progress. Commit `794c1550c13198bda8cff05f30a576553209427d` adds the two production SwiftData model declarations. Occurrence stores five scalar fields and removal evidence eight, with private setters, declaration defaults and explicit constructor identities/timestamps. Imported raw strings remain unchanged; there are no relationships, uniqueness constraints or constructor validation. Focused strict SwiftLint and source-shape/diff checks pass. The declarations have not compiled or run.++Parent subsequently granted only the containment-reviewed App schema-list and Makefile compile-list additions from the pending patch at eaf5f461. Commit `55c88faef57f43c2036f5a2bc95eadb20e1becd4` applies exactly those two hunks: append both model types after MCPWriteReceipt in TransitApp's schema and include both model files in MCP_PROBE_MODELS. Startup guards, isolation configuration, storage, counters, sidecars and handlers are unchanged. Historical five/six-model controls and the graph-free isolation MigrationProbe remain intact. Exact diff review and focused lint pass; the source configuration guard passes all development identity, entitlement, test-launch and guarded-allocator checks.++Source parity audit at 55c88fa exits1 as expected, with both production files present and six current factories still missing registrations: MCPWritePersistenceProbeTests, TestModelContainer, CoordinatorProbe, FoundationProbe, Probe's current-mode branch and ServiceProbe. Evidence is `/tmp/t1734-schema-audit-55c88fa.json`. Those six additions await the parent's remaining owner agreement; this checkpoint does not infer that T-63 owns every write-probe file. Do not apply whole older owner files or broaden the granted hunks.++Once source parity is ready and parent assigns a heavy slot, a fresh guarded build must verify macro compilation and scalar metadata, then execute closed-store upgrade/final reopen and empty graph-table assertions. Prior runtime evidence predates these declarations and cannot establish their GREEN result. No new heavy build, test, compiler probe or runtime launch occurred here.++Real development CloudKit verification remains a separate environment prerequisite: a reserved Development account/container/zone, verified additive record types and field mappings with exemplars, a properly provisioned dedicated signed host, a reviewed exact contract and parent environment/execution clearance. The opt-in fixture is uncompiled and unexecuted; no signing, account, schema publication or live data operation occurred. Task2 remains incomplete and task3 blocked until both approved local migration and cleared development evidence gates pass. Canonical main and .kiro remain untouched; evidence stays local without routine report delivery.++Parent relayed T-63's explicit grant for the TestModelContainer default schema's two-model list addition. It preserves all configuration and retained-container lifetime logic. The five remaining pending hunks are the computed schema in MCPWritePersistenceProbeTests, ServiceProbe.main, FoundationProbe.receiptStorage, CoordinatorProbe.main and Probe's non-seed-old branch. Parent is routing their ownership directly; no permission for those five edits is inferred from this grant. No heavy verification or live operation is authorized by the source handoff.++The TestModelContainer addition is committed at `d4dcb9b2c7beb01b51101427efdb3f9086e70ef9`. Exact diff review and strict focused SwiftLint (zero violations) pass. Source parity audit still exits1, now reporting precisely the five factories above; evidence `/tmp/t1734-schema-audit-d4dcb9b.json`. Models are present, but source parity and all current-source compilation/runtime GREEN evidence remain pending.++Parent designated this branch sole writer for the exact four list-only additions in MCPWritePersistenceProbeTests, ServiceProbe, FoundationProbe and Probe, confirming no active competing edits. This grants registration additions only; broader write/configuration/guard ownership is unchanged. CoordinatorProbe remains pending separate T-2384 confirmation. No heavy verification is scheduled by this handoff.++Commit `3572ef4d67f3684f7f29b70ad5418580b58e5f24` applies exactly those four hunks. Strict focused SwiftLint reports zero violations across four files; exact diff review confirms unchanged configuration, test behavior and historical seed-old five-model schema. Isolation source configuration guard passes. Static parity audit exits1 with only `tests/mcp-write-probe/CoordinatorProbe.swift` missing, saved at `/tmp/t1734-schema-audit-3572ef4.json`. That last factory is untouched pending its grant. No compilation, runtime or live operation occurred; task2's local and external GREEN gates remain outstanding.++Parent relayed T-2384's explicit final list-only CoordinatorProbe grant, confirming no competing edit. Commit `1f41201cd3921c2e5e6dcdd686d23c0470d426b7` applies exactly that addition, leaving coordinator behavior, configuration and cleanup unchanged. Strict focused SwiftLint reports zero violations; exact diff review, isolation source guard, queued helper AST checks and diff checks pass. Source parity audit now exits0, with both model files present and no missing current factories; evidence `/tmp/t1734-schema-audit-1f41201.json`. Manual mode review confirms Probe's historical seed-old schema still excludes receipt/link entities; isolation historical controls remain graph-free.++All source-owner handoffs are resolved. This is source readiness for the next parent-assigned local migration GREEN slot, not a passing build or runtime result. `migration-next-tests.md` now specifies a fresh guarded shared Debug build, runner-owned signed preflight, four serial closed-store stages with byte preservation/zero graph rows, then the three expanded metadata/control cases using the same preflighted base run file and a fresh result path. Models/macro compilation and actual eight-entity migration remain unverified. Prior offline results do not cover changed model/compile-list inputs. No heavy run, CloudKit activation, signing change, server-schema publication or live operation occurred; the separate external development gate and task2/task3 dependency remain binding.++## Local task2 migration GREEN — exclusive-slot result++Parent released the exclusive slot after T-2382 drain for immutable source `aa5f56a7744c0dc8f09e974be8d9b8944982d822`. Fresh private evidence/DerivedData root `/tmp/t1734-green.Zf1DYx`. Locked-package shared Transit Debug build-for-testing exits0, compiling the new model macros and migration fixtures. Runner-owned fresh signed-unit preflight passes: exact me.nore.ig.Transit.development host, valid signature, get-task-allow=true, no iCloud/push/App Group entitlement, unit-test persistence, startup attestation and only the allowlisted unit target. No UI test is launched.++Closed-store runner exits0. Seed PID67410, legacy PID67446, upgrade PID67456 and final reopen PID67469 each execute exactly one passing non-skipped case with xcodebuild exit0 and recorded hostDrained=true. Each stage uses a distinct host, with both path aliases and prior exact PID checked before advancement; no individual stage claims it alone proves closure. Original pre-save raw fields/receipt bytes and physical duplicate task identities remain preserved through both six-entity legacy and actual eight-entity upgrade/reopen. Upgrade/reopen observations report both link entities present. Read-only physical SQLite counts after each show TaskLinkOccurrence=0 and TaskLinkRemovalEvidence=0.++Separate metadata/control run using the same freshly preflighted base run file exits0. Both parameter argument nodes (TaskLinkOccurrence and TaskLinkRemovalEvidence) pass scalar field/type/default-or-optionality, no uniqueness and no relationship assertions; the saved-state raw-field/receipt/physical-duplicate control also passes. metadata-summary.json top-level totalTestCount/passedTests=2 counts declarations; its per-device passedTests=3 and metadata-tests.json's two explicit Arguments nodes plus control establish all three expanded cases. Failed/skipped counts are zero. XCTest's zero legacy cases is distinct from the executed Swift Testing cases.++Retained artifacts include build/runtime logs and exit statuses, fresh signed preflight/base and stage xctestrun files, all five xcresults, per-stage drained summaries, upgrade/reopen empty-graph counts, metadata summary/test tree, static source audit and `preserved-evidence-sha256.json` (177 retained files). Synthetic SQLite/WAL/SHM, original manifest and four observations remain at `/Users/arjen/Library/Containers/me.nore.ig.Transit.development/Data/tmp/T1734Closed-B455DB2A-A6C3-4361-A2E5-E1508E3F75ED`. No store cleanup or deletion occurred. Initial parallel metadata-report extraction collided while xcresulttool materialized its cache; sequential escalated extraction succeeds. This evidence-extraction issue did not affect the completed runtime cases. Destination/App Intents service warnings are incidental.++Independent escalated final-process-census.json records all five host PIDs (including metadata PID67551) absent and no owned build/test process remaining. No stall, sampling or bounded cleanup was required. Exclusive heavy slot is released after confirmed drain. This is verified local migration/metadata GREEN for the recorded source, not current offline-probe runtime coverage or real CloudKit compatibility/deletion/convergence evidence. The substantive opt-in Development fixture remains uncompiled/unexecuted and its account/host/schema prerequisites separately uncleared; task2 stays in progress and task3 blocked. No CloudKit account/schema operation, client activation, live task mutation, push/main merge or canonical .kiro change occurred.++## Explicit owner deferral to T-2402; reviewed local task2 completion++Owner `Sentinel_42e647a603ac81918cbb949ed1ca67bb`: "The CloudKit test isolation can be a separate ticket. Proceed without it for now". Parent created and freshly verified **T-2402 — Set up isolated CloudKit integration testing**, Transit Idea/Research, through the installed UI. No duplicate live ticket write occurred here. Requirements/design/tasks/prerequisites and review evidence record this exact scoped amendment; optional smoke source remains uncompiled/unexecuted and account/schema/client actions held. Earlier external task2 blockers above describe the pre-amendment scope, not the current approved dependency.++Internal critic reviewed the amendment against preserved aa5f56a runtime/source-parity evidence and confirms task2 may complete on its amended local boundary with no additional owner approval. No other requirement, foundation ownership or DAG edge is weakened. Rune completes task2 and starts task3, retaining task4's mandatory supported atomic validation-to-save proof against peer-context/import commits. Graph writes stay unavailable if that mechanism cannot be demonstrated. Source-only task3 preparation is delegated; T-2383 holds the heavy slot, so no competing compiler/build/runtime job is launched. No phase changelog is due while the remaining stream tasks are unfinished.++## Task3 source preparation and exact local feasibility queue++Test-owned source `a44d11c7adab3c51053a625c9608ff3d1709707c` adds TaskLinkCommitBoundaryTests.swift; critic-requested explicit PersistenceAvailability(isFallbackStorageActive: false) fixture injection is `ab74a99a684525478fb05b4c32bc7fde1061e1c9`. No production/shared source changes. Five default expanded controls cover pending graph edits excluded from independently opened saved observations, peer endpoint change after model registration, save/encoding failure outcomes preserving saved domain/historical bytes (two argument cases), and exact retained replay bypassing repeated preparation/commit save. The owning containers remain retained, so these controls do not claim process-closed persistence proof. One additional transaction counterexample is explicitly disabled unless T1734_TRANSACTION_DIAGNOSTIC=1; passing it would show an earlier observation becoming stale, never atomicity/graph-write enablement.++Internal critic finds no blocking API/source issue and confirms baseline expectations match the actual legacy coordinator. Focused source lint/ownership/diff checks pass; the final fixture injection passes exact diff review. Compilation, discovery and execution remain unverified. Task3 remains in progress because these prepared controls are not the complete graph-commit RED suite.++Next parent-scheduled focused slot: fresh locked-package guarded Debug build, fresh exact signed-unit preflight, then derive an allowlisted unit-only run selecting TaskLinkCommitBoundaryTests with T1734_TRANSACTION_DIAGNOSTIC absent. Require five passing expanded controls and explicitly account for the one disabled diagnostic rather than interpreting discovery/skip counts as full task3 coverage. Preserve logs/statuses, individual argument results, fixture stores and exact owned host drain. Queue the transaction diagnostic separately, only with an externally bounded isolated host runner that samples its owned PID before bounded timeout cleanup; the environment flag alone does not bound a synchronous peer save. Do not run it through an unbounded shell or ordinary unit suite.++Atomic feasibility is approved internal work, not an external waiting condition or a request for further product approval. Continue its source/tests and request only heavy-slot scheduling and ordinary owner integration coordination. Read-only T-2384 committed checkpoint 011660ec6fca617e474ee056c5bcf95dc7ee4d9d exposes execute(...batchPolicy:) with validateBeforeApply before command.apply. Coordinate its exact MCPWriteCoordinator.swift, MCPWriteCoordinator+Outcomes.swift, MCPWriteOutcome.swift and MCPBatchWritePolicy.swift dependency handoff before shared edits; do not import its unrelated dirty task5 source. The existing callback does not prove exclusion of peer/import commits before save. The subsequent real seam must enclose authoritative saved refresh, complete graph validation and terminal domain/result commit; no generation-check/MainActor-only substitution. T-2384 now holds the heavy slot. No heavy job, account/schema/client operation or live ticket write ran here; T-2402 remains the separately deferred CloudKit work.++## Separate bounded transaction diagnostic prepared++Commit `64e1c9b6825beb78496e1da950aa56d9d5664a3c` adds run_commit_diagnostic.py and narrowly extracts prepare_unit_run.py's unchanged signed-host/unit-only validation into validated_unit_run. Default migration output names, exclusive writes, selection and startup guards remain intact. The diagnostic helper revalidates exact development signing/entitlements/host/unit-test mode, selects only primitiveTransactionEarlierObservationCanBeInvalidatedByPeerSave(), sets its explicit opt-in marker and requires fresh output paths. Default invocation prepares only; it has not been invoked.++Future separate assigned-slot command: `python3 tests/typed-task-links/run_commit_diagnostic.py BUILD_PRODUCTS --run`, using the fresh build's absolute Products path after the default controls and with untouched diagnostic outputs. Do not prepare first then execute against those consumed output paths. The run has a 60-second diagnostic deadline, bounded exact owned-host/child sampling before termination, identity rechecks, canonical path-alias/PID drain checks and fail-closed unknown-host attribution. Exception handling bounds the known Popen child without signaling unattributed processes. No global kill or store cleanup occurs. Sequential retained summary/tree extraction must establish exactly one non-skipped passing case with the exact diagnostic identifier before writing success; results explicitly set atomicityProof=false and counterexampleObserved=true.++Root and internal critic review find no remaining source blocker after environment-reference, absolute-child-path, fresh-output and exact-case-identity corrections. AST/diff checks pass. No compiler, build, host, sampler, signal or test-result command was executed by this preparation. Wrapper behavior and test discovery remain unverified; task3 and the mandatory graph atomicity gate remain incomplete. Parent has queued the guarded five-control job after T-2384's fixture retry/drain and is coordinating the exact four-file baseline. These are internal scheduling/integration steps under existing approval, not another product-permission gate.++## Task3 controls and primitive counterexample — actual isolated results++Parent assigned the exclusive slot after T-2384 drain for pinned source `27fa36e3a9b4614989f052580e16d39f3a4efa61`. Fresh private evidence/DerivedData root `/tmp/t1734-commit.3ZjIQ2`. Guarded locked-package shared Debug build exits0 and compiles TaskLinkCommitBoundaryTests.swift. Signed-unit validation passes exact development identity/signature/safe entitlements/unit-test persistence/startup guard and removes UI targets. No live CloudKit/account/data operation occurs.++Two method-only run-file filter attempts exit0 but discover zero tests (hosts PID97344 and PID97593); retained summaries correctly reject those outcomes as selector prerequisites, not control PASS or behavioral RED. A fresh suite-level control run with explicit only-testing CLI exits0 and executes all five expanded controls successfully in host PID97823: pending graph edits excluded from saved observation; peer endpoint change visible through a fresh independently opened container; save and encoding rejection cases preserve saved domain/historic bytes; exact replay avoids repeated preparation/commit save. The primitive diagnostic remains intentionally disabled/skipped in this run. Top-level summary counts four passed declarations plus one skipped; per-device results report five passed expanded bodies plus one skipped. controls-tests.json retains exact declarations and save/encode argument nodes. No unsupported process-closed or graph-atomicity claim follows.++The separate reviewed run_commit_diagnostic.py invocation exits0 within its 60-second budget, using the exact method's CLI selection and host PID98090. Summary/tree establish precisely one passed, non-skipped primitiveTransactionEarlierObservationCanBeInvalidatedByPeerSave() case. Inside the transaction closure, an earlier endpoint observation validated Done, then the independent peer context saved Abandoned and the source write after earlier validation still persisted; fresh saved observation sees both. Result explicitly records counterexampleObserved=true, atomicityProof=false and hostDrained=true. This refutes the simple earlier-observation/transaction wrapper as a sufficient guarantee; it does not rule out every supported alternative or enable graph writes.++Final independent escalated process census records all four host PIDs absent and no owned build/test process remaining. No timeout, sampling or cleanup was needed; the exclusive slot is released promptly after drain. Retained artifacts include fresh build/preflights/run files, both zero-discovery attempts, successful control and diagnostic xcresults/logs/counts/test trees, wrapper result, final census and preserved-evidence-sha256.json (177 files). Six synthetic T1734Commit UUID stores/sidecars remain under the development host's private Data/tmp, listed in preserved-synthetic-fixtures.json; no store/evidence deletion occurred. App Intents service/destination warnings remain incidental.++After runtime drain, parent-authorized source-only baseline integration is `327390ad64f431349b2eb5d34800e17cc80ee1e0`. Tested e26efd4d2ce0ba534d2e4168aadd13cac6fb0ebe manifest and exported current hashes were verified before import; all four authorized coordinator/Outcomes/Outcome/policy blobs match afterward. Three files change; MCPWriteOutcome.swift already matched. No other owner sources, fixtures or registrations change, and T-2384 retains editing ownership. Source dependency inspection/diff checks pass with no additional gap; this newly imported baseline has not built or run in this branch. Existing results remain pinned to 27fa36e, not attributed to the post-import source.++Task3 remains in progress: the next approved internal work is deterministic full graph/dirty-context/receipt boundary RED through the real clean-policy and saved-validation/commit seam, followed by task4's mandatory supported-mechanism proof. Keep graph writes unavailable until that proof; no new product permission is required for ordinary source/tests/scheduling. T-2402 remains deferred and unexecuted; this local result does not activate CloudKit or promote schema.++## Task3 protected-policy fixtures and write-first prerequisite — source preparation++Source commit `0ecb78fb415b9030264b4a35b5d6e935c562ba69` adds eight expanded default controls through the actual imported MCPBatchWritePolicy/coordinator: dirty entry, dirty preparation success/error, dirty retained replay, fresh saved endpoint rejection, and staged domain/graph/terminal receipt save/encoding/recovery failures. Graph staging is expressly fixture-only; no production graph adapter exists yet. Two separately opt-in endpoint/cycle interleavings retain genuine RED expectations after a peer commits between validation and the actual commit save. This source has not compiled or executed. Independent critic found a missing `try` on the abort prerequisite's throwing assertion and a sidecar-observation gap in the dirty-entry no-reservation claim. Corrections `7dc0ba6` and `05f0d5e08663fbcd9fbbacaa4a2958d4811b3ce8` add the throwing-assertion fix, compare actual `guards/guards/*.json` bindings before/after dirty entry, and require a nonempty retained-replay binding snapshot. Focused strict SwiftLint, Python AST and diff checks pass; corrected source still has no compilation/runtime result.++The next supported-API hypothesis is a write-first ModelContext.transaction with an internal save, followed by fresh saved graph reads and final domain/receipt commit. Its smallest prerequisite is the separate `primitiveTransactionInternalSaveMustRollBackOnClosureAbort()` case: save a fixture-only marker together with domain/edge/removal changes inside the closure, throw, then observe from a newly opened container that all saved originals remain intact. The existing diagnostic runner now allowlists `--diagnostic internal-save-abort`, clears other diagnostic flags, retains exact one-case summary/tree/log evidence and bounds owned-process cleanup. PASS establishes abort durability only; an exact failing case retains a nonzero outcome and requires issue inspection before disqualifying this candidate. Neither result proves graph atomicity or excludes other supported mechanisms.++Read-only installed SDK inspection confirms ModelContext exposes transaction/save/rollback but no public predicate-lock, read-set conflict registration, underlying managed-context accessor or expected-read-set save parameter. DefaultStore is final; DataStoreSaveChangesRequest contains inserted/updated/deleted snapshots and editingState. These facts constrain the present SwiftData default-store approach without proving all supported approaches impossible. A Core Data coordinator queue alone does not cover an independently opened coordinator, and object conflicts alone do not cover new dependency/duplicate-ID phantoms. No private bridge, custom store protocol or distributed guarantee is introduced. If abort durability passes, subsequent bounded worker-owned probes must still prove fresh reads, existing-row and phantom exclusion across independent containers, successful complete domain/edge/removal/receipt atomicity, and rollback. If it fails, inspect the concrete persistence result before proposing a material architecture change.++Internal critic verified both corrections and the actual sidecar path/nonempty replay baseline with no remaining source blocker. Queue only a fresh guarded Debug build and signed unit preflight against the corrected clean source, eight default policy controls with diagnostic flags absent, then the exact separately bounded abort case: `python3 tests/typed-task-links/run_commit_diagnostic.py FRESH_BUILD_PRODUCTS --diagnostic internal-save-abort --run`. Heavy execution requires the parent's exclusive slot assignment; source readiness does not reuse the earlier binary or attribute prior results to this changed baseline. Task3 and the graph-write safety gate remain incomplete; no ordinary product approval is pending.++## Task3 eight policy controls and internal-save abort — actual assigned-slot results++Parent assigned only the fresh guarded build/preflight, eight policy controls and separate exact internal-save-abort diagnostic at pinned source `c8bbd127a2b862961050eb079a692fc668d4aa95`. Private evidence/DerivedData root: `/var/folders/11/v0tnfm294kd9c6zll_ncmpkh0000gn/T/t1734-abort.wd0req0i`. Fresh locked-package shared Debug build-for-testing exits0, compiling the corrected fixtures and imported coordinator baseline. Signed-unit preflight verifies the exact development bundle/signature, get-task-allow, absence of CloudKit/push/App Group entitlements, unit-test persistence and startup isolation attestation. The suite runner clears all three opt-in flags from both run-file and inherited process environment. The shared build compiles the UI target but no UI test launches.++Policy controls exit0 in host PID7228. Retained summary reports five passed declarations and one disabled opt-in declaration; per-device expanded bodies are eight passed, zero failed and one skipped. The test tree independently retains all dirty-entry, dirty-after-preparation false/true, retained-replay, fresh endpoint and save/encode/uncertain failure arguments as passed. Both opt-in endpoint/cycle race bodies remain unexecuted under this grant. Saved-domain, graph participant, historical-byte and reservation-binding assertions are control coverage through the real imported policy/coordinator, not a graph-adapter atomicity certificate.++The reviewed separate `--diagnostic internal-save-abort --run` executes exactly one non-skipped case in host PID7406. Xcode exits65 and the wrapper correctly exits1, retaining `exactCaseFailed=true`, `abortDurabilityObserved=false`, `atomicityProof=false`, summary/tree/log and six failed expectations. The internal save returned and the injected closure abort was caught (the throwing prerequisite assertion passes), but a newly opened saved observer sees marker state `fixture-flushed` and terminal JSON instead of accepted/nil; unchanged source-domain and original edge assertions fail; the inserted removal evidence remains and its count is2 instead of1. The historic receipt preservation assertion does not fail. This is a behavioral abort-durability failure, not a fixture exception or discovery failure: this write-first/internal-save rollback candidate is disqualified. It does not prove all supported approaches impossible. No worker/phantom probe is justified for this already-disqualified candidate, and graph writes remain unavailable.++Both hosts exit and drain normally. The independent escalated final census records no owned build/test/compiler process and both host PIDs absent; the exclusive slot is released immediately after this check. No diagnostic deadline, teardown stall, sample or termination was needed. Evidence retains exact source/build command/log/status, signed preflight, run files, argument-level results, wrapper status, six issue excerpts and process census. Nine new synthetic T1734Commit fixture roots with their store/WAL/SHM/sidecar files are preserved and hashed; no store or original evidence is deleted. Internal critic independently reviewed retained results and confirms this specific candidate's rejection while preserving the limit on universal claims. No live task write, account/client/schema operation, production/shared source change, push or main merge occurs. Task3 remains in progress and task4's supported local validation-to-save mechanism still requires evidence or a concrete material architecture proposal; the observed failure alone does not authorize a design change.++## Supported-fence architecture assessment — recommendation only++Parent requested bounded source-level investigation after the abort result, with no speculative app probes and T-2383 holding next heavy priority. Recommendation: preserve the approved guarantee and keep the graph-write gate closed. No supported fence has been identified for the existing SwiftData DefaultStore/coordinator that covers the complete saved graph predicate through terminal save against independently opened containers and imports. This is a source/API assessment of the current architecture plus two precise runtime counterexamples, not a proof that every conceivable supported architecture is impossible. Independent peer review agrees with this boundary.++Installed SDK evidence: `SwiftData.swiftinterface` exposes ModelContext transaction/save/rollback but no public read-set/predicate-lock registration, merge-policy control or underlying managed-context accessor; DefaultStore is final, and DataStoreSaveChangesRequest contains inserted/updated/deleted snapshots plus editingState. CoreData `NSManagedObjectContext.h:141–142` offers detectConflictsForObject for unchanged existing objects, while `:216–218` explicitly says query generations cover fetched data, not saves. `NSPersistentStoreCoordinator.h:316–320` describes its own queue; that queue does not serialize independently opened coordinators. Public notification objects do not supply a documented actor-safe SwiftData context-to-coordinator control bridge. [Apple's Core Data change-management guide](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/ChangeManagement.html) describes edited-object optimistic conflicts; extending that to existing read rows would still omit newly inserted cycle/duplicate-ID phantoms. These conclusions do not depend on hidden framework internals.++The current coordinator's `commit` calls validateBeforeApply, apply, stageTerminal and save in sequence. Its sidecar lock covers cooperating retry-binding access, not every graph-affecting writer: TaskService/ProjectService save independently, and platform imports or other containers do not participate in an app lock. Rechecking generation before save leaves the same interval; pinning query generation only makes observation stable; touching existing rows does not cover absence predicates; actor/queue/sidecar serialization covers only participants. Post-commit rollback cannot restore a failed protected-write contract or undo peer commits. Neither a direct Core Data substitution nor a guard record establishes a fence unless every relevant writer participates or a store-level predicate check is atomic with the originating write.++The smallest preserving architecture contract is one authoritative local persistence transaction that (1) obtains fresh saved task/endpoint/complete dependency/cardinality/removal evidence, (2) checks revisions, identities and invariants including absence predicates, and (3) saves the complete task/link/removal/terminal receipt change together or rolls it back before publication. Every local graph-affecting path, including imports and independent containers, must pass through its exclusion or commit-time predicate-validation boundary. Preserve the existing coordinator's key/replay/uncertainty semantics; do not create a second receipt engine or put links and receipts in separate stores. A custom SwiftData store or explicitly owned persistence backend is a possible implementation direction, not selected or proven. [Apple's custom-store session](https://developer.apple.com/videos/play/wwdc2024/10138/) documents backend replacement and identifies migration/history/CloudKit sync as DefaultStore features. Replacing it therefore needs explicit migration, all-writer ownership, UI observation/history and sync/import design; automatic CloudKit integration cannot be assumed. This is a material foundation design change, not an ordinary T-1734 policy callback edit.++Exact weaker alternative, requiring owner approval if chosen: guarantee serialization only among cooperating application writers, with graph validation describing the saved observation taken before commit. A peer/import commit during the interval could still cause the originating write to commit against a changed endpoint, introduce a cycle or duplicate target, or invalidate a removal selector; later diagnostics may identify the fault, but rejection/no-domain-effects at the originating commit would no longer be guaranteed. Even if domain and receipt still save together, that is a change to the approved local guarantee, not merely the already-excluded global CloudKit guarantee. No such reduction is adopted. A weaker proposal must enumerate participants before review: at minimum the MCP create_task/update_task/update_task_status/add_comment routes (including batch dispatch), native TaskService creation/update/status/abandon/restore/project-change/deletion saves, native graph editing, removal-evidence maintenance, and any UI autosave path affecting covered data; it must explicitly identify which independent-container/import paths remain outside. Internal critic reviewed the assessment and found no source blocker, with this participant enumeration required for any executable weaker proposal. Next design review should choose a preserving persistence-foundation revision or explicitly amend that guarantee; until then fresh graph writes remain unavailable and dependent implementation stays gated. No additional app/compiler probe, source promotion, task transition or product approval request occurred in this assessment.++## Owner-approved simpler guarantee — amended document review++Recovered the same worktree after the usage interruption: five amended spec documents were uncommitted at `5fde620`; owned process census was empty. Preserved all work and previous run evidence; started no build, compiler or app probe. Owner `Sentinel_c95239aefa6481919303c2353b8a9e9c` explicitly chose the simpler guarantee after parent explained the race and persistence-redesign alternative. Requirements4.2/4.5/5.5/8.2, design commitment/risk/testing contracts, tasks3/4/12/14 and ADR4 now consistently limit coordination to participating shared MCP coordinator writes and report outside saved inconsistencies. Stronger local all-writer/import predicate-fence proof is not required; owned task/link/removal/receipt saving, dirty protection and receipt-first replay remain mandatory.++Explain-like self-validation: beginner—Transit checks saved links and takes turns for its managed writes; sync or another writer can still change links, and later reads show current problems. Intermediate—the final shared-coordinator MainActor validation/apply/stage/save phase has no await, clean checks guard preparation, and one originating store save contains owned changes plus terminal receipt; outside contexts do not participate. Expert—validation is a point observation rather than serializable predicate isolation; phantoms and independent imports can invalidate it before commit, retained receipts still certify their immutable originating outcome, and actual saved projection diagnoses available faults without asserting historical race attribution. Self-review corrected a potential task3/projection DAG circle and distinguished valid status assessments from invalid evidence. No new product question emerged.++Design critic reviewed first; two subsequent internal peers reviewed correctness and scope/maintainability via the documented unavailable-external-review fallback. All review blockers/clarifications were addressed; both peers approve readiness for final document review. Rune validates 22 stable task IDs with unchanged statuses/edges/streams, two complete and task3 in progress, and all39 acceptance criteria covered. Expected two-space Markdown hard breaks are retained per requirements skill; diff validation passes with blank-at-eol excluded. Source tests remain unchanged under this spec-only amendment: old counterexamples/abort failures are preserved, not relabeled passing guarantees. Task3 source work will recast the opt-in race assertions as limit observations, add participating-phase/fresh-saved-resolution controls and preserve existing eight policy controls; actual graph diagnostic tests follow tasks5/6 and integrated21/22.++`send-md-to-phone` exited0 and reported sending exactly five amended review documents: requirements.md, design.md, tasks.md, decision_log.md and prerequisites.md, received-name prefix typed-task-links. No routine implementation report, test source or raw runtime evidence was sent. Local Starwave iteration instructions require final amended-document approval through the parent; the simpler guarantee choice is already approved and is not asked again. Task statuses are not advanced from this amendment alone. CloudKit setup/live verification stays deferred to T-2402. Next executable source step after that document gate is task3's narrow actual-coordinator test amendment; heavy runs still wait for the parent-assigned slot after T-63 drain. No live task/data/account/settings action, main/push/merge/deployment or canonical .kiro mutation occurred.++## Amended spec approved — task3 source continuation++Owner `Sentinel_08cb318218788191a85da25d1206979f` explicitly approved checkpoint `a64e595c439db6d62e46c85888f37130d53269fa` after the final amended-document request. Approval is recorded in requirements/design/tasks metadata and ADR4; historical pending-review text above records its earlier checkpoint and is superseded by this approval. Continue task3's participating coordinator controls/allowed-race fixture amendment then task4's minimal owned-save policy integration. Do not require an all-import predicate fence or CloudKit setup; preserve dirty drafts, receipt/replay and truthful outside-race limitations. T-2382 owns the current heavy slot; no build/test is launched. Existing test source agent is delegated source-only work, with owner-directed production handoff proposals rather than edits to T-2384-owned files.++## Task3 amended boundary source ready; task4 owner proposal remains unapplied++Approved-document metadata is committed at `c2b77ccd9f487d72cbaef2df3a767f787b10b0ab`. Single-stream source delegation follows the local make-it-so workflow; Rune identifies task3 in progress (available streams is empty because that stream is already active). Stable source `a35906535ef0e352f2a90eeb810cfcf4f52301db` contains the original eight default protected-policy controls, five new participating-boundary cases and two separately opt-in outside-writer observations. Default inventory is13; prepared focused inventory is15 with zero intended skips. Primitive transaction/abort diagnostics and preserved raw failures are unchanged and excluded from this run.++`TaskLinkParticipatingBoundaryTests.swift` adds an actual existing-SUT stale-source expectation through the default policy without a custom freshness callback, fresh endpoint-revision and before-apply cycle rejection controls, complete originating graph/domain/removal/terminal-receipt success, and deterministic same-coordinator MainActor phase-order observation. The stale-source case is anticipated RED until runtime establishes its result; no cached-value defect or fix is claimed from source alone. The two outside-writer cases now expect the allowed originating commit and byte-identical retained replay, independently observing changed valid endpoint status or saved dependency cycle. They do not require external exclusion or pretend that fixture graph staging is a production adapter. Actual projection diagnostics remain in tasks5/6 and21/22.++Independent critic verified the source after two narrow corrections: endpoint REVISION_CONFLICT carries currentRecord from the same fresh snapshot and checks rejected replay; the signed preflight recipe includes both explicit suite CLI selectors, avoiding earlier zero-discovery filtering. Strict SwiftLint on both owned Swift files, helper Python AST and diff checks pass. No compilation/runtime occurs, and task3 remains incomplete. The parent holds the heavy queue; T-2382 owns the current full macOS slot.++Next concrete job: fresh guarded locked-package shared Transit Debug build, then `python3 tests/typed-task-links/prepare_participating_run.py FRESH_BUILD_PRODUCTS` exactly once, followed by its recorded expectedCommand in the parent's bounded sampling/drain wrapper. The command selects both TaskLinkProtectedBoundaryTests and TaskLinkParticipatingBoundaryTests with explicit only-testing CLI filters, and the run file enables only T1734_OUTSIDE_WRITER_OBSERVATIONS. Sanitize inherited T1734 flags at launch. Retain all15 expanded outcomes, exact stale-source expectation issues if any, raw fixture stores and owned host drain; do not interpret exit0 or a top-level declaration count without the argument tree. Do not include primitive probes, UI tests, CloudKit or other ticket suites. Source readiness does not reuse the earlier binary or independently grant execution.++`tests/typed-task-links/participating-commit-scope-proposal.md` records an unapplied concrete interface/owner-path proposal if fresh application context is needed: optional factory in MCPBatchWritePolicy, fresh same-container autosave-disabled context/services and revalidated accepted receipt in MCPWriteCoordinator, owned rollback/rejection and expiry from its fresh terminal receipt. Keep validateBeforeApply last in the initializer to preserve trailing closures, and retain existing format/replay/uncertainty semantics. A nil factory preserves old behavior and cannot fix the current default-policy expectation. Task4 must configure the real participating factory under that expectation and all graph-covered standalone/per-item routes before GREEN; link-only opt-in wiring is insufficient. Current standalone MCPToolHandler calls with nil policy and later startup/adapter wiring need owner-directed integration; the limited imported base has no batch runner, so its exact caller path must be refreshed from the approved merged owner source. No new coordinator/store, independent-import fence or persistence redesign is proposed. Runtime evidence determines whether this candidate is needed; no shared production source is edited or owner grant inferred here.++No task is completed merely from these source changes. No new product decision or approval gate is pending; remaining blockers are the scheduled focused runtime result and explicit shared-file integration ownership. No routine report/phone delivery, live task/data/settings/account operation, push/main merge/deployment or canonical .kiro change occurs.++## T2384 conditional owner review — minimum patch request ready++Read the exact owner review at `/Users/arjen/Documents/Codex/2026-10-03/task-4/reviews/t1734-participating-commit-owner-review.md`, pinned to owner source `fc1b7d9d034cdcee1af7b822d3423c8830e01722`. That review conditionally accepts the fresh participating scope and retains coordinator/policy ownership; it does not authorize or apply a patch. Doc-only commit `15aa0d9b57c22a91fc1450f44c4e4d438250c7d0` updates the existing proposal with the minimum owner request and a 17-row future acceptance matrix.++The proposed sealed wrapper constructs all four services internally from one supplied context and the original task/milestone allocator instances, with default context fetchers and no arbitrary-services initializer. The coordinator must select and retain the fresh same-container autosave-disabled context, validate/refetch the exact receipt, replay a fresh terminal before graph validation, and parameterize every rejection/recovery/save branch with the owned receipt scope. Foreign durable lookup models are read-only recovery evidence, never staging inputs. Missing/inconsistent evidence retains original-key reconciliation; immutable replay, dirty protection and legacy/default-nil behavior remain explicit. The policy request preserves the current typed `onPendingEditsStop` and initializer order factory, observer, validator.++Independent correctness review accepted the sealed construction and lifecycle direction; the critic subsequently found no concrete blocker in the completed proposal against all owner conditions. This establishes document readiness only. The coordinator owner still agrees shared-wrapper interface placement and schedules its isolated patch on the current owner base after its active Task9/10 handoff; T1734 supplies feature-local factory/guards/tests against that interface. Startup/standalone routing needs its separate owner handoff, and T2384 wires its actual per-item seam. No older coordinator replacement or invented batch runner is requested.++The queued 15-case source and runner remain identical to `de6ea490d802f0b34302a27cc667134fb2407a12`; the only intervening change is the proposal document. Focused runtime remains queued under parent scheduling, with no RED/GREEN result asserted. No source factory, shared production change, build/test/compiler, task transition or routine phone delivery occurred. No new product decision or spec approval is pending.++## Approved 15-case participating boundary run — all pass, no stale-source RED++Parent explicitly assigned the exclusive slot after T2384 Task9 and T63 drain. Actual source HEAD was `ce11ea7a69c7add00d95a1bc076150992e73f048`; executable source and helper diff against queued `de6ea49` is empty. Run root: `/var/folders/11/v0tnfm294kd9c6zll_ncmpkh0000gn/T/t1734-participating.uipq6w23`. Fresh locked-package shared Debug build exits0 using private DerivedData/cache/tmp paths and ad-hoc development signing. Signed preflight passes exact development host identity/signature, get-task-allow, no iCloud/push/App Group entitlements, unit-test persistence and startup attestation. Only the two approved unit suites launch; all primitive flags are cleared and outside-writer observations enabled.++Actual xcodebuild exit0; argument-expanded case tree and device summary establish **15 passed, zero failed, zero skipped**. The top-level summary counts11 test declarations; this is not the expanded inventory. Eight protected controls, five participating cases and both outside-writer race observations pass. `existingPolicyMustRejectChangedSavedRevisionDespiteRegisteredSource()` also passes with the existing `.init()` policy. Read-only inspection of its saved synthetic receipt confirms `REVISION_CONFLICT` with currentRecord.name `outside saved update`; it preserves that saved peer change. No stale-source behavioral RED was reproduced, and this fixture does not justify a fresh-context fix by itself or establish the future scoped receipt/recovery/factory/caller acceptance matrix. No production factory has been implemented.++Owned host PID98031 exits normally; bounded wrapper and final process census prove it absent with no matching run host, compiler or xcodebuild left. No deadline, sample or signal is needed for the successful run. Heavy slot released immediately. `expanded-case-inventory.json`, summary/tests/run logs, signed preflight, exact command/source HEAD, launch wrapper and run-outcome.json are retained. All15 synthetic fixture directories are copied without altering originals;90 preserved files have SHA256 hashes. Original independent-writer/primitive evidence remains unchanged.++One earlier build-only attempt at `t1734-participating.cw9zme0w` stops before compilation because an outer sandbox prevented SwiftPM's nested sandbox application. Its build log/status are retained; no host launched and process drain was checked. The successful retry uses the existing documented private-cache locked-package build recipe and unchanged signed startup/unit-host safeguards; no settings or global permissions are changed. No repeat heavy run, source patch, task completion/transition, phone delivery, CloudKit action, live data operation, push or main merge occurs. Parent/coordinator owner should assess the actual all-pass result against the proposed scope before its scheduled patch; no new product/spec approval is requested.
specs/typed-task-links/isolation-integration-plan.md Changed +40 / -0
diff --git a/specs/typed-task-links/isolation-integration-plan.md b/specs/typed-task-links/isolation-integration-plan.mdnew file mode 100644index 00000000..a8e2c280--- /dev/null+++ b/specs/typed-task-links/isolation-integration-plan.md@@ -0,0 +1,40 @@+# T-1734 independent migration-test isolation integration++Status: containment delivered the narrower isolation-only `3194e5a64dedb004dbfca3666bf590a552b676ee` on T-1734 base `594c549`; consumed as `e1c1ac4`. No app build/host run or shared ownership transfer occurred. The source comparison below records the initial integrated-envelope proposal; the owner-delivered component is the selected integration.++## Exactly what task1 needs++The prepared `TaskLinkMigrationTests` imports Foundation, SwiftData, Testing and Transit. Its functional dependencies are the existing six models (`Project`, `TransitTask`, `Comment`, `Milestone`, `SyncHeartbeat`, `MCPWriteReceipt`) and `TestModelContainer`'s default/custom-schema initializers. All exist at base `201205bd`; those models and `TestModelContainer.swift` have no diff between that base and `b500543`.++The fixture does **not** call T-63 capture/freshness/publication, T-2382 portfolio/reusable views, T-2383 result encoding/protocol, or T-2384 batch/coordinator policy APIs. It can run its initial capability RED without all four feature branches merging. Future graph mutation/read integration remains separately dependent on those foundations and feasibility gates.++Its runtime host nevertheless constructs the application. The isolated App startup at the verified checkpoint binds `MCPReadAppDependencies.make`, `MCPReadCoordinator`, `MCPToolHandler(readService:readCoordinator:)` and `MCPServer(readCoordinator:)`. Taking only App/project/isolation files onto the old base leaves that transitive startup dependency missing. A custom isolation-only App rewrite would be new unverified owner work; an old containment App copy must not replace the integrated read plumbing.++## Compared immutable source++| Checkpoint | Role / finding |+| --- | --- |+| `594c54987146b39257f26b1d152999fb452e8f6b` | Current T-1734 checkpoint; only production-tree difference from main base is new migration test source. |+| `201205bd4e786c7f152d8f99006b37da7da888c7` | Exact common ancestor of T-1734 and verified T-63 component. |+| `b500543369ebbd53f01634fa829bf74a8fceabe5` | Verified integrated Stage A source, already consumed by T-2383; includes development isolation plus required read startup plumbing. Upstream smoke/routing evidence is not T-1734 combined-source verification. |+| `9ba4297` | Containment's cumulative verified component. App, Services, Configuration, project/schemes, Makefile, isolation runners and smoke fixture are byte-equivalent to `b500543`; no App/project adaptation is proposed. This alone is not the source dependency closure on the old base. |++Read-only `git merge-tree 201205bd HEAD b500543` reports only `specs/OVERVIEW.md` changed on both branches, with two conflict hunks. Preserve both rows and both file lists. The prepared migration test has no incoming overlap. The local preview is `/tmp/t1734-b500543-merge-preview.txt`; it performed no merge.++## Selected owner-delivered integration++Containment supplied the isolation-only adaptation from established `9ba4297` wiring as `3194e5a64dedb004dbfca3666bf590a552b676ee`, based exactly on T-1734 `594c549`. The parent selected this component instead of the initial full `b500543` envelope proposal. It preserves T-1734's existing MCP/read constructor plumbing and avoids absent T-63 interfaces. The original-base App adaptation, project/target/scheme/entitlement changes and startup guards were applied by their owner; no whole App blob replaced the current source.++Consumed at `e1c1ac4`; all delivered manifest hashes outside the fixture-only lint correction match. Models, TestModelContainer, MCP/read/write sources and the migration fixture were untouched by the component. Existing graph foundation ownership remains intact. Fixture-only lint correction is `d2cc0c6`; branch-local development configuration guard and full strict lint pass (406 files, zero violations). These are source checks, not branch-local runtime verification.++Preserve policy resolution before storage, disabled CloudKit counter construction, isolated sidecars, suppressed automatic MCP startup and the six-model receipt schema. No full T-63 or modern adapter integration is implied. Task1 can exercise its independent model/schema/disk-control capability checks on this host; later graph integration keeps its own foundation gates.++## Concrete next isolated job++T-2383 currently owns the exclusive heavy slot. After owner integration, request a slot for a fresh dedicated isolation smoke, fresh shared Transit Debug build containing `TaskLinkMigrationTests.swift`, signed-host/xctestrun preflight, then **only** `TransitTests/TaskLinkMigrationTests` on macOS serially. Use private fresh DerivedData/result paths and locked package versions. The smoke must verify `me.nore.ig.Transit.development`, no CloudKit/push/App Group entitlement, memory-only host persistence, disabled counter adapters and private sidecars. `TransitDevelopment` is not the unit-test scheme.++`verification-readiness.md` contains the exact guarded offline, signed-host and focused migration commands. Helper checkpoint `b9d65b9e483ea59d65ed458851132184dab1331f` adds branch-local signed artifact/xctestrun checks; it has not executed.++Use a new unused result path for any necessary rerun. Expected source enumeration is two declarations/three expanded cases; inspect xcresult and reject zero tests/compile failure as behavioral RED. Missing link entities should produce honest registration-capability RED; the disk control proves saved observation only. Closed-store process-separated migration, development CloudKit verification and complete task1 coverage remain outstanding, so task1 stays incomplete even if this initial job yields the expected failures.++Live Transit mutations, client activation, production schema promotion and deployment remain held. Reports stay local; owner coordination goes through the parent because this execution context exposes no callable thread-messaging tool.
specs/typed-task-links/local-review.md Changed +100 / -0
diff --git a/specs/typed-task-links/local-review.md b/specs/typed-task-links/local-review.mdnew file mode 100644index 00000000..4459c255--- /dev/null+++ b/specs/typed-task-links/local-review.md@@ -0,0 +1,100 @@+# T-1734 final local review++## Verdict and provenance++Ready for publication review. All 22 tasks and all 39 acceptance criteria in the approved local scope are implemented; no mandatory fix remains. Final application/test source is `bbe3a2560584f7fb822aa8006b20f08d22284ce4`, based on freshly verified `origin/main` `e04c1268ee37bd4ae925d4d686954cf2121005c7`. Review covered the full branch at cf33cb25 plus corrective deltas through 81f78e7 and the five-file native delta at bbe3a25. Later documentation commits do not change the tested application/test/Makefile content.++The pre-push-review skill supplied four independent read-only perspectives: reuse, code quality, efficiency, and specification/documentation. Root also reviewed the actual runtime failures, corrections and final native result trees. The pre-push peer reviews were internal. The subsequent PR Pilot workflow publishes this branch diff to GitHub and its configured Claude action under owner approval. The original worktrees, historical evidence and canonical `.kiro` remain preserved.++## Findings and resolutions++| Finding | Outcome |+| --- | --- |+| Advertised schema named nonexistent `batch_task_mutations` | Fixed to shipped `mutate_tasks`; caller contract and wire guidance agree. |+| Graph refetched task population before selected serialization | Fixed by reusing the already fetched complete population inside the capture fence. Original selected malformed-canonical assertion is unchanged and passes. |+| Five legacy project/milestone error surfaces were bypassed | Restored discarded compatibility checks in capture validation order; successful live model values never select returned records. |+| Eight old read fixtures seeded only pending/mock values | Explicitly inserted/saved only intended read seeds; every original assertion, cursor/fetch-count check and dirty-write helper remains intact. |+| Project shape validation could lose precedence to a storage hook | Fixed using the existing extracted selector parser before the hook, with newline normalization. Three actual handler controls assert zero hook calls and exact expected outcomes. |+| Duplicate status catalog, unused apply parameter, repeated preparation scaffolding | Optional low-severity maintenance suggestions; current behavior agrees and cleanup is not required for this feature. |+| Global diagnostic scans | Optional bounded optimization opportunity; existing deadlines/caps remain intact. |+| Native refresh bursts and incoming attribution/duplicate wording | Fixed at bbe3a25: invalidation precedes cancellable 100-ms notification wait; provider/publication guards preserve full saved graph freshness. Incoming labels are Introduces / Duplicated by; association and unknown raw kinds retain their meaning. |++The initial full macOS run's 14 failures and all compile/invocation-only attempts remain preserved. Focused corrective verification passed 170 cases before the final full runs. No test expectation, capacity cap, retry guarantee or unsaved-data policy was relaxed.++## Final verification and evidence++| Platform | Expanded case executions | Native declarations | Outcome |+| --- | --- | --- | --- |+| macOS units | 3,265 passed; five intentional skips | 2,530 passed; five skipped | build/run 0; no timeout; host drained |+| iOS units | 1,403 passed | 1,326 passed | build/run 0; no timeout; host drained |+| iOS UI | 26 passed | 23 passed | unchanged signed products; run 0; no timeout; all hosts drained |++Aggregate: 4,694 passing case executions across final platform runs at bbe3a25, zero failures. Runtime warning arrays are empty. Root independently parsed summary/tree leaf outcomes and exit/drain records. Full lint passed 652 files with zero violations; ownership, create-schema, development configuration and final registration guards passed. Build warnings are pre-existing and retained in the handoff.++The five macOS skips are the two opt-in primitive diagnostics, process-separated closed-store stage, development schema precheck and outside-writer observation. Their earlier targeted evidence or explicit deferral remains separately recorded. The current final iOS run recovered two first-attempt census timeouts with bounded diagnostic retries, retaining the original absolute deadline, ownership checks and fail-closed non-timeout errors. All owned simulators were shut down/deleted. See [pr254-native-corrections.md](pr254-native-corrections.md) for current artifact roots, pins and counts; [final-handoff.md](final-handoff.md) preserves the earlier source separately.++Generic JUnit/coverage data is unavailable: the review ecosystem only detects SwiftPM through a root Package.swift, while this is an Xcode project. No unrelated SwiftPM recipe was executed and no coverage or JUnit was fabricated. Actual native xcresult evidence establishes the platform outcomes above.++## Final critic questions — closed++1. Is published caller guidance accurate? Yes: `mutate_tasks` is the batch tool; link directives remain standalone-only and batches reject them before item/key acceptance.+2. Are final gates evidenced at the actual source? Yes: the original focused compatibility checks passed at 81f78e7, and fresh native focused/build/lint/guard/full-platform checks passed at bbe3a25; later changes are documentation only.+3. Are concurrency and native observation claims truthful? Yes: participating owned local saving is implemented; independent containers/imports can race. Native saved value projection/cancellation is distinct from a fenced retained MCP capture. There is no certified inter-fetch native coherence claim or global CloudKit atomicity claim.+4. Are deferred product boundaries preserved? Yes: live CloudKit verification remains T-2402 and consolidation remains T-2381. Installed-client activation/production promotion is not performed by this local implementation.++## Acceptance-criterion traceability++The independent specification review mapped all 39 criteria to production symbols and behavioral fixtures. The table below preserves that mapping; its formerly pending final checks are now established by the outcomes above.++| AC | Implementation / verification evidence | Assessment |+| --- | --- | --- |+| 1.1 | TaskLinkType, TaskLinkWireRequest closed parser; WireTests exact public spellings, malformed shapes, self-link rejection | Implemented |+| 1.2 | QueryProjection public orientation and QueryBoundaryTests both saved endpoints; native Incoming/Outgoing labels | Implemented |+| 1.3 | Normalized TaskLinkRelation and Plan.validate; inverse/association normalization, already-present no-op, incompatible remove/add, physical multiplicity tests | Implemented |+| 1.4 | OwnedPlan source/endpoint UUID uniqueness and graph all-matches indices; missing/colliding identities, foreign graph closure and cross-project integration controls | Implemented |+| 1.5 | QueryProjection edge UUID/stored endpoints/type/direction/observed label/physical identity; native saved labels | Implemented |+| 2.1 | GraphIndex.assessment direct Done-only blockers and complete evidence; GraphTests Done/Abandoned/unknown status | Implemented |+| 2.2 | Complete proposed graph validation and iterative dependency SCC; PlanTests cycle-closing rejection | Implemented |+| 2.3 | Cycle membership includes physical dependency rows; invalid direct evidence; doneBlockerDoesNotPropagateItsBadAncestry | Implemented |+| 2.4 | Frozen graph retained in capture; QueryBoundaryTests actual modern cursor after endpoint/incidence edits; no duplicate alias traversal | Implemented |+| 3.1 | Separate stored attribution/association kinds; mixed field/link integration tests preserve independent task field authority | Implemented |+| 3.2 | Complete proposed duplicate graph and at-most-one outgoing validation; cardinality and same-request retarget tests | Implemented |+| 3.3 | DuplicateResolution ordered source-to-terminal path/canonical UUID; chain and terminal-state graph fixtures | Implemented |+| 3.4 | DuplicateResolution missing/ambiguous/cardinality/cycle/invalid occurrence diagnostics; acquisition errors throw | Implemented |+| 3.5 | Scalar edges, no redirects/flattening/task closure; incomingDuplicateVisibilityDoesNotRedirectOrdinaryTaskIdentity and protected integration | Implemented |+| 4.1 | Closed wire directives, max50, creation additions-only, exact edge/l1 identity; WireTests and precise repair fixtures | Implemented |+| 4.2 | OwnedPlan validates source/current endpoint snapshots and full proposed graph immediately before synchronous apply; source/endpoint preparation-race and exact affected-guard tests | Implemented within approved participating boundary |+| 4.3 | TaskLinkOwnedApply stages in retained sealed context before terminal snapshot/receipt save; OwnedPhase/OwnedScope/WriteIntegration save and encode failure controls | Implemented |+| 4.4 | Existing coordinator receipt binding/replay retained; dirty retained replay, exact full binding matrix, retained bytes after incidence edits, foundation recovery tests | Implemented |+| 4.5 | Clean shared-context checks before acceptance and after preparation success/error; fresh owned context; pending draft and safe replay controls | Implemented |+| 4.6 | Capability guard, existing protected tool dispatch/durable-store restrictions and recovery outcomes; no reset/deletion API introduced | Implemented |+| 5.1 | Required explicit incidence input, canonical physical tuples plus empty linkContract, current revisionCoverage; RevisionTests old tokens, no-link property/status conflict, labels/removal exclusion | Implemented |+| 5.2 | Exact active row deletion + separate immutable evidence; fresh re-add UUID; exact fresh-key no-op; expiry/content-token stability tests | Implemented |+| 5.3 | Graph missing/ambiguous endpoint diagnostics; exact dangling repair without nonexistent guard; physical edge selector collision rejects | Implemented |+| 5.4 | All physical multiplicity/raw rows retained; exact removal-only repair preserves other rows and unrelated corruption; matching invalid removal evidence remains conflict | Implemented |+| 5.5 | Caller contract explicitly excludes independent writers/import atomicity; allowed outside-writer observations and later available graph diagnostics; valid status assessment is not called historical race | Implemented within ADR4 |+| 5.6 | Additive scalar models in schema parity audit; process-separated closed legacy store upgrade/reopen; explicit legacy nil incidence/missing graph coverage; historic receipt replay bytes unchanged | Implemented locally; live CloudKit deferred |+| 6.1 | TaskLinkQueryOptions conjunctive valid-type/orientation/target/unblocked predicates before ordering/page; ordinary/query boundary fixtures; reusable graph options rejected | Implemented |+| 6.2 | Full links/diagnostics/resolution/blockers and explicit graphCoverage; omitted bodies preserve covered token; missing graph null/unavailable fixture | Implemented |+| 6.3 | MCPReadCaptureBuilder fresh saved context and history/generation fence wraps task/graph/comment capture; draft exclusion and fetch failures; default handler uses saved capture | Implemented for covered MCP queries |+| 6.4 | Frozen retained graph and fixed selected membership; cross-project closure excluded from selectable scope/totals; reusable rejection and retained byte/index accounting fixtures | Implemented |+| 6.5 | Original operation deadline threaded through graph/capture/body picker/filter/encoding; repeated-identity stop; deadline/capacity/publication and existing read-service limit tests | Implemented; final platform checks passed |+| 6.6 | Original retained metadata and modern frozen payload parity; no guessed navigation URLs; modern actual cursor test | Implemented |+| 7.1 | Saved native DTO, TaskLinksSection and source-relative TaskLinkNativeLabels in existing native detail patterns; source/endpoint draft exclusion and actual UI diagnostic fixtures | Implemented |+| 7.2 | Saved unique destination at click and TaskDetailWindowView resolver; nil for missing/ambiguous/unsaved/pending-delete; actual iOS UUID navigation UI test | Implemented |+| 7.3 | Existing field/status/comment paths use new current coverage; batch parser removes/rejects link fields before keys; real foundation batch/portfolio integration | Implemented |+| 7.4 | Write/result contracts and input schema describe normalizations/guards/no-op/expiry/coverage/history/local boundary | Implemented; tool-name correction verified |+| 8.1 | Graph/Generated/Plan/Wire/Write suites cover public directions, multiplicity, seeded independent SCC reference, repair and duplicate cases | Appropriate behavioral tests present |+| 8.2 | Participating/Protected/OwnedScope/OwnedPhase suites exercise dirty contexts, source/endpoint races, all-or-none domain/receipt, replay binding, uncertainty; historical independent-writer counterexamples retained | Appropriate behavioral tests present |+| 8.3 | Migration/ReadCaptureBoundary/QueryBoundary/RemovalEvidence/Native/Foundation suites cover lifecycle integration; actual UI source pins and lost-exit limitation documented honestly | Appropriate tests present; final platform evidence passed |+++## Local review artifact++The standard review renderer generated the complete branch diff and blast-radius artifact from landed base e04. `pulsar publish` validated its metadata and archived the HTML locally at `/Users/arjen/CodeReviews/2026-10/2026-10-05-github-transit-branch-t-1734-typed-task-links-final.html` (exit 0). This operation moved a local file; it did not push source, publish a PR or contact an external reviewer. Review inputs and four peer reports remain at `/tmp/t1734-final-review.qjczlb7m`.++## PR #254 corrective review and verification++Configured Claude reviews posted at remote heads 452e3d3 and 0714ce01; both explicitly disclosed limited inspection and no independent execution. Root validated every suggestion through the PR Review Fixer overview comments. The second review's merge recommendations led to the native five-file correction at bbe3a25. All four internal reviewers independently inspected that exact delta with no mandatory finding; prior native assertions remain unchanged. Ten label contracts and two burst/cancelled-start controls join the existing eight focused native cases, all 20 passing. Complete macOS, iOS unit and iOS UI suites were rerun at the revised source; root independently parsed trees, exit and cleanup records into `/tmp/t1734-final-review.qjczlb7m/root-audit-bbe3a25.json`.++CLAUDE.md's directory map and the CHANGELOG's MCP-only authoring statement are corrected. The entity count was already eight; all schema registrations remain verified. Literal centralisation, encoder reuse, narrower/off-actor pure-value projection and display polish are optional follow-ups, without relaxing full graph closure or unknown-kind diagnostics. Production CloudKit promotion remains blocked on T-2402's deferred live verification; this PR workflow authorises repository merge only. There are no live task-record, CloudKit or client-setting changes.
specs/typed-task-links/migration-next-tests.md Changed +64 / -0
diff --git a/specs/typed-task-links/migration-next-tests.md b/specs/typed-task-links/migration-next-tests.mdnew file mode 100644index 00000000..cb4fab01--- /dev/null+++ b/specs/typed-task-links/migration-next-tests.md@@ -0,0 +1,64 @@+# Task1 remaining migration evidence and precise seams++Current contract: owner `Sentinel_c95239aefa6481919303c2353b8a9e9c` approved participating Transit writes with pre-save validation and outside-writer conflict reporting (decision_log.md ADR 4). The historical all-independent-writer/import validation-to-save fence and persistence-redesign completion gate below are superseded. Original tests, failures and approvals remain historical evidence; owned same-store domain/receipt saving and T-2402 deferral remain unchanged.++Deferred destination: **T-2402 — Set up isolated CloudKit integration testing**, created and freshly verified by the parent through the installed UI (Transit, Idea/Research). No duplicate live ticket write.++Current owner amendment `Sentinel_42e647a603ac81918cbb949ed1ca67bb` defers CloudKit test isolation/live verification to a separate ticket and authorizes proceeding without it. The historical external task2 blocker described below is superseded. Verified local migration/metadata GREEN can satisfy task2's remaining scope after review; no live smoke success is claimed. The next mandatory gate is task3/task4 atomic validation-to-save feasibility, with parent-scheduled execution and graph writes disabled until proven.++## Historical task2 GREEN queue — before owner deferral++This local queue now passed at immutable source aa5f56a7744c0dc8f09e974be8d9b8944982d822 in the parent-assigned slot. Fresh build/preflight, four distinct drained closed-store stages, both physical empty-table checks and all three expanded metadata/control cases pass. Evidence `/tmp/t1734-green.Zf1DYx`; detailed outcomes and retained hashes are in implementation.md. The slot is released after independent final drain. No repeat local run is needed without changed inputs or a new concern; the separate Development CloudKit completion gate remains outstanding.++The parent has now resolved all registration owners, including T-2384's final CoordinatorProbe list-only grant. The two model declarations and all seven current factories are being aligned on this isolated branch; the historical observations below describe the earlier RED source. Record the final clean HEAD and current source audit in the next run's evidence. Source registration readiness does not establish SwiftData macro compilation, inferred metadata or migration GREEN.++After a parent-assigned heavy slot, use a fresh private DerivedData/cache root and the locked-package, development-signing build-for-testing command in verification-readiness.md. Run `run_closed_store.py BUILD_PRODUCTS --run` directly: it performs the fresh signed-unit preflight and retains its base T1734Migration.xctestrun. Require seed, legacy, upgrade and reopen each to execute exactly one passing non-skipped case in distinct drained host processes; require preserved original raw fields/receipt bytes/physical multiplicity and zero physical rows in both new graph tables after upgrade and reopen.++Then use that preflighted base run file for the separate TaskLinkMigrationTests serial run with a fresh T1734Migration.xcresult path, without rerunning the output-exclusive preflight helper. Require both expanded entity metadata cases and the saved-field control to pass: real scalar types/defaults/optionality, no relationships and no uniqueness. Preserve source identity, logs, exits, per-case xcresults, preflight, manifests, store/WAL/SHM and physical graph counts. Sample an owned stalled host before bounded cleanup; stop on discovery, build, metadata, byte-preservation, migration or drain failure.++No heavy run is authorized merely by finishing source registration. Earlier offline runtime evidence predates the new model files and Makefile compile-list changes and cannot certify those changed inputs. The separate opt-in real Development CloudKit host/account/schema/deletion gate remains uncompiled and unexecuted; this local queue performs no CloudKit activation or publication. Even successful local GREEN leaves task2 incomplete and task3 blocked until the approved external gate is satisfied.++Source preparation `7c4b28944975f7b945cb3f45af53bd6ee2672334` follows the verified capability RED/control boundary at `4e44caa`. No new production declaration, shared registry, account operation or schema publication occurred. This document initially recorded task1 in progress. Subsequent critic-reviewed smoke source closes RED preparation; Rune now completes task1 and returns task2 next, with ownership coordination pending. All task2 completion gates below remain binding.++## Prepared local job (now executed through expected RED)++After the next parent-assigned heavy slot, build a fresh shared Transit Debug unit bundle using the locked-package, development-signing and private-cache command in `verification-readiness.md`. Skip the unchanged offline checks and dedicated smoke already verified at `237c7e1`. Do not run `prepare_unit_run.py` separately on the same products directory: the new runner invokes that signed-unit preflight itself and requires fresh outputs.++```sh+python3 tests/typed-task-links/run_closed_store.py BUILD_PRODUCTS --run+```++Replace BUILD_PRODUCTS with that fresh build's absolute `unit/Build/Products` path. The runner prepares allowlisted unit-only runs. Without `--run` it only preflights/prepares; it does not launch. Preparation consumes its fresh output paths, so use a different fresh build/output directory for an execution rather than invoking prepare then run on the same directory.++| Stage | Concrete assertion | Expected on current source |+| --- | --- | --- |+| seed | Six-entity CloudKit-none synthetic store; pre-save raw-field/receipt-byte manifest equals saved values | One passed case; process drains |+| legacy | A different drained host opens that existing six-entity store and matches original bytes/physical multiplicity | One passed case; genuine closed-store baseline control |+| upgrade | A third host opens with the **actual** default TestModelContainer schema; preserves old bytes and requires both link registrations | One failed case identifying missing entities; evidence retained; stop |+| reopen | A fourth host reopens successful upgraded schema, preserves bytes, and verifies zero physical graph rows | Not reached until the upgrade becomes GREEN |++Each stage requires exactly one executed, non-skipped case and a consistent xcresult/exit outcome. The runner checks both path aliases and the recorded stage host PID have exited before advancing; xcodebuild exit alone is insufficient. A bounded drain failure stops for parent sampling/cleanup; it does not delete stores or weaken the guard. Synthetic SQLite/WAL/SHM and manifests remain in the development app's private Data/tmp UUID directory. No live records are used. Build failure, missing observation, crash or zero discovery is not migration RED.++After a successful upgrade/reopen, read-only SQLite counts must show zero TaskLinkOccurrence and TaskLinkRemovalEvidence rows. This is physical local incidence evidence, not graph projection or CloudKit convergence. Unknown table layout fails closed for inspection.++## Source parity and static CloudKit compatibility++`python3 tests/typed-task-links/audit_schema_sources.py --check` is source-only and currently exits 1. The inventory has 19 entries and identifies seven current factories needing task2 registrations: TransitApp, TestModelContainer, MCPWritePersistenceProbeTests and the four MCP write probes. Dynamic Probe.swift needs manual mode review: historical seed-old remains pre-receipt/pre-link. Development-isolation historical/control fixtures remain deliberately graph-free; ContainerFactory receives its caller's schema and adds no registration.++This is a token inventory, not inferred runtime schema proof. The existing parameterized metadata tests will inspect real entity scalar types, defaults/optionality and absence of unique constraints/relationships once the models are registered. Those assertions currently stop at the missing-entity requirement. No source result proves server record types exist.++## Exact paired GREEN and ownership boundary++No production API seam is needed to compile the prepared RED source: it obtains the actual schema from an owning TestModelContainer and names future entities as strings. New model declarations and registration belong to **task2**, not task1. T-1734 owns the two approved Models files; App/schema and central TestModelContainer integration require targeted coordination with the containment/T-63 owner, and MCP probe/Makefile lists require their foundation owner's handoff. Use an explicit verified compatible source checkpoint; preserve legacy controls and every unrelated shared change. This schema-only seam does not require unrelated graph query/write features to be implemented first, and does not justify importing all owner branches.++The prepared closed-store RED must run before claiming task1's local migration fixture is established. Substantive opt-in development platform-deletion source is now prepared and reviewed; its future-model compilation and cleared execution remain unverified. If completing that fixture requires typed production declarations, the parent must coordinate that minimal task2 seam at the approved Red/Green boundary at the reviewed RED/ GREEN boundary without treating task2 as complete or enabling dependent graph work. Even with local GREEN, task2 cannot pass its full gate until its separate development-schema evidence exists. Atomic-save and bounded-capture gates remain untouched.++## Genuine external development gate++TaskLinkDevelopmentSchemaPrecheckTests remains explicitly opt-in and **local only**. The substantive future typed smoke is now separately prepared in tests/typed-task-links/development-cloudkit; see its README and red-boundary-review.md. It never creates a CloudKit container or makes a request, and deliberately cannot certify the external gate. It is not a completed platform-deletion smoke fixture.++Real verification requires the task2 model declarations, a separately cleared signed development CloudKit host/operator fixture, the reserved development account/environment, verified additive server types/fields, and observed platform deletion behavior. Parent must clear that environment and its heavy slot. The existing isolated unit host intentionally has no CloudKit entitlement and cannot supply this evidence. No schema initialization, account/signing settings change, production promotion or ticket-store access is authorized here. Do not infer remote convergence from any local or development deletion observation.++## Actual boundary++At source `4ba0c6569ac914c91f9953e55ef832e247fd03f6`, the fresh build/preflight passed; seed and closed-store legacy stages passed in distinct drained host processes; upgrade failed only for missing link entities; final reopen was not executed. See implementation.md and `/tmp/t1734-closed.zwjNwD/preserved-evidence-sha256.json`. Next local runtime work follows the coordinated task2 model/registration seam, then successful upgrade/reopen and metadata assertions. This does not satisfy the separate external development gate.
specs/typed-task-links/pr254-native-corrections.md Changed +58 / -0
diff --git a/specs/typed-task-links/pr254-native-corrections.md b/specs/typed-task-links/pr254-native-corrections.mdnew file mode 100644index 00000000..fd3a5256--- /dev/null+++ b/specs/typed-task-links/pr254-native-corrections.md@@ -0,0 +1,58 @@+# PR 254 native review corrections and verification++Verified application/test source: `bbe3a2560584f7fb822aa8006b20f08d22284ce4`, based on parent documentation checkpoint `ebd7330`. This is new evidence for the PR corrections; [final-handoff.md](final-handoff.md) remains the truthful historical verification at81f78e7. No source changed during the following runs. The final commit after this source only records this handoff.++## Narrow corrections++`TaskLinkNativeLabels` supplies wording relative to the selected endpoint:++| Stored kind | Outgoing | Incoming |+| --- | --- | --- |+| dependency | Blocks | Blocked by |+| association | Relates to | Relates to |+| attribution | Introduced by | Introduces |+| duplicate | Duplicate of | Duplicated by |+| unrecognized raw kind | Unknown relation | Unknown relation |++Raw stored kinds and physical graph evidence remain unchanged. These are native presentation labels, not new MCP wire spellings.++`TaskLinksSection` keeps first/new-source loads immediate and debounces repeated same-source notification refreshes for100ms. Every save/import still invalidates; there is no task-specific notification filtering or neighbourhood-only capture. `TaskLinkNativeDetailState` invalidates its generation and clears the prior observation before waiting. It checks cancellation, selected source and generation after waiting **before** calling the provider, and again before publication. An already-canceled task cannot invalidate a current observation. The provider still reads the complete fresh saved graph with its original bounded budget and cancellation checkpoints. Navigation resolution, budgets, schemas, shared writes and CloudKit behavior are unchanged.++Existing eight native projection/navigation cases and assertions were preserved. New controls add ten direction-label contracts and two refresh lifecycle cases. The deterministic three-request burst supersedes one waiting capture, cancels another and proves exactly one provider reads the latest saved source plus unrelated cross-project task/link incidence; no old observation survives waiting. The canceled-before-start control proves the current selection/observation survives and no provider runs.++No capture speed benchmark or outside-writer fence is claimed. The improvement coalesces burst scheduling; each necessary capture still builds the complete graph. Optional per-graph encoder reuse and broader refactors were left out.++## Final native verification++| Run | Expanded outcomes | Declaration outcomes | Build/run and drain |+| --- | --- | --- | --- |+| Focused native | 20 pass,0 fail/skip | 7 pass | fresh build0/run0; host86721 drained |+| Full macOS units | 3,265 pass,0 fail,5 intentional opt-in skips | 2,530 pass,5 skip | exact focused products revalidated; run0; host86946 drained |+| Full iOS units | 1,403 pass,0 fail/skip | 1,326 pass | fresh build0/run0; host88774 drained |+| Full iOS UI | 26 pass,0 fail/skip | 23 pass | same fresh iOS products; run0; all27 recorded hosts drained |++Full-suite aggregate: **4,694 passed expanded executions**, five intentional macOS opt-in skips. All native summaries report zero runtime warnings. Compiled full inventories have no discovery errors: macOS2,535 declarations, iOS units1,326, UI23. The focused inventory explicitly enables7 declarations and filters the other2,528; it is not a full-target discovery claim.++`make lint` passed all ownership, source schema and development configuration guards, plus SwiftLint on652 files with zero violations. Log: `/tmp/t1734-pr254-native-lint.log`. Diff check passed. The fresh macOS build has the existing manual-target-order warning. The fresh iOS build has35 existing warning lines (manual target order, retroactive TaskStatus/TaskType Sendable conformances, unused values/results in existing tests); none points to the native correction files.++## Signing, isolation and artifacts++Full roots beneath `/var/folders/11/v0tnfm294kd9c6zll_ncmpkh0000gn/T/`:++- `t1734-pr254-native-focus.hnv9pd4u`: fresh `build.log`, `build-exit.txt`, compiled inventory, `summary.json`, `tests.json`, `run-outcome.json`, source pin and guarded runner/preflight source copies.+- `t1734-pr254-full-macos.k2h6pc3b`: `reused-build-proof.json` pins the exact successful unchanged focused build and drain; independent signed preflight and unfiltered runfile; compiled full inventory, `summary.json`, `tests.json`, `enumeration-outcome.json`, `run-outcome.json`, guarded runner/preflight source copies.+- `t1734-pr254-full-ios.1t0jwd2h`: `source-head.txt`, fresh `build-exit.json`/`build.log`, `signed-preflight.json`, per-target compiled inventories, `TransitTests-summary.json`/`TransitTests-tests.json`/`TransitTests-exit.json`, `TransitUITests-summary.json`/`TransitUITests-tests.json`/`TransitUITests-exit.json`, native xcresult bundles, guarded runner/preflight source copies, `process-census-timeouts.jsonl`, `final-recorded-pid-census.json`, `final-drain.json`, `owned-simulator-deletion.json`.++Preflight verified the exact signed `me.nore.ig.Transit.development` host, expected executable/test-host path and startup modes. macOS requires its development debugging entitlement and rejects CloudKit/push/AppGroup entitlements. iOS verifies simulator platform, exact development app/runner identity and strict signatures; app entitlements are empty. Unit and UI clones retain only their respective target, with unit-test/ui-test isolation modes and all inheritedT1734 opt-in flags sanitized. Packages and build roots are private/locked; no production store, account, live MCP mutation, schema promotion or settings change occurred.++The macOS full run reuses the successful **fresh** focused products only after exact source pin/build/run/drain and signature validation; no filter-only redundant build was performed. iOS had its own fresh build and separately enumerated full unit/UI targets. Deadlines stayed fixed: bounded build, enumeration, unit and1,200-second UI phases; elapsed process inspection time is charged to the original monotonic deadline.++Two transient first-attempt `/bin/ps` timeouts recovered through the next original bounded inspection. Their requested five-second timeout and actual elapsed durations are recorded; at most three attempts are allowed. Denial, nonzero output, malformed rows or an ownership mismatch remain fail closed. No runtime timeout or sampled teardown occurred. The final exact recorded-PID census proves all30 focused/full macOS/iOS runtime PIDs are absent.++Owned simulator `984525F2-7564-4EA6-903E-570A2D44A825` shut down and was deleted with exit0. Final census has no remaining owned simulator/app processes. No additional verification job remains active.++## Remaining ownership and limits++Development CloudKit setup/export/deletion and production schema promotion remain deferred toT-2402; these local corrections do not satisfy that future gate or activate a client. Actual UI execution here is iOS; macOS click/window resolution remains covered by its shared unit-tested resolver. The five macOS opt-in diagnostics remain intentionally disabled as documented in the historical handoff.++The parent owns review replies, PR body/checks, documentation/HTML archive, push and any eligible merge. This worker performed only local source/test corrections, isolated verification and the handoff commit; no push, main change, deployment or live task-record write.
specs/typed-task-links/prerequisites.md Changed +16 / -0
diff --git a/specs/typed-task-links/prerequisites.md b/specs/typed-task-links/prerequisites.mdnew file mode 100644index 00000000..77e61ad9--- /dev/null+++ b/specs/typed-task-links/prerequisites.md@@ -0,0 +1,16 @@+# Prerequisites for typed task links++Deferred destination: **T-2402 — Set up isolated CloudKit integration testing**, created and freshly verified by the parent through the installed UI (Transit, Idea/Research). No duplicate live ticket write.++## Before implementation++- [ ] Parent confirms compatible merged T-63 read/capture, T-2382 reusable-view, T-2383 result-encoder and T-2384 write-coordinator foundations, their shared-file ownership handoffs and an explicit latest verified base SHA. Refresh the actual running tool schema before coding. Keep the ticket branch isolated and canonical main/`.kiro` intact; task approval alone does not authorize implementation or merges.++## Deferred CloudKit test-isolation ticket++Owner `Sentinel_42e647a603ac81918cbb949ed1ca67bb` explicitly assigns this setup and live verification to a separate ticket and says to proceed without it for now. The items below remain prerequisites for that future live smoke, not blockers of T-1734 task2 or its coordinated local save work. No remote verification is claimed; account/signing/schema/client changes still require separately scoped authorization. Parent owns ticket creation; do not duplicate a live ticket write.++- [ ] Confirm access to the existing Apple developer account and a development CloudKit environment reserved for test records. Before the deferred development-sync fixture, verify the additive `TaskLinkOccurrence` and `TaskLinkRemovalEvidence` record types/fields in that development schema. Obtain parent clearance for the environment and heavy-test slot; do not use the user's production store or ticket records.+- [ ] If the new types are absent, the parent must designate the user or an authorized development operator to initialize the development schema from the real model declarations using Apple's SwiftData/Core Data development-schema procedure, then verify it in CloudKit Console. Do not add schema initialization to normal app launch or promote the production schema as part of this plan.++Production schema promotion is a separate release action, outside this task plan. No account, signing, entitlement, global permission or production configuration change is authorized by spec approval.
specs/typed-task-links/red-boundary-review.md Changed +21 / -0
diff --git a/specs/typed-task-links/red-boundary-review.md b/specs/typed-task-links/red-boundary-review.mdnew file mode 100644index 00000000..04382c3b--- /dev/null+++ b/specs/typed-task-links/red-boundary-review.md@@ -0,0 +1,21 @@+# Task1 RED completion review++Current contract: owner `Sentinel_c95239aefa6481919303c2353b8a9e9c` approved participating Transit writes with pre-save validation and outside-writer conflict reporting (decision_log.md ADR 4). The historical all-independent-writer/import validation-to-save fence and persistence-redesign completion gate below are superseded. Original tests, failures and approvals remain historical evidence; owned same-store domain/receipt saving and T-2402 deferral remain unchanged.++Deferred destination: **T-2402 — Set up isolated CloudKit integration testing**, created and freshly verified by the parent through the installed UI (Transit, Idea/Research). No duplicate live ticket write.++Current owner-approved amendment: `Sentinel_42e647a603ac81918cbb949ed1ca67bb` defers CloudKit test isolation to a separate ticket and authorizes continuing without it. The review below records the original boundary; its live Development compilation/execution dependency is superseded only by this explicit amendment. Verified local task2 GREEN at aa5f56a remains valid; the optional smoke stays uncompiled/unexecuted. Atomic validation-to-save and every other safety gate remain unchanged.++Internal design-critic reviewed the preserved focused and process-separated results, approved task1/task2 text and the final opt-in development smoke source. Verdict: **task1 RED source and local behavioral boundary complete; no approved DAG contradiction**. No external source disclosure or new product approval occurred.++The focused run executed two missing-entity argument failures and one passing saved-state control. The closed-store run passed seed and legacy reopen in distinct drained hosts, then preserved original bytes and failed upgrade only because both real link entities were absent. These are intended behavioral failures with passing controls, not compile errors, zero discovery or migration GREEN. Evidence remains at `/tmp/t1734-focused.2GDqRp` and `/tmp/t1734-closed.zwjNwD`.++The original local precheck did not fulfill task1's opt-in fixture source requirement. That gap is now closed by `tests/typed-task-links/development-cloudkit/Smoke.swift`, prepared at `31687b9a6d3acae953f831540928e4af71aae238` with timeout sampling correction `cffece1b597e975038d3b8deb023e89345ad949f`. The substantive typed body saves a real occurrence, observes all mapped exported scalar fields, deletes through SwiftData while saving separate removal evidence, then observes the exact record's platform deletion and evidence export. Assertions select only this run's UUIDs, allowing unrelated imported exemplars. It does not directly delete/save CloudKit records or initialize/promote schema.++The wrapper validates a dedicated signed sandbox host, Development environment, exact reviewed container and contract hash before launch. Private fresh paths, bounded requests/observation/child lifetime, exact-child sampling before bounded timeout teardown and normal PID drain are prepared in source. Smoke source is outside default targets; no future model compilation, signing, account request or execution has occurred. Lightweight lint/AST/source checks are not substituted for those later checks.++Requiring successful metadata assertions, eight-entity migration, empty upgraded graph tables or real CloudKit evidence before completing RED would demand task2 GREEN circularly. Preparing substantive deferred smoke source fulfills RED preparation; compiling and executing that source belongs to task2. This interpretation preserves the existing blocked-by edge rather than deleting it or changing task scope.++Task1 was completed through Rune. Task2 is now the next pending task, with source work waiting only for the parent-agreed shared-file ownership split. Task2 cannot complete, and task3 cannot start, until successful actual-schema upgrade/final reopen, preserved historic bytes, zero graph rows, executed scalar/default/optionality/constraint assertions, current factory parity/manual probe-mode review, smoke compilation and separately cleared development schema/deletion evidence all exist. The two-model smoke alone does not prove full application-schema compatibility. No atomic-save or global convergence guarantee follows from this review.++The concrete seven-factory plus compiler-list patch is `tests/typed-task-links/pending-schema-registration.patch`; inventory is adjacent. It is unapplied and based on immutable `4459a964`, so owners must adapt its narrow additions against their latest verified integrated source. No App/common fixture/probe source is concurrently edited. This environment has no callable cross-thread messaging tool; parent routing to T-63/containment and identification of current write-probe/fixture ownership remain necessary.
specs/typed-task-links/requirements-review.md Changed +55 / -0
diff --git a/specs/typed-task-links/requirements-review.md b/specs/typed-task-links/requirements-review.mdnew file mode 100644index 00000000..52059273--- /dev/null+++ b/specs/typed-task-links/requirements-review.md@@ -0,0 +1,55 @@+# Typed task links — requirements review and owner gate++Review outcome: **ready for the requirements approval gate**. Scope/name/types are approved; these detailed requirements are not yet approved. Design, tasks and implementation have separate gates.++Public naming: **blocks, blocked-by, relates-to, introduced-by, duplicate-of**. All use kebab-case; no alias is proposed. Owner correction `Sentinel_54fa08e7dbb881919d2c718f23bfb0fe` changes spelling only and does not approve the full requirements.++Naming re-review: the design critic followed by both independent internal peers confirmed consistent spellings, unchanged relationship semantics, no alias and no implied requirements approval. The scope inventory now identifies spelling as settled while detailed behaviors remain pending.++Live ticket naming update is pending: full display-ID lookup now returns `Duplicate task identifier detected for displayId 1734`, so no write was attempted. A bounded direct `tools/list` read at the configured `http://localhost:3141/mcp` confirms the running server advertises the legacy query schema with no UUID batch/full-detail selector or duplicate scan tool. This is a live endpoint/data blocker, not stale connector metadata alone. No identity guard, task data, maintenance toggle or settings were changed.++A narrow exact-title search returns two T-1734 rows with the same task UUID `2E3A1518-78CA-43CA-9F96-516A51094EA3` and display ID 1734: one has no returned project and revision `r1:d7034fef6d06b45432923b4b03c3af1629d2f803f591ab5aeddee0a35ad62dc0`; the Transit-owned row has project UUID `8491AAC4-CC6C-498C-B93D-99DD68424226` and revision `r1:f6c920b55f5073f5fed605c2b63f06ee63837e416e3fd065fca2e2ef285964de`. Both are Spec and have one comment. A UUID write would not resolve that observed ambiguity, so the ticket change awaits a safe uniquely identified full read; no first-match write or repair was attempted.++## Review method and actual results++The local Starwave requirements skill requires a design critic followed by peer validation. The design-critic reviewer first examined draft checkpoint `b51b2a2`; two independent internal peers then validated the document and critic findings through technical-correctness and scope/maintainability lenses. Following refinement, the critic re-reviewed before both peers re-reviewed the final proposals.++The local peer-review-validator's external-model selector was active (`PERSONAL_PROJECTS=1`), but neither external Codex nor Kiro reviewer tool was callable. Its documented internal-peer fallback supplied two independent perspectives. These were internal agents using the available model, not distinct external model systems. No repository source was disclosed externally; no review CLI, build, test, lint or typecheck ran during the Asterism quiet window.++| Finding agreed by critic and both peers | Current requirement resolution |+| --- | --- |+| Invalid-edge repair could not be selected by target UUID alone. | Exact saved occurrence removal with source/endpoint guards; repair unavailable for ambiguous affected identities; nonexistent endpoints need no invented revision. |+| Current versus historic revision coverage was ambiguous. | Preserve r1 syntax, explicitly cover active incidence including empty sets, distinguish graph-covered evidence, conflict on old fresh-write tokens, and replay historical receipts first unchanged. |+| Batch endpoint overlap and strict item schemas were unsettled. | Standalone create/update link edits initially; T-2384 link directives reject before item/key acceptance. No implicit chaining or whole-batch graph guarantee. |+| Earlier graph validation did not establish commit-time safety. | Validate complete proposed local graph, affected invariants and endpoint preconditions at the same local commit boundary; explicit removal-only repair can reduce invalid evidence incrementally. |+| Imported-cycle reach, query orientation and occurrence lifecycle were unclear. | Direct-only blocker rule, cycle-member exclusion, explicit incoming/outgoing filters, direct incoming duplicate targets, new occurrence on re-add, and no domain effects for absent-edge no-ops. |+| Reusable view enhancement would change T-2382's approved contract. | Preserve reusable project/status options and capacity; graph filters unsupported, absent coverage explicit, ordinary graph captures frozen with scoped closure evidence. |++The critic's final wording gaps—mixed property/link edits, ambiguous endpoint repair and retained assessment wording—were addressed explicitly. Both final peer reports found no blocking technical, scope or compatibility contradiction for presenting the requirements. The technical peer's minor wording corrections to incoming duplicate-of and the decision log were also incorporated.++No material review disagreement remained after synthesis. Multi-endpoint task revisions are a conservative proposal with a real tradeoff: an unrelated target field edit can cause a link conflict. A separate graph token is an alternative, but would introduce a new concurrency surface; the owner is being asked to approve the conservative proposal, not a storage implementation.++## Choices the owner is approving++1. **Done-only blockers:** Abandoned does not satisfy a dependency. Exclude cycle participants and candidates with invalid direct evidence; do not recursively propagate a Done blocker's unrelated ancestry faults.+2. **Cross-project links:** explicit same-store UUID targets allowed without moving tasks or milestones.+3. **Attribution and duplicates:** multiple introduced-by sources; one direct duplicate-of target, chains and Done/Abandoned canonical targets allowed. No regression inference, redirect, merge or closure.+4. **Guarded delta edits:** at most 50 link directives per standalone create/update; source and affected existing endpoint task preconditions; locally all-or-none task/link/result commitment. No batch link support initially.+5. **Current revision transition:** retain r1 syntax but add active incident graph coverage, including empty sets. **Every pre-feature token becomes insufficient for fresh preconditioned writes, including status/property edits on no-link tasks.** Obtain a new full read after upgrade. Historical protected receipt replay remains unchanged and precedes fresh validation.+6. **Removal/re-add:** exact occurrence removal, incremental removal-only repair, ambiguous affected identities fail closed, no fake revision for a missing endpoint. A re-add gets a new occurrence identity; removed evidence has bounded design-defined retention rather than permanent consolidation history.+7. **Read surfaces:** ordinary queries gain graph filters and frozen saved evidence; reusable queries retain current project/status options and graph-filter rejection. Capture budgets/retention remain unchanged.+8. **Native surface:** read-only saved relationship visibility and exact-UUID in-app navigation; native editors and App Intent parity deferred.++## Remaining work and validation limits++Design must choose and verify the SwiftData/CloudKit-safe representation, migration and coverage marker, removal retention horizon, isolated local commit mechanism, exact repair locator, graph validation and bounded saved capture. Those feasibility checks belong to design and later authorized implementation; this review supplies no runtime or CloudKit convergence evidence. Shared-file ownership and compatible merged foundation prerequisites remain in force.++## Exact next request through the parent++**“Do the T-1734 typed-task-links requirements look good or do you want additional changes? Approval includes the choices above, especially old-token conflicts on fresh writes, standalone-only link mutations and unchanged reusable query filters.”**++An approval authorizes design work only. No implementation, deployment, push or main/PR merge is authorized.++## Requirements gate outcome++Approved by owner `Sentinel_36dc8dafea7c81919e7b060518fc9009` against corrected commit `748f474517d420498ccd9e54cf79f777e7763f57`. The pending request above is historical; next phase is design. The live duplicate investigation remains owner-managed.
specs/typed-task-links/requirements.md Changed +114 / -0
diff --git a/specs/typed-task-links/requirements.md b/specs/typed-task-links/requirements.mdnew file mode 100644index 00000000..e8b893c9--- /dev/null+++ b/specs/typed-task-links/requirements.md@@ -0,0 +1,114 @@+# Typed task links — requirements++Deferred destination: **T-2402 — Set up isolated CloudKit integration testing**, created and freshly verified by the parent through the installed UI (Transit, Idea/Research). No duplicate live ticket write.++Review status: amended requirements approved by owner `Sentinel_08cb318218788191a85da25d1206979f` at `a64e595c439db6d62e46c85888f37130d53269fa`. Owner `Sentinel_c95239aefa6481919303c2353b8a9e9c` approved the simpler concurrency guarantee; prior requirement/task approvals and decision history are recorded in decision_log.md. CloudKit test isolation/live verification remains deferred to T-2402.++## Introduction++Transit task relationships let agents identify dependencies, associations, attribution and duplicates without parsing prose. Explicit directions, saved observations and protected edits make those relationships usable while records and CloudKit imports change. This feature supplies the common link foundation for later consolidation without performing consolidation itself.++## Non-Goals++- Semantic duplicate matching, survivor selection, content merging, duplicate closure, consolidation preview/apply/undo or provenance from deferred T-2381.+- Regression tri-state/PR-number fields and workflow/eval adoption from T-1732/T-1733; task copying from T-649.+- Additional relation kinds, task hierarchy, native link editing, App Intent mutation parity or automatic prose-to-link migration.+- Atomic validation-to-save protection against independent writers or sync imports; persistence redesign, distributed locks, global CloudKit graph atomicity or guaranteed remote convergence.+- Permanent-delete cleanup or retry-guard resets.+- New snapshot/freshness/protocol engines, summary count definitions, unsupported entity URLs or changes to unrelated tool permissions.+- Provisioning CloudKit test isolation or executing its live Development schema/export/deletion smoke; deferred by the explicit owner amendment above.++### 1. Relationship vocabulary and identity++**User Story:** As a caller, I want explicit task relationships, so that each link has one interpretable meaning.++**Acceptance Criteria:**++1. <a name="1.1"></a>The system SHALL support only `blocks`, `blocked-by`, `relates-to`, `introduced-by` and `duplicate-of` as public link type spellings, with `blocks`/`blocked-by` representing opposite views of one dependency kind. Unsupported types, self-links and malformed UUIDs SHALL be rejected without domain effects.  +2. <a name="1.2"></a>WHEN A blocks B, readback SHALL expose A's `blocks` B and B's `blocked-by` A; WHEN A relates-to B, readback SHALL expose the association from either endpoint; WHEN A is introduced-by B or duplicate-of B, readback SHALL expose that directed relation and explicitly identified incoming edges on B without inventing additional public mutation types.  +3. <a name="1.3"></a>WHEN equivalent inverse dependency spellings or reversed relates-to endpoints identify the same valid logical relation, the system SHALL expose one active occurrence with stable identity; adding an already-present valid relation or removing an already-absent relation SHALL preserve domain content/timestamps while retaining the protected operation outcome. Incompatible add/remove directives for the same occurrence in one request SHALL be rejected; an explicit replacement of a duplicate target SHALL remain valid under 3.2. Imported multiple physical occurrences SHALL follow 5.4 rather than be silently merged.  +4. <a name="1.4"></a>WHEN endpoints are explicitly selected, the system SHALL accept unambiguous task UUIDs in the same store, including across projects, and SHALL reject missing or ambiguous identities rather than choosing a display-ID/name match; link changes SHALL NOT move either task or its milestone.  +5. <a name="1.5"></a>Each exposed logical edge SHALL identify its edge UUID, endpoint task UUIDs, semantic type and direction relative to the observed task; display labels SHALL be separately identified as observed labels and SHALL NOT establish identity.  ++### 2. Dependencies and unblocked queries++**User Story:** As an agent, I want to exclude blocked work, so that I do not start work whose prerequisite is unfinished.++**Acceptance Criteria:**++1. <a name="2.1"></a>WHEN deciding whether a task is unblocked, the system SHALL require every direct blocker to resolve unambiguously and have effective status `done` in the selected saved view; `abandoned`, all nonterminal statuses and unrecognized raw statuses SHALL NOT satisfy a blocker, and no blockers SHALL mean unblocked only when dependency evidence is complete.  +2. <a name="2.2"></a>WHEN a new dependency change would create a directed dependency cycle in the locally observed graph, the system SHALL reject the entire domain change; relates-to and attribution cycles SHALL NOT be interpreted as dependency cycles.  +3. <a name="2.3"></a>WHEN imported dependency evidence contains a cycle, its participants SHALL NOT qualify as unblocked; a candidate with missing/ambiguous/invalid direct blocker evidence SHALL also be excluded with diagnostics. A candidate outside that cycle whose own direct blocker evidence is valid and all direct blockers are Done SHALL remain eligible even if one Done blocker has an invalid dependency ancestry; invalidity SHALL NOT propagate recursively beyond the candidate's own cycle membership/direct evidence.  +4. <a name="2.4"></a>WHEN blockers later change status or dependencies are explicitly removed, a new capture SHALL evaluate the new saved state without changing any retained blocker assessment actually captured in an existing cursor/view; unblocked filtering SHALL consider direct dependencies only and SHALL NOT follow duplicate aliases automatically.  ++### 3. Associations, attribution and duplicate resolution++**User Story:** As a caller, I want distinct relationship semantics, so that association, attribution and canonical identity do not trigger unintended actions.++**Acceptance Criteria:**++1. <a name="3.1"></a>WHEN relates-to or introduced-by is set, the relationship itself SHALL preserve task status, descriptions, assignments and regression classification except for separately requested supported task edits in that same operation; introduced-by SHALL allow multiple explicit task sources and SHALL NOT infer regression=yes/no, dependency completion or a PR number.  +2. <a name="3.2"></a>A task SHALL have at most one active outgoing duplicate-of edge; WHEN a new change would create another target or a duplicate chain cycle, the system SHALL reject the whole domain change, while an explicit same-request removal of the old edge and addition of its replacement SHALL be evaluated against the complete proposed result.  +3. <a name="3.3"></a>WHEN a duplicate chain resolves through unambiguous saved tasks and valid edges, the system SHALL return the direct target, ordered path and terminal canonical task UUID; a task with no outgoing duplicate-of SHALL resolve to itself, and Done/Abandoned targets SHALL remain valid targets without a status change.  +4. <a name="3.4"></a>IF duplicate resolution encounters a missing/ambiguous endpoint, cycle, conflicting multiple targets or unreadable required evidence, the system SHALL distinguish invalid graph from failed evidence acquisition and SHALL NOT claim a canonical task; it SHALL NOT silently flatten, repair or hide the chain.  +5. <a name="3.5"></a>WHEN duplicate-of is added, changed or removed, the system SHALL preserve original tasks, field values, comments and statuses except for separately requested task edits in that same operation; ordinary reads/writes SHALL continue to address the selected original UUID and SHALL NOT be redirected to a canonical task.  ++### 4. Protected local link mutation++**User Story:** As an MCP caller, I want guarded link changes, so that retries and concurrent edits do not silently replace relationships.++**Acceptance Criteria:**++1. <a name="4.1"></a>Standalone `create_task` and `update_task` SHALL accept explicit link additions by target UUID and removals of precisely identified saved incident occurrences; omission SHALL leave existing links unchanged, creation SHALL allow additions only, and one request SHALL contain at most 50 link directives. Malformed shapes SHALL reject before key acceptance; validly shaped invalid references/graphs SHALL yield defined domain outcomes. Target UUID alone SHALL NOT authorize removal of an ambiguous/corrupt occurrence; IF exact saved source/edge identity cannot be established, the system SHALL return repair unavailable without effects.  +2. <a name="4.2"></a>A new update, including a semantic no-op, SHALL require the selected source's current task revision; every other existing endpoint whose active incident membership changes SHALL require its current task revision, and creation SHALL require those preconditions for its existing endpoints. Participating Transit writes (standalone and per-item batch executions through the shared MCP write coordinator) SHALL be coordinated, and identity, affected cardinality/cycle invariants and all preconditions SHALL be validated against the complete proposed result and locally saved graph immediately before applying and saving, with explicit removal-only repair governed by 5.4; IF required evidence cannot be established or a precondition differs, the domain change SHALL have no effects and return identifiable conflict/unavailable evidence.  +3. <a name="4.3"></a>WHEN an accepted create/update changes fields and links, all requested task fields, every attributable edge change and the protected terminal saved result SHALL commit together in the originating local store or have no domain effect; this guarantee SHALL NOT extend across a generic batch, another store or later CloudKit synchronization.  +4. <a name="4.4"></a>Link edits SHALL retain T-2380's exact tool/local-store key binding, seven-day terminal replay expiry, immutable saved outcomes, key-reuse conflict and rejected/in_progress/uncertain recovery rules; retained replay SHALL precede current identity/graph/revision validation, including after subsequent edits/removal/deletion.  +5. <a name="4.5"></a>WHEN shared context edits are unsaved, the operation SHALL neither expose, save nor roll back those edits as link handling; a new write unable to establish clean owned changes and saved precondition evidence SHALL stop with an explicit unavailable or uncertain outcome as warranted by acceptance evidence, while safe read-only retained replay SHALL remain possible.  +6. <a name="4.6"></a>A link mutation SHALL obey the existing tool enablement, loopback access and durable-store restrictions; it SHALL introduce no privilege bypass, automatic repair, force-write, key reset or task deletion path. IF result delivery fails after possible commitment, the response/recovery evidence SHALL require original-key retry or reconciliation rather than claim no effect.  ++### 5. Saved revisions, removals and synced invalid states++**User Story:** As a maintainer, I want truthful graph and revision evidence, so that removal and synchronization cannot silently change the meaning of a saved record.++**Acceptance Criteria:**++1. <a name="5.1"></a>Current task revisions SHALL remain `r1:[0-9a-f]{64}` content tokens and cover existing fields/comments plus normalized active incident occurrence identity/type/endpoints; current saved results SHALL identify their graph-covered revision contract. The coverage transition SHALL include an explicit empty incident set, so pre-feature tokens SHALL NOT authorize new fresh writes, including status/property updates; those requests SHALL return the existing no-effect revision conflict and current graph-covered record/revision. Target labels/status, removal-retention metadata, blocker assessment and transitive canonical path SHALL be separately identified observation evidence.  +2. <a name="5.2"></a>WHEN a specific occurrence is removed, subsequent local saved readback SHALL exclude it from active relations and preserve its removed identity under a documented bounded retention policy; an explicit later re-add SHALL create a distinct active occurrence identity rather than revive the removed occurrence. An already-absent removal SHALL create no additional domain removal record or timestamp/token change. Removal-evidence expiry SHALL NOT change active-link/task content tokens or imply safe uncertain-write retry; removing a link SHALL NOT delete either task or its comments.  +3. <a name="5.3"></a>WHEN an endpoint is deleted or cannot be resolved after sync, surviving tasks SHALL report the dangling/ambiguous relation without silently retargeting or treating it as a satisfied blocker/canonical target. Explicit removal SHALL use exact saved source/occurrence evidence and require no nonexistent endpoint revision; IF exact repair identity cannot be established or any existing affected endpoint UUID is ambiguous, it SHALL return repair unavailable without choosing a physical record. Removal of one identified occurrence SHALL NOT remove other equivalent physical occurrences implicitly.  +4. <a name="5.4"></a>WHEN imported changes create multiple equivalent physical occurrences, cardinality/cycle/endpoint faults or conflicting active/removal evidence, the system SHALL preserve and identify each available conflicting occurrence rather than arbitrarily choose a valid logical identity, blocker or canonical target. Explicit removal-only repair SHALL be allowed to reduce precisely identified invalid evidence without requiring all corruption to be repaired in one request; invalid evidence outside the affected change SHALL NOT prevent such removal, and no unrelated addition or automatic cleanup SHALL accompany it.  +5. <a name="5.5"></a>Caller documentation and readback SHALL state that validation/revisions describe locally imported saved evidence and protection applies to participating Transit writes. Independent writers or sync imports MAY change that evidence between validation and save and temporarily leave inconsistent links that MAY remain until explicit repair; subsequent saved readback SHALL derive current blocker/canonical assessments and detect/report available missing/ambiguous/invalid endpoint, identity, cycle, cardinality and active/removal conflicts under 2.3, 3.4, 5.3 and 5.4, without automatic repair or a claim of global remove-wins semantics. A valid endpoint status change SHALL update its assessment rather than be labeled a historical race conflict.  +6. <a name="5.6"></a>WHEN schema/revision coverage is introduced, preexisting tasks SHALL remain readable with no links, original task history and unrelated fields unchanged. Retained historical receipts/pages SHALL retain their original bytes/revisions/meaning; exact protected receipt replay SHALL precede fresh-write coverage validation. Old captured/receipt evidence SHALL be explicitly distinguishable as lacking graph coverage rather than reminted or relabeled, while T-2384/T-2383 validators SHALL retain their approved r1 token format.  ++### 6. Relationship queries and frozen observations++**User Story:** As an agent, I want filtered and coherent relationship readback, so that I can select work without independently joining changing records.++**Acceptance Criteria:**++1. <a name="6.1"></a>Ordinary `query_tasks` SHALL support link presence/type and opposite-endpoint UUID filters plus unblocked selection, combined with existing selectors/filters. `blocks`/`blocked-by` SHALL match the candidate's named dependency view; relates-to SHALL match either orientation; introduced-by/duplicate-of SHALL support explicit outgoing or incoming direction, default outgoing. Incoming duplicate-of SHALL find direct target tasks, which may themselves be duplicates, and SHALL NOT imply transitive incoming matching; outgoing duplicate-of SHALL find duplicates. Unsupported/conflicting options SHALL reject without changing unrelated ordering/status/count semantics.  +2. <a name="6.2"></a>Full task detail SHALL expose incident links, explicit invalid-edge diagnostics, direct duplicate/canonical resolution and blocker assessment where established; queries omitting link bodies SHALL retain the authoritative covered revision, and omission SHALL NOT be interpreted as an empty link set.  +3. <a name="6.3"></a>Every relationship-aware query SHALL use one immutable saved local observation for selected tasks, endpoint identities/statuses, edges and required comments; unsaved insert/edit/delete state SHALL NOT appear. A required fetch/capture failure SHALL be a failed read rather than an empty relation, no blockers or successful partial canonical resolution.  +4. <a name="6.4"></a>New ordinary captured queries SHALL identify graph-evidence coverage and support relationship filters/readback within their declared task scope; cross-project closure SHALL support evaluation without making closure tasks selectable or changing portfolio totals. Retained graph-aware pages SHALL preserve original edges, assessments, revisions, metadata and expiry after edits/imports. T-2382 reusable queries SHALL retain their approved project/status options and exclusion of comment bodies; graph filters against them SHALL return the existing unsupported-option error. Views lacking graph evidence SHALL explicitly report unavailable graph coverage rather than live-enrich or imply no links. Added retained evidence SHALL remain within unchanged five-minute/eight-view/16-MiB lifecycle/accounting limits.  +5. <a name="6.5"></a>Relationship capture/filter/traversal and result encoding SHALL fit T-63's five-second covered-read budget and eight-unfinished-physical-read limit; deadline or capacity failure SHALL return the defined typed failure without partial success or late cursor/snapshot publication. Graph traversal SHALL stop on repeated identities and budget/capacity exhaustion.  +6. <a name="6.6"></a>Results SHALL retain T-63/T-2382 original `snapshotId`, `asOf` and freshness meaning, and T-2383 latest-only structured/text parity and failure categories; a recent import SHALL NOT imply complete remote graph convergence, and missing supported navigation SHALL remain explicit rather than produce guessed URLs.  ++### 7. Native visibility and compatibility++**User Story:** As a user, I want to see recorded relationships, so that agent-managed links do not remain hidden in my tasks.++**Acceptance Criteria:**++1. <a name="7.1"></a>WHEN native task details show a saved task, they SHALL show recorded incident link types, target identities/labels and explicit unresolved/canonical diagnostics using existing task-detail and navigation patterns; labels SHALL NOT be taken from unsaved endpoint drafts, and no inline link editor or consolidation action SHALL be added.  +2. <a name="7.2"></a>WHEN a resolved relationship target is selected in native task details, navigation SHALL open that exact task UUID through existing in-app navigation; missing/ambiguous targets SHALL remain a diagnostic rather than open an arbitrary task.  +3. <a name="7.3"></a>Existing create/update/status/comment behavior without link arguments SHALL retain field semantics, permissions and retry guarantees, with current graph-covered revisions required for fresh preconditioned writes under 5.1. T-2384 batches SHALL initially reject link directives as unsupported shape before any item/key acceptance, retain their approved fields and ordered per-item/advisory-preview semantics, and SHALL NOT gain incidental multi-endpoint link changes, implicit revision chaining, whole-batch graph atomicity or consolidation undo.  +4. <a name="7.4"></a>Published schemas and caller guidance SHALL document type/direction normalization, cardinalities, preconditions, no-op/repair/removal behavior, blocker/canonical rules, saved-only scope and link/revision compatibility; accepted historic receipt shapes and omission of graph evidence SHALL be explicit.  ++### 8. Verifiable behavior++**User Story:** As a maintainer, I want edge-case coverage, so that graph changes cannot bypass write or read safety.++**Acceptance Criteria:**++1. <a name="8.1"></a>Automated verification SHALL exercise all type directions/inverses, reversed association deduplication, self/duplicate/colliding UUIDs, cross-project links, add/remove/retarget/no-op/cardinality behavior, dependency and duplicate cycles, multiple attribution sources, Done versus Abandoned blockers, canonical chains and invalid-graph repair.  +2. <a name="8.2"></a>Automated verification SHALL exercise coordinated participating writes, immediate saved validation, all-or-none source/edge/removal/terminal-receipt saving, revision races and documented independent-writer limits, retained replay before graph lookup, exact-key mismatch, restart/save/delivery failure and uncertainty, dirty UI contexts and independently observed saved readback, without weakening T-2380 guarantees.  +3. <a name="8.3"></a>Automated verification SHALL exercise migration, endpoint deletion/dangling links, explicit removal/re-add and imported invalid/removal conflicts, scoped closure evidence, omitted bodies/revision coverage, frozen cursors/reusable views, deadlines/capacity/late publication and native exact-UUID navigation; no test SHALL claim CloudKit-wide convergence from local evidence.  
specs/typed-task-links/scope-assessment.md Changed +108 / -0
diff --git a/specs/typed-task-links/scope-assessment.md b/specs/typed-task-links/scope-assessment.mdnew file mode 100644index 00000000..3fd57878--- /dev/null+++ b/specs/typed-task-links/scope-assessment.md@@ -0,0 +1,108 @@+# T-1734 — Typed task links: initial scope assessment++Status: **scope, full-spec route, name and listed types approved** by the owner at `Sentinel_2f1bde004c10819186e2b02bbc23023e`, as verified by the parent on 2026-10-03. Name: **`typed-task-links`**. Requirements, design and tasks remain separate gates. This starts the relationship foundation ahead of deferred T-2381 consolidation; T-2382 portfolio work stays active. Recommendations below describe the approved routing proposal; detailed behavioral choices are being taken through requirements review.++Public relation naming is consistently kebab-case following owner correction `Sentinel_54fa08e7dbb881919d2c718f23bfb0fe`: **blocks, blocked-by, relates-to, introduced-by, duplicate-of**. This changes the duplicate spelling in the initial proposal, without introducing an alias or approving detailed requirements. Historical source tickets/comments retain their original text.++## Recommendation++Specify one task-link foundation covering dependencies, associations, task-based regression attribution, and explicit duplicate relationships. Provide protected link mutations and saved-only detail/filter readback through the existing task tools. The foundation makes relationships visible to callers; linking a duplicate does not merge content, choose equivalence, close a task or perform undo.++Ask the owner to approve the scope, full-spec route and name before drafting requirements. Confirm any additional recently discussed type names that the checked sources do not establish. Requirements, design and tasks then have separate explicit approval gates. Implementation is not authorized by the instruction to start specs.++## Owner direction and verified checkout++- Owner message `Sentinel_491f1fff691c819189b3f7535e2465c3`: “It's probably more important/useful to implement 1734 first. So, table 2382 until that's done and expand 1734 with the various types that we've discussed recently as needing and then start with its spec”.+- The parent asked whether the pause meant T-2381 duplicate consolidation rather than T-2382 portfolio summaries. Owner clarification `Sentinel_4165673ac91c8191befe3f7d137a6d8c`: “Yes, typo, thanks for catching it”. Therefore T-2381 is deferred and T-2382 is not paused.+- Canonical `/Users/arjen/projects/personal/transit` remains on `main`, with its untracked `.kiro/` preserved. Local `main`, `origin/main` and live `git ls-remote origin refs/heads/main` matched **`201205bd4e786c7f152d8f99006b37da7da888c7`** immediately before checkout creation on 2026-10-03.+- Separate checkout: `/Users/arjen/Documents/Codex/2026-10-03/task-6/transit-t1734`, branch **`T-1734/typed-task-links`**, created from that explicit SHA. The T-2381 branch and scope document remain preserved at `bf4f40a`; this work does not reuse their identity.+- Applied the local Transit router and Starwave full-spec guidance, repository `CLAUDE.md`, SwiftData/JSON rules, and existing approved MCP foundation specs/ownership handoffs. No existing spec is edited.+- T-1734's description expansion was committed by the live MCP endpoint at `2026-10-03T12:40:19.440Z`, using fresh observed revision `r1:452d046508550ff12315735ba31cde3115827e1bcf9561a747fccbab23d249c4` and key `t1734-scope-expansion-20261003-7ce9e596`. Full readback exactly matched the appended description, retained all original description text, and verified name/type/priority/metadata unchanged. Current revision: **`r1:b829c52abd78e8fb23c1f3072930c63aa866560a793b0c9fd26481f5f3aec0da`**. Status remains **Idea** until scope approval.++## Exact relationship inventory and sources++| Type or projection | Established source | Proposed meaning/boundary |+| --- | --- | --- |+| `blocks` / `blocked-by` | Original live T-1734 description | Dependency edge and its inverse view. Support excluding tasks whose blockers are not done. The T-1733 → T-1732 dependency is the ticket's concrete motivating example. Whether both spellings are accepted mutation inputs or only projections is not yet decided. |+| `relates-to` | Original live T-1734 description | Association without dependency semantics. Symmetry and physical edge normalization must be specified rather than guessed. |+| `introduced-by` | Original live T-1734; T-1732 regression attribution; T-1733 workflow adoption | Directed task-based attribution. PR-number fallback remains possible where no introducing task exists; adding regression tri-state fields or changing filing/eval skills stays with T-1732/T-1733. |+| `duplicate-of` | Live T-2381 description, initial T-2381 scope at `bf4f40a`, and owner direction to expand T-1734 first | Directed duplicate-to-canonical relationship, with explicit invalid-target/cycle/canonical resolution semantics. Kebab-case spelling is settled by the naming correction; reverse/read projections and detailed semantics await requirements approval. No consolidation action follows implicitly. |++This is **four semantic relationship kinds**; `blocks` and `blocked-by` are opposite views of the dependency kind, not proof that two independent stored edges are required. “Depends on” in existing prose does not establish an additional kind. “Canonical” is duplicate resolution/readback, not an independently sourced relation type.++The reviewed ticket sources and checked recent parent discussion do not name `supersedes`/`superseded-by`, parent/child, follow-up, split-from or copy-of as requested types. Do not invent requirements for them. The word “Supersedes” in T-1734 describes replacing text-only dependency notes, not a supersession edge request. T-649 requests copying a task, which is not evidence for a copy-of relationship. If other recently discussed types were intended, the parent should obtain their exact names/use cases or source messages before requirements are written.++## Why full spec++1. **User-owned behavior:** blocker completion, symmetric association, duplicate chains, cross-project links, link edit semantics and native visibility have multiple reasonable behaviors not chosen by current code.+2. **Persisted/public contract:** SwiftData/CloudKit relationship representation, revisions and MCP inputs/results/query filters become data and consumer contracts. A source revert cannot safely undo persisted links.+3. **Contested architecture:** a dedicated link entity, task-owned serialized links and native model relationships have different identity, migration, inverse, revision and local transaction boundaries. The design must select one after requirements and feasibility review.++At the verified base, `TransitTask` has no typed task links. `TaskService.findByID` returns the first UUID match; display-ID lookup explicitly rejects collisions. T-2380 task revisions cover fields, assignments and complete comments, with no graph state. The implementation cannot inherit first-match identity behavior or assume current task revisions already guard link changes.++## Proposed included work++- A single typed task-link representation and reusable service with stable UUID identity, supported types, normalization, inverse read views, duplicate-edge handling and clear add/remove/change semantics.+- Validation of source/target identity and reference existence, self-links, allowed cardinality, cycles where relevant, and local graph invariants. Imported missing/ambiguous/corrupt references are reported without silently choosing a target or repairing data.+- Link mutation inputs in `create_task` and `update_task`, as the original ticket requests, integrated with the shared T-2380 write coordinator. Specify revision coverage and transaction boundaries for every affected record. A link edit must not flush or roll back unrelated unsaved UI edits.+- Saved-only task-detail relationship readback and `query_tasks` filtering by link presence/type and target, including the original unblocked-work use case. Include enough UUID/direction information that consumers stop parsing task descriptions for dependencies.+- Duplicate target/canonical readback suitable for later T-2381, with explicit safe behavior for chains and invalid graphs. No semantic equivalence classifier or automatic retargeting of ordinary writes.+- Compatibility with bounded capture, cursor/reusable snapshot evidence, structured results and generic batches after their compatible foundations merge. Frozen captures and historic receipts retain their original meanings.+- Focused eventual regression coverage for identity, graph/filter semantics, saved-only observations, protected mutations, migration/sync limitations and failures. No heavy test or build is part of this scope-assessment work.++Native surface recommendation for discussion: make relationships visible in task details using existing navigation patterns, with MCP creation/editing initially. A full native link editor, automated bug-blitz/next-task adoption and App Intent mutation parity should be included only if the owner explicitly chooses them. The original ticket establishes query support for those workflows, not permission to modify external workflow repositories.++## Ownership and exclusions++| Ticket | Responsibility retained |+| --- | --- |+| T-1734 | Link types, common storage/validation/service, protected link edits and relationship read/query contract. Duplicate linkage is included in this one foundation. |+| T-2381, deferred | Caller semantic-equivalence decision, survivor selection, detail preservation, consolidation preview/apply/undo, audit/provenance and operation recovery. No status changes or merging are triggered by a T-1734 duplicate link. |+| T-1732 | Regression yes/no/unknown data and PR-number attribution fallback where appropriate; do not silently absorb its tri-state feature. |+| T-1733 | Bug-filing/root-cause workflow and eval adoption; its dependency example informs T-1734 but does not authorize harness changes. |+| T-649 | Copying a task from the task detail sheet. |+| T-63 / T-2382 / T-2383 / T-2384 | Their approved capture/snapshot/protocol/batch contracts and present shared-file ownership. T-1734 coordinates integration and does not rewrite their specs or concurrently edit owned files. |++Exclude automatic semantic matching, content synthesis, task consolidation, duplicate closure, permanent deletion, full status history, a new task hierarchy, global CloudKit graph transactions, receipt/guard resets, and unsupported navigable URLs.++## Product choices for the requirements gate++| Decision | Recommendation to discuss, not an approved requirement |+| --- | --- |+| Vocabulary | Preserve existing meanings and add `duplicate-of`; kebab-case public spelling is settled. Any genuinely additional types need explicit use cases and approval. |+| Dependency orientation | One logical edge, with `blocks`/`blocked-by` read views; decide accepted input aliases and normalization. |+| Blocker completion | Begin with the ticket's exact “not done” rule: abandoned is not automatically completed. Decide missing/ambiguous/cyclic blockers and fail-closed unblocked filtering explicitly. |+| Cross-project links | Allow explicit same-store UUID targets across projects, since task dependencies/attribution need not share a project. Validate identities; never move either task or milestone. |+| `relates-to` | Symmetric association with idempotent duplicate-edge handling; decide how one edit covers both read directions and revisions. |+| Duplicate chains | At most one direct duplicate target per source; resolve canonical identity deterministically and reject self-links/cycles locally. Decide permitted chains, retargeting, terminal targets, and behavior under imported invalid graphs. |+| Link changes | Explicit add/remove operations rather than accidental full-list replacement; choose whether task creation/property editing and links save atomically together. The final MCP shape belongs in design. |+| Revision coverage | Guard link mutation using covered saved graph evidence, including affected inverse views where necessary; target status changes must affect blocker-filter results without rewriting history. Preserve receipt replay independently of live state. |+| Native/App Intent surfaces | Minimal task-detail visibility plus MCP mutation/query initially; decide editors and App Intent parity before requirements. |+| Limits and history | Bound links/request/query traversal; decide edge reason/audit need and deletion/dangling policy without turning T-1734 into consolidation provenance. |++## Foundation and integration prerequisites++- **Merged base T-2379/T-2380:** preserve bounded full-detail queries, complete comment-covered revisions, receipt key scope/expiry and exact historical replay. New link coverage needs an explicit version/migration decision; do not remint historical receipt tokens or rewrite saved outcomes. CloudKit-delayed edits are not detected by a local revision and later imports can conflict.+- **T-63:** saved-only immutable DTO capture, five-second covered-read deadline, eight unfinished physical read permits, honest freshness and coordinated publication. T-63 retains common read/server/type ownership until its verified handoff. Link traversal/filter capture must fit the same boundary without exposing unsaved or independently fetched graph state as coherent evidence.+- **T-2382, still active:** reusable captured views and summary reconciliation. Add graph evidence through agreed capture contracts; do not fabricate a second snapshot system or silently redefine summary counts.+- **T-2383:** approved MCP `2026-07-28` latest-only adapter and structured/text result parity. Existing historical receipt evidence stays frozen; task/project navigation is unavailable until supported, not guessed.+- **T-2384:** current owner of `MCPWriteCoordinator`. Its batch supports existing task update/status/comment operations with one target operation per batch item, ordered per-item commitment and no whole-batch rollback. Adding link arguments later needs agreed validation/receipt integration, not a competing coordinator or changed batch guarantee.+- **Schema/release:** select and verify an additive SwiftData/CloudKit-safe model and migration, including all ModelContainer/schema call sites and test factories. Production schema publication is a later explicit release prerequisite, not work authorized here.++The spec can progress after its gates while declaring foundation assumptions. Implementation and final integration wait for compatible merged contracts, a newly verified base, settled ownership transfers, refreshed actual tool discovery and separate implementation authorization. Existing endpoint query discovery lags the T-2379 repository selectors; live ticket readback is not evidence of client activation or schema adoption.++## Risks to resolve early++- **Graph identity/sync:** duplicate UUIDs, dangling edges and cross-device cycles cannot be solved by first-match lookup or a local check presented as a global guarantee. Design must define diagnostics and safe local mutation rejection.+- **Revisions and replay:** inverse views and graph changes may require multi-record preconditions; historical receipts, content tokens and no-ops must remain truthful. Replay precedes live validation under T-2380.+- **Capture cost/coherence:** dependency/canonical traversal and target status evidence must be bounded and saved-only within the shared observation boundary. Failure cannot appear as “no blockers” or “no duplicate”.+- **Meaning drift:** “abandoned means unblocked”, “introduced-by means regression=yes”, and “duplicate link means close/merge” are different product decisions; none follows implicitly from the relation label.+- **Scope creep:** verify every new type against a specific owner use case; keep consolidation, regression tri-state, workflow adoption and copying in their ticket owners.++No implementation, build/test, settings change, deployment, push or main/PR merge has occurred. Per-command escalation succeeded for origin verification and isolated checkout creation. The T-2381 record was not abandoned, deleted or moved to a new status; its deferral is conveyed by the parent direction and this assessment. T-2382 was not changed.++## Exact next approval for the parent++**“Approve a full spec named `typed-task-links` for T-1734, covering `blocks`/`blocked-by`, `relates-to`, `introduced-by`, and `duplicate-of`, with consolidation remaining deferred in T-2381? If other recently discussed relationship types were intended, which exact types and use cases should be included before requirements?”**++After approval, re-read T-1734 and perform its authorized transition to Spec with an approval comment. Then draft/review requirements and request their explicit approval. Future requirements/design peer reviews use the documented internal independent-peer fallback if external reviewers are unavailable; no unapproved external source disclosure is authorized.
specs/typed-task-links/task14-checkpoint.md Changed +9 / -0
diff --git a/specs/typed-task-links/task14-checkpoint.md b/specs/typed-task-links/task14-checkpoint.mdnew file mode 100644index 00000000..d866a8d9--- /dev/null+++ b/specs/typed-task-links/task14-checkpoint.md@@ -0,0 +1,9 @@+# Owned link-write integration checkpoint++The foundation reconciliation preserved old typed checkpoint `7d7271f0c86ed337ae52b0cb49fc152fea8f6a47` on local branch `T-1734/pre-landed-foundation-20261005`. Exactly 21 unique typed commits were rebased from the reviewed T-2384 foundation `fe76adae712045d770b902c02b6f86c8e4980f9e` onto landed `origin/main` `e04c1268ee37bd4ae925d4d686954cf2121005c7`, producing `9c8695e0070666b0902434c26b449881ba8d3023`. Code, tests and Makefile were identical before and after reconciliation. Only three already-landed batch review documents differed (17 additions, two deletions). The old worktree and canonical main were preserved; no ancestry-only verification rerun was required.++Task 13's actual protected-handler RED run at `9c8695e` is retained at `/var/folders/11/v0tnfm294kd9c6zll_ncmpkh0000gn/T/t1734-writes-red.hxgi38zq`: build exit 0, run exit 65, 15 expanded failures, zero passes/skips/runtime warnings, host PID 16289 drained. The missing adapter rejected link-bearing operations before acceptance; these were behavioral capability failures rather than compilation or discovery failures.++The task 14 candidate installs the feature adapter in the production handler and each participating batch item. Each operation receives a fresh sealed service scope and plan holder. Saved source and endpoint preconditions and the complete proposed graph are validated synchronously; command-owned task application precedes exact physical graph deletion/addition, and the final covered record and receipt share the existing sole domain save. Creation chooses its final UUID after allocation and uses it in the proposed graph and insertion. No independent-writer/import exclusion or remote atomicity is claimed.++Focused strict SwiftLint and whitespace checks passed before pinning this candidate. Runtime GREEN remains pending; this note does not mark task 14 complete.
specs/typed-task-links/task20-checkpoint.md Changed +12 / -0
diff --git a/specs/typed-task-links/task20-checkpoint.md b/specs/typed-task-links/task20-checkpoint.mdnew file mode 100644index 00000000..dfbae234--- /dev/null+++ b/specs/typed-task-links/task20-checkpoint.md@@ -0,0 +1,12 @@+# Native relationship checkpoint++Task20 native implementation is verified locally. Eight expanded unit controls passed at49d3be7 (kjpg5jif), including pending-delete, saved UUID ambiguity, unsaved identity and canceled/stale observation guards; build/run0, host36479 drained. The final UI seed save and layout gestures are163a098.++The signed development iPhone17/iOS27 UI artifact ju4u1e8b confirms two cases passed, no failures/skips/runtime warnings: exact UUID destination opening and unresolved ambiguous destination diagnostics. It consumed the successful163a098 build8o643623 after a pre-launch V1/V2 wrapper layout correction. Bundle identity me.nore.ig.Transit.development, simulator entitlements empty, ui-test memory storage. Original wrapper/xcodebuild exit status was lost when the executor session disappeared; it is unavailable, not asserted0. Native xcresult and raw TEST EXECUTE SUCCEEDED are preserved. Recovery summary/tree extraction succeeded; bounded shutdown/delete of ONLY owned3743ABE3-B7C3-4265-9352-AA6A4BE3FA38 succeeded, final owned census empty. Logs and recovered-drain.json remain in the private artifact root.++Artifact roots:+- /var/folders/11/v0tnfm294kd9c6zll_ncmpkh0000gn/T/t1734-native-green-projectfix.kjpg5jif+- /var/folders/11/v0tnfm294kd9c6zll_ncmpkh0000gn/T/t1734-native-ios-ui.8o643623+- /var/folders/11/v0tnfm294kd9c6zll_ncmpkh0000gn/T/t1734-native-ios-ui-v1.ju4u1e8b++The fresh iOS build logged34 existing compiler-warning lines, none in typed-link/new native files; the complete build log remains for final warning classification. Compile-only fixture failures and pre-launch layout rejection remain separate from runtime evidence. Full final platform suites are still task22 work. No CloudKit account, production app, or live data was touched.
specs/typed-task-links/task4-checkpoint.md Changed +51 / -0
diff --git a/specs/typed-task-links/task4-checkpoint.md b/specs/typed-task-links/task4-checkpoint.mdnew file mode 100644index 00000000..6e1f94c9--- /dev/null+++ b/specs/typed-task-links/task4-checkpoint.md@@ -0,0 +1,51 @@+# Task4 checkpoint — scheduling pause++Committed foundation integration: `9fbb626997488e22ad29a544e865f9d009455b7f`.+Opt-in owned scope and 15 new control cases: `9ab65c8`.+Actual attempted source: `fc9a9d0af3ea6eb5a55bc2d03aaed0f715d59f08`.+User explicitly approved T1734 implementation, local commits and isolated verification;+the prior automatic approval-review block was resolved before this commit/build.++The final T2384/T2382/T63/T2383 foundation is locally integrated. Task3 completion+is based on its prior actual 15-case passing result, not an invented stale-cache RED.+Task4 is in progress and is **not complete**. Its opt-in scope, sealed service+construction, full original receipt binding and selected-context rejection/recovery+are committed; they have no runtime acceptance yet. Existing nil/default policy+behavior is intended to remain unchanged.++## Exact attempted job++Evidence directory:+`/var/folders/11/v0tnfm294kd9c6zll_ncmpkh0000gn/T/t1734-scope.d0x4ki_r`.+The private locked-package build used the proven signed development unit-host+recipe. Planned selection was the prior 15 cases plus 15 new owned-scope cases.+Actual `xcodebuild build-for-testing` exited **65** before host preflight or tests.+No test host launched, zero cases executed, and this is a compiler failure rather+than behavioral RED or GREEN. Preserve `build-command.json`, `build.log`,+`build-exit.txt`, `source-head.txt`, private products/cache and `final-drain.json`.++Compiler errors in TaskLinkProtectedBoundaryTests at lines64/91/122/162 show that+existing `MCPBatchWritePolicy { _, _ in ... }` calls bind to the first optional+`makeCommitServices` factory despite validation being last. Swift expects a+one-argument wrapper-returning closure, rather than the two-argument validator.+No production compiler error was observed in the captured log.++Next narrowly scoped correction after scheduling resumes: provide a single+nondefaulted validation-closure compatibility initializer overload that delegates+to the default-nil factory/no-op observer initializer. Preserve the existing+unlabelled trailing-closure API rather than changing fixture labels to hide its+breakage. Actual compilation and the focused 30-case runtime must then establish+the fix and owned-scope behavior; no correction or new run occurred under pause.++## Drain and preserved state++The bounded wrapper observed the owned build child exit normally; no timeout,+sampling or signal was required. A subsequent read-only escalated process census+was needed because default sandbox denied `/bin/ps`. It found no matching owned+xcodebuild/compiler/test host and recorded `drained: true`, `hostLaunched: false`+and `runtimeCases: 0` in `final-drain.json`.++Parent scheduling pause permits finishing this exact active job only while the+foundation PRs land. No graph source, new phase, retry, publication or external+review/disclosure was started. Source is preserved in local commits, main is+untouched, and the worker returns idle awaiting resumed scheduling/new base.
specs/typed-task-links/tasks-review.md Changed +42 / -0
diff --git a/specs/typed-task-links/tasks-review.md b/specs/typed-task-links/tasks-review.mdnew file mode 100644index 00000000..a59094e6--- /dev/null+++ b/specs/typed-task-links/tasks-review.md@@ -0,0 +1,42 @@+# Typed links — task-plan review and approval gate++Current contract: owner `Sentinel_c95239aefa6481919303c2353b8a9e9c` approved participating Transit writes with pre-save validation and outside-writer conflict reporting (decision_log.md ADR 4). The historical all-independent-writer/import validation-to-save fence and persistence-redesign completion gate below are superseded. Original tests, failures and approvals remain historical evidence; owned same-store domain/receipt saving and T-2402 deferral remain unchanged.++Design checkpoint `56e9ad5` was approved by owner `Sentinel_775be6f4fc6c8191a9d7ccf1d0c04557`, including seven-day recognition and early migration/atomic-save feasibility. Local approval record is `1b82a48`; task draft is `da415e1`. Task checkpoint `18a268f` and conditional implementation were approved by owner `Sentinel_d1ba9360969c81918777711b2420bfc7`. Technical foundation/feasibility dependencies remain; no further readiness approval is required.++## Plan and verification++Rune created and managed 22 flat numbered tasks: 11 adjacent Red/Green pairs in one stream. Shared services, snapshots, capture and coordinator wiring make a sequential stream appropriate. Every downstream task directly declares the relevant migration (2), atomic-save (4) and bounded-capture (8) gates, in addition to incremental dependencies.++`rune list specs/typed-task-links/tasks.md` parsed all tasks/dependencies without warnings. A lightweight check confirmed all tasks pending, adjacent Red/Green ordering, valid acyclic dependencies, direct gate links, and all **39 granular acceptance criteria covered before the final integration pair**. No app tests/builds, test fixture execution or implementation occurred. The plan uses owning test containers, serialized Swift Testing and seeded generated graph/reference properties during later authorized implementation.++## Critic and independent peer review++Read the actual local starwave-tasks, Rune, design-critic and peer-review-validator instructions. The documented internal fallback supplied two independent read-only peers because external review tools were unavailable; no source disclosure.++| Review | Finding | Resolution |+| --- | --- | --- |+| Critic | Intermediate parser/schema wiring could expose directives before protected apply integration. | Tasks11–12 test and enforce fresh-link unavailability until task14 passes; no accepted-and-ignored directives. |+| Critic | Local migration/schema-shape tests were not development CloudKit verification. | Tasks1–2 include opt-in isolated development schema/deletion fixture. Full gate2 requires both disk and development evidence; prerequisites name clearance/setup. |+| Critic | Requirement7.4 needs executable caller guidance. | Wire/query Red/Green pairs test and implement schema/output descriptions covering direction, guards, no-ops, removal expiry, local-only guarantees and historic coverage. |+| Critic | ADR2 retained stale pending wording. | Recorded the approved seven-day decision consistently. |+| Correctness peer | No blocking issue; make foundation pre-coding conditions easy to track. | Standalone prerequisite checklist includes all four handoffs, verified merged base and refreshed live schema. |+| Scope peer | No blocking issue; specify missing development-schema setup ownership. | Parent designates authorized development operator; initialize only development schema from task2 models, verify in CloudKit Console, keep task2 incomplete until confirmed. |++Both peers validated the critic's refinements and found no task-approval blocker. No material disagreement remains. The selected commit mechanism is not proven: task4 must demonstrate closure of validation through save against peer-context/import commits; failure keeps writes unavailable and returns design for review before dependent work. Tests cannot mark that task green by weakening the invariant or skipping the race.++## Boundaries and prerequisites++Implementation needs a separate approval and compatible merged T-63/T-2382/T-2383/T-2384 foundations with ownership handoffs. Early gates use synthetic/copied disk stores and an explicitly cleared development CloudKit environment. Development setup and heavy-job scheduling are external prerequisites, not production deployment tasks. No framework history purge, global convergence promise, task deletion, guard reset or production schema promotion is included.++Consolidation T-2381, regression/workflow T-1732/T-1733, copying T-649, native link editing and batch link mutations remain excluded. Live Transit mutations/status/comments stay paused; all bookkeeping is local. The broader testing approval does not authorize T-1734 implementation or a heavy-test slot during spec planning.++## Exact next approval through parent++**“Do the T-1734 typed-task-links tasks look good? Please explicitly approve this task plan. Approval completes task planning only; implementation remains a separate approval and stays blocked by foundation handoffs and the migration/atomic-save/capture feasibility gates.”**++No tasks are claimed or started. Phone transfer outcome is reported separately; it does not constitute approval.++## Task gate outcome++Approved with conditional implementation by owner `Sentinel_d1ba9360969c81918777711b2420bfc7` against checkpoint `18a268f`, relayed by parent. The question above is historical. Live writes/client activation/deployment remain held; tests need the parent queue slot.
specs/typed-task-links/tasks.md Changed +195 / -0
diff --git a/specs/typed-task-links/tasks.md b/specs/typed-task-links/tasks.mdnew file mode 100644index 00000000..49679f0a--- /dev/null+++ b/specs/typed-task-links/tasks.md@@ -0,0 +1,195 @@+---+references:+    - specs/typed-task-links/requirements.md+    - specs/typed-task-links/design.md+    - specs/typed-task-links/decision_log.md+metadata:+    amendment_review: approved-a64e595-Sentinel_08cb318218788191a85da25d1206979f+    approval: approved-18a268f-Sentinel_d1ba9360969c81918777711b2420bfc7+    deferred_ticket: T-2402-Set-up-isolated-CloudKit-integration-testing+    scope: participating-write-coordination-and-owned-save+    scope_amendment: Sentinel_c95239aefa6481919303c2353b8a9e9c-participating-writes+---+# Typed task links implementation tasks++- [x] 1. Red: test pre-feature store migration and schema parity <!-- id:ev1ktkw -->+  - Create serialized Swift Testing disk fixtures in TransitTests/TaskLinkMigrationTests.swift using an owning TestModelContainer and a reproducible pre-feature schema; assert unchanged task/comment fields and retained receipt bytes after reopen, empty graph incidence and both new model registrations.+  - Test defaulted/optional CloudKit-compatible scalar schema, no unique/cascade attributes, UUID physical multiplicity and every app/probe/container schema listed by the design audit. Use copied or synthetic test stores only.+  - Retain the prepared optional development CloudKit schema/deletion smoke source outside default targets; its compilation, isolated environment setup and live execution are deferred to the separate owner-requested ticket. Do not claim its assertions executed or remote convergence.+  - Stream: 1+  - Requirements: [5.1](requirements.md#5.1), [5.6](requirements.md#5.6), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md++- [x] 2. Green: implement pre-feature store migration and schema parity <!-- id:ev1ktkx -->+  - Add Models/TaskLinkOccurrence.swift and TaskLinkRemovalEvidence.swift with immutable scalar identities/endpoints/kind and separate evidence; wire TransitApp, TestModelContainer and relevant tests/mcp-write-probe schemas.+  - Adapt exact types/imports against the explicit latest verified compatible merged foundation base. Re-audit every schema/snapshot consumer; preserve unrelated task history and production store. If additive disk migration fails, stop dependent work and return the design for review.+  - Complete the in-scope local gate with actual eight-entity closed-store upgrade/final reopen, preserved original fields/receipt bytes/physical multiplicity, empty graph tables, executed scalar/default/optionality/no-unique/no-relationship metadata assertions and all current factory registrations/manual legacy-mode review. Live Development setup/schema/export/deletion verification is explicitly deferred by the owner amendment, not marked passed. No production promotion/records/settings reset. Owned task/link/removal/terminal-receipt saving and participating-write coordination remain required.+  - Blocked-by: ev1ktkw (Red: test pre-feature store migration and schema parity)+  - Stream: 1+  - Requirements: [5.1](requirements.md#5.1), [5.6](requirements.md#5.6), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md++- [x] 3. Red: test coordinated saved validation and owned receipt commitment <!-- id:ev1ktky -->+  - Write disk-backed controls for participating coordinator writes, immediate fresh saved validation, stale registered source/endpoint observations, changed preconditions/cycles before apply, and all-or-none owned domain/graph/receipt save/encoding failures. Preserve existing read-first and internal-save-abort counterexamples as documented-limit evidence; they are not all-writer completion gates.+  - Require all-or-none originating task/edge/removal-evidence/terminal-receipt outcomes in independently reopened saved state; test dirty contexts before acceptance and after await success/error, retained replay without repair/save and uncertain recovery. Recast opt-in outside-writer endpoint/cycle races as allowed-race observations of saved faults, not rejection/no-domain-effect expectations; actual projection diagnostics are exercised by tasks5/6 and integrated tests21/22 after those components exist. Test that participating operations cannot interleave the synchronous final phase; do not claim sync/import exclusion.+  - Blocked-by: ev1ktkx (Green: implement pre-feature store migration and schema parity)+  - Stream: 1+  - Requirements: [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), [5.5](requirements.md#5.5), [8.2](requirements.md#8.2), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md++- [x] 4. Green: implement coordinated saved validation and owned receipt commitment <!-- id:ev1ktkz -->+  - Implement the minimum shared coordinator policy/adapter for the participating synchronous MainActor saved-validation/apply/stage/save phase, with clean checks around preparation and explicit fresh saved resolution. Reuse the T-2384 policy and T-2380 receipt engine; retain one same-store domain/result commitment and existing replay/recovery semantics.+  - Complete the amended coordination, fresh-validation and owned-save tests before dependent graph-write integration. Outside writers/imports may race and produce temporary inconsistent links; projection reports their available evidence without automatic repair or post-commit rollback. No persistence-redesign or all-independent-writer predicate-fence proof is required. Ordinary implementation still stops on unsafe/ambiguous evidence, dirty drafts or uncertain persistence.+  - Blocked-by: ev1ktky (Red: test coordinated saved validation and owned receipt commitment)+  - Stream: 1+  - Requirements: [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), [5.5](requirements.md#5.5), [8.2](requirements.md#8.2), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md++- [x] 5. Red: test normalized graph projection and exact change planning <!-- id:ev1ktl0 -->+  - Write TaskLinkGraphTests/TaskLinkPlanTests with seeded Swift Testing generated small graphs and an independent reference for inverse/reversed normalization, permutation invariance, SCC membership, direct blockers and duplicate paths.+  - Cover cross-project/missing/colliding identities, imported repeated occurrences, Done/Abandoned/unknown, valid Done ancestry exceptions, duplicate cardinality/chains/cycles/retarget and removal-only incremental repair. Seed outside-writer race faults into actual projection expectations for updated endpoint assessments and cycle/cardinality/identity/removal diagnostics, preserving the original committed receipt. Exact selector collisions fail closed; same-logical remove/add rejects; missing endpoint needs no invented revision.+  - Blocked-by: ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment), ev1ktkx (Green: implement pre-feature store migration and schema parity)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [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.2](requirements.md#4.2), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [8.1](requirements.md#8.1)+  - References: design.md, requirements.md, decision_log.md++- [x] 6. Green: implement normalized graph projection and exact change planning <!-- id:ev1ktl1 -->+  - Implement value-only TaskLinkGraph/TaskLinkPlan and Services/TaskLinkService normalization/indexing. Preserve all physical matches and malformed evidence; iterative SCC uses every structurally resolvable dependency row without dedup hiding cycle evidence.+  - Project with frozen removal evidence/evaluation instant; distinguish unblocked/blocked/invalid/unavailable. Validate complete proposed results, exact incidence/fingerprint removal and cardinality/cycles; no automatic canonical redirect, flattening, status changes or consolidation.+  - Blocked-by: ev1ktl0 (Red: test normalized graph projection and exact change planning), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [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.2](requirements.md#4.2), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [8.1](requirements.md#8.1)+  - References: design.md, requirements.md, decision_log.md++- [x] 7. Red: test bounded saved capture and graph-closure capacity <!-- id:ev1ktl2 -->+  - Add TaskLinkReadCaptureTests with pending insert/edit/delete in source/endpoint/occurrence/evidence/comments and independent saved contexts, failures/repeated identities and link-only history fence changes.+  - Write early scaling/deadline/retained-byte fixtures under unchanged five-second/eight unfinished-read and five-minute/eight-view/16-MiB limits. Cover cross-project closure not selected/countable, complete cycle evidence, timed-out lingering physical slots, frozen expiry instant and no late publication.+  - Blocked-by: ev1ktl1 (Green: implement normalized graph projection and exact change planning), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment)+  - Stream: 1+  - Requirements: [2.4](requirements.md#2.4), [5.4](requirements.md#5.4), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.5](requirements.md#6.5), [6.6](requirements.md#6.6), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md++- [x] 8. Green: implement bounded saved capture and graph-closure capacity <!-- id:ev1ktl3 -->+  - Extend T-63 CapturedReadView/ReadTask/MCPReadCaptureBuilder DTOs, fence and prepared capture path with occurrence/removal-evidence/endpoint closure. Use fresh autosave-disabled saved contexts and immutable Sendable values; no @Model return from child tasks.+  - Gate downstream capture/query work on passing bounded capacity fixtures. On excess return existing typed failure and optimize within budgets; no larger cap/partial unblocked result. Freeze graph/evaluation time and charge all retained evidence/index/result bytes; defer current task revision wiring to the next pair, never falsely mark absent evidence empty.+  - Blocked-by: ev1ktl2 (Red: test bounded saved capture and graph-closure capacity), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment)+  - Stream: 1+  - Requirements: [2.4](requirements.md#2.4), [5.4](requirements.md#5.4), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.5](requirements.md#6.5), [6.6](requirements.md#6.6), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md++- [x] 9. Red: test graph-covered current task revision and historic result compatibility <!-- id:ev1ktl4 -->+  - Add TaskLinkRevisionTests covering explicit empty incidence transition, incoming endpoint tokens, physical multiplicity/raw corrupt tuples, changed labels/status/evidence expiry exclusion and hidden link/comment bodies.+  - Exercise every MCPRecordSnapshot.task callsite: ordinary/full/reusable detail, create/update/status/add_comment and probes. Old tokens must conflict on fresh task status/property edits even no-link tasks; exact historic receipt replay stays byte-identical before current lookup.+  - Blocked-by: ev1ktl3 (Green: implement bounded saved capture and graph-closure capacity), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment)+  - Stream: 1+  - Requirements: [1.5](requirements.md#1.5), [4.2](requirements.md#4.2), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6), [6.2](requirements.md#6.2), [6.4](requirements.md#6.4), [6.6](requirements.md#6.6), [7.3](requirements.md#7.3), [8.2](requirements.md#8.2), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md++- [x] 10. Green: implement graph-covered current task revision and historic result compatibility <!-- id:ev1ktl5 -->+  - Require incidence coverage in MCPRecordSnapshot.task overloads; add linkContract and sorted incident tuples to canonical covered fields and revisionCoverage/graphCoverage to current task results while retaining r1 syntax.+  - Wire the completed saved capture and all write/result callsites to the authoritative builder. Preserve T-2383 historical raw fragments and explicit missing coverage; never remint old receipts/pages or fabricate graph coverage for legacy fixtures.+  - Blocked-by: ev1ktl4 (Red: test graph-covered current task revision and historic result compatibility), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment), ev1ktl3 (Green: implement bounded saved capture and graph-closure capacity)+  - Stream: 1+  - Requirements: [1.5](requirements.md#1.5), [4.2](requirements.md#4.2), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6), [6.2](requirements.md#6.2), [6.4](requirements.md#6.4), [6.6](requirements.md#6.6), [7.3](requirements.md#7.3), [8.2](requirements.md#8.2), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md++- [x] 11. Red: test standalone wire deltas and accepted domain plan validation <!-- id:ev1ktl6 -->+  - Write TaskLinkWireTests for exact kebab-case types, UUID/l1/r1 shapes, 50 directives, create-additions-only, omitted fields, unique endpoint preconditions and inverses.+  - Separate pre-acceptance shape errors from saved-edge/semantic conflict validation after retained replay. Cover precise affected endpoints, source no-op guard, unknown/expired selector, retained no-op source incidence, physical UUID collisions, and duplicate retarget versus same-logical remove/add. Batch link fields reject before any item/key acceptance.+  - Add negative enablement tests: before protected task14 wiring succeeds, fresh link-bearing requests are unavailable rather than accepted/ignored. Assert schema descriptions cover directions, affected endpoint guards, no-op/repair/removal expiry, local-only guarantees and unsupported batches.+  - Blocked-by: ev1ktl5 (Green: implement graph-covered current task revision and historic result compatibility), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment), ev1ktl3 (Green: implement bounded saved capture and graph-closure capacity)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [3.2](requirements.md#3.2), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.4](requirements.md#4.4), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [7.3](requirements.md#7.3), [7.4](requirements.md#7.4)+  - References: design.md, requirements.md, decision_log.md++- [x] 12. Green: implement standalone wire deltas and accepted domain plan validation <!-- id:ev1ktl7 -->+  - Add MCP/Links delta DTO/parser and l1 immutable occurrence fingerprint; extend standalone create/update validation and schemas, supplying TaskLinkPlan with complete captured result and endpoint guards.+  - Explicitly reject linkChanges/endpointPreconditions in T-2384 batch shapes. Keep existing field/permission semantics and all accepted domain failures in the original protected operation; no replacement set, alternate spelling, endpoint-first-match or implicit revision chaining.+  - Tool schema descriptions are executable caller guidance: explain type/direction, exact occurrence/preconditions, omitted versus empty evidence and unsupported batch fields; do not change public type spellings.+  - Keep fresh link-bearing writes unavailable behind the completed participating coordination and owned-save boundary/complete-apply enablement guard until task14 passes. Intermediate schemas must not accept and ignore directives; retained exact replay remains first.+  - Blocked-by: ev1ktl6 (Red: test standalone wire deltas and accepted domain plan validation), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment), ev1ktl3 (Green: implement bounded saved capture and graph-closure capacity)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [3.2](requirements.md#3.2), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.4](requirements.md#4.4), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [7.3](requirements.md#7.3), [7.4](requirements.md#7.4)+  - References: design.md, requirements.md, decision_log.md++- [x] 13. Red: test protected standalone link create/update integration <!-- id:ev1ktl8 -->+  - Write TaskLinkWriteIntegrationTests for mixed task fields/links, allocation awaits, endpoint revision races, no-op exact replay, repair-only unrelated corruption, deleted targets, accepted rejection, delivery/save failure and restart uncertainty.+  - Verify task/occurrence deletion/addition/removal evidence/terminal result in one local save, original-key/tool/store binding and seven-day receipt behavior; dirty UI drafts remain untouched on all success/error/recovery paths. No global CloudKit atomicity claim.+  - Blocked-by: ev1ktl7 (Green: implement standalone wire deltas and accepted domain plan validation), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment), ev1ktl3 (Green: implement bounded saved capture and graph-closure capacity)+  - Stream: 1+  - Requirements: [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), [1.3](requirements.md#1.3), [3.2](requirements.md#3.2), [3.5](requirements.md#3.5), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [7.3](requirements.md#7.3), [8.1](requirements.md#8.1), [8.2](requirements.md#8.2)+  - References: design.md, requirements.md, decision_log.md++- [x] 14. Green: implement protected standalone link create/update integration <!-- id:ev1ktl9 -->+  - Wire MCPWriteCommand prepare/apply and MCPWriteCoordinator execution policy to the completed participating coordination and owned-save boundary and graph plan. Revalidate complete proposed invariants and all affected endpoint guards immediately before the sole attributable domain/result save.+  - Delete only the exact active occurrence and insert separate removal evidence atomically. Re-add gets fresh identity, no-op changes no timestamps/token, endpoint tokens change through incidence only. Retained replay remains first and read-only while dirty; keep uncertainty/reconciliation and enablement guards intact.+  - Blocked-by: ev1ktl8 (Red: test protected standalone link create/update integration), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment), ev1ktl3 (Green: implement bounded saved capture and graph-closure capacity)+  - Stream: 1+  - Requirements: [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), [1.3](requirements.md#1.3), [3.2](requirements.md#3.2), [3.5](requirements.md#3.5), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [7.3](requirements.md#7.3), [8.1](requirements.md#8.1), [8.2](requirements.md#8.2)+  - References: design.md, requirements.md, decision_log.md++- [x] 15. Red: test ordinary query filters, frozen detail and modern result parity <!-- id:ev1ktla -->+  - Write TaskLinkQueryTests for hasLinks/type/opposite UUID/direction/unblocked plus existing selectors, incoming duplicate direct targets, complete blocker assessments and unsupported/conflicting options.+  - Test certified blocked-only unblocked:false, invalid matching neither value, scoped closure/count/order compatibility, frozen pages across edits/imports/expiry, missing graph coverage, reused graph options rejected before publication, and semantic text/structured parity.+  - Assert query/output descriptions cover saved-only scope, blockers/canonical resolution, body omission versus empty incidence, new r1 coverage/old-token conflicts, immutable historic receipts and explicit missing historic graph coverage.+  - Blocked-by: ev1ktl9 (Green: implement protected standalone link create/update integration), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment), ev1ktl3 (Green: implement bounded saved capture and graph-closure capacity)+  - Stream: 1+  - Requirements: [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [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), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.5](requirements.md#6.5), [6.6](requirements.md#6.6), [7.3](requirements.md#7.3), [7.4](requirements.md#7.4), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md++- [x] 16. Green: implement ordinary query filters, frozen detail and modern result parity <!-- id:ev1ktlb -->+  - Wire MCPToolHandler+TaskQuery/definitions to the saved frozen graph and prepared tool result; add links/diagnostics/duplicateResolution/blockerAssessment while preserving authoritative tokens when bodies omitted.+  - Integrate T-2383 frozen encoder fragment and existing T-63 publication gates. T-2382 reusable project/status queries stay unchanged and reject graph options; no live enrichment, broadened selection/counts or guessed navigation URLs.+  - Describe saved-only scope, revision coverage transition, blocker/canonical rules, missing historic graph coverage and supported navigation directly in published tool/output contract guidance.+  - Blocked-by: ev1ktla (Red: test ordinary query filters, frozen detail and modern result parity), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment), ev1ktl3 (Green: implement bounded saved capture and graph-closure capacity)+  - Stream: 1+  - Requirements: [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [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), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.5](requirements.md#6.5), [6.6](requirements.md#6.6), [7.3](requirements.md#7.3), [7.4](requirements.md#7.4), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md++- [x] 17. Red: test seven-day repair evidence expiry and clean maintenance <!-- id:ev1ktlc -->+  - Write TaskLinkRemovalEvidenceTests with both active/evidence import arrival orders, frozen versus fresh evaluation at seven-day expiry, content-token stability, changed evidence-based diagnostics/derived assessments, re-add identity and original-key receipt independence.+  - Verify cleanup affects only expired evidence, never active rows/framework history or UI drafts; future/malformed dates and ambiguous evidence identity defer; post-expiry unknown selectors fail closed, live reads/preview never run cleanup.+  - Blocked-by: ev1ktlb (Green: implement ordinary query filters, frozen detail and modern result parity), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment), ev1ktl3 (Green: implement bounded saved capture and graph-closure capacity)+  - Stream: 1+  - Requirements: [1.3](requirements.md#1.3), [4.4](requirements.md#4.4), [4.5](requirements.md#4.5), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [6.4](requirements.md#6.4), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md++- [x] 18. Green: implement seven-day repair evidence expiry and clean maintenance <!-- id:ev1ktld -->+  - Implement seven-day evidence recognition/expiry and a bounded maintenance hook in TaskLinkService using its own clean autosave-disabled context. Preserve actual platform occurrence deletion and do not add a custom tombstone or history purge protocol.+  - Wire maintenance to an existing safe owned lifecycle hook, outside read/preview/graph commit. Remove only eligible evidence after fresh identity revalidation; stale completion/cleanup must not alter retained graph or imply retry/convergence safety.+  - Blocked-by: ev1ktlc (Red: test seven-day repair evidence expiry and clean maintenance), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment), ev1ktl3 (Green: implement bounded saved capture and graph-closure capacity)+  - Stream: 1+  - Requirements: [1.3](requirements.md#1.3), [4.4](requirements.md#4.4), [4.5](requirements.md#4.5), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [6.4](requirements.md#6.4), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md++- [x] 19. Red: test saved native relationship visibility and unique navigation <!-- id:ev1ktle -->+  - Write TaskLinkNativeProjectionTests and focused automated UI/navigation tests for saved endpoint labels under unsaved drafts, unsaved source unavailable, missing/colliding destination UUIDs, saved import refresh and cancellation of stale task/generation completions.+  - Assert no first-match navigation at click or TaskDetailWindowView resolution; read-only incident direction/canonical diagnostics use the existing iOS/macOS detail patterns.+  - Blocked-by: ev1ktld (Green: implement seven-day repair evidence expiry and clean maintenance), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment), ev1ktl3 (Green: implement bounded saved capture and graph-closure capacity)+  - Stream: 1+  - Requirements: [1.2](requirements.md#1.2), [1.5](requirements.md#1.5), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [5.3](requirements.md#5.3), [6.3](requirements.md#6.3), [7.1](requirements.md#7.1), [7.2](requirements.md#7.2), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md++- [x] 20. Green: implement saved native relationship visibility and unique navigation <!-- id:ev1ktlf -->+  - Wire TaskLinkService.savedDetail and Views/TaskDetail/TaskLinksSection into TaskDetailView Form/LiquidGlassSection, using saved value DTOs and existing exact UUID window/iOS detail navigation.+  - Revalidate unique saved destination at selection and macOS window resolver; unresolved targets remain diagnostics. Cancel stale refresh output; no link editor, merge/closure/undo, guessed URLs or App Intent parity.+  - Blocked-by: ev1ktle (Red: test saved native relationship visibility and unique navigation), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment), ev1ktl3 (Green: implement bounded saved capture and graph-closure capacity)+  - Stream: 1+  - Requirements: [1.2](requirements.md#1.2), [1.5](requirements.md#1.5), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [5.3](requirements.md#5.3), [6.3](requirements.md#6.3), [7.1](requirements.md#7.1), [7.2](requirements.md#7.2), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md++- [x] 21. Red: test integrated regression and schema-contract verification <!-- id:ev1ktlg -->+  - Add focused disk/multi-context regression fixtures tying schema upgrade, protected create/update/repair, revision coverage, frozen captured queries, batch rejection, retention and native navigation together in TaskLinkFoundationIntegrationTests.+  - Assert non-link tool field/status/comment/retry semantics, unchanged T-2382 counts/lifecycle, T-2383 parity/historic bytes and T-63 failure/publication limits. Use synthetic/copy test stores and no production repair/reset.+  - Blocked-by: ev1ktlf (Green: implement saved native relationship visibility and unique navigation), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment), ev1ktl3 (Green: implement bounded saved capture and graph-closure capacity)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [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), [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.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.5](requirements.md#6.5), [6.6](requirements.md#6.6), [7.1](requirements.md#7.1), [7.2](requirements.md#7.2), [7.3](requirements.md#7.3), [7.4](requirements.md#7.4), [8.1](requirements.md#8.1), [8.2](requirements.md#8.2), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md++- [x] 22. Green: implement integrated regression and schema-contract verification <!-- id:ev1ktlh -->+  - Complete shared service/app/tool schema wiring and minimum corrective code exposed by integration fixtures; repeat the final-base parity audit against every schema/snapshot consumer and fill missed equivalent callsites.+  - Run only focused affected tests first, then repository-required lint/build/unit/simulator checks through parent heavy-test queue with per-command approval. Preserve all non-goals; failures return to the responsible pair/design gate, not retries against live records or relaxed owned-save protections/budgets.+  - Blocked-by: ev1ktlg (Red: test integrated regression and schema-contract verification), ev1ktkx (Green: implement pre-feature store migration and schema parity), ev1ktkz (Green: implement coordinated saved validation and owned receipt commitment), ev1ktl3 (Green: implement bounded saved capture and graph-closure capacity)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [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), [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.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.5](requirements.md#6.5), [6.6](requirements.md#6.6), [7.1](requirements.md#7.1), [7.2](requirements.md#7.2), [7.3](requirements.md#7.3), [7.4](requirements.md#7.4), [8.1](requirements.md#8.1), [8.2](requirements.md#8.2), [8.3](requirements.md#8.3)+  - References: design.md, requirements.md, decision_log.md
specs/typed-task-links/verification-readiness.md Changed +72 / -0
diff --git a/specs/typed-task-links/verification-readiness.md b/specs/typed-task-links/verification-readiness.mdnew file mode 100644index 00000000..06e4968a--- /dev/null+++ b/specs/typed-task-links/verification-readiness.md@@ -0,0 +1,72 @@+# T-1734 queued independent verification++Prepared source checkpoint: `b9d65b9e483ea59d65ed458851132184dab1331f`, on `T-1734/typed-task-links`. Containment's `3194e5a64dedb004dbfca3666bf590a552b676ee` is consumed as `e1c1ac4`; fixture lint correction is `d2cc0c6`. The final documentation commit adds no executable source. Record actual HEAD in each run's evidence.++Static evidence: development configuration/ownership/source guards and strict SwiftLint pass, 406 files and zero violations; helper Python AST parse passes. Delivered manifest hashes match except the intentional fixture-only lint correction. MCP/read/write, models and TestModelContainer remain unchanged by containment integration. No compiler probes, app builds, codesign preflight, host launches or tests have run on this combined source.++T-2383 holds the exclusive heavy-test slot. Execute the following only after the parent releases that slot to T-1734. Existing conditional implementation approval remains sufficient; this is scheduling coordination, not a new product approval. Use per-command escalation when required by the execution sandbox; never change global permissions. Stop at any offline, build, signature, host-smoke or preflight failure. Preserve logs and artifacts locally. Do not send routine phone reports.++## Exact future command sequence++Run from this checkout in one shell after slot handoff. Fresh private paths prevent reusing another owner's artifacts. Locked package flags fail if required local package inputs are unavailable; stop and report that blocker rather than resolving new versions. These commands do not modify main, activate clients, initialize a CloudKit schema or mutate live task data.++```sh+set -euo pipefail+cd /Users/arjen/Documents/Codex/2026-10-03/task-6/transit-t1734+test -z "$(git status --porcelain)"+test "$(git branch --show-current)" = T-1734/typed-task-links+T1734_RUN_ROOT=$(mktemp -d /tmp/t1734-independent.XXXXXX)+git rev-parse HEAD > "$T1734_RUN_ROOT/source-head.txt"++# Offline probes: synthetic stores with the owner runner's network/live denial.+make test-development-isolation DERIVED_DATA="$T1734_RUN_ROOT/offline"++# Dedicated signed development host: preflight precedes its one smoke case.+make test-isolated-host-smoke \+  DERIVED_DATA="$T1734_RUN_ROOT/cache" \+  SMOKE_DERIVED_DATA="$T1734_RUN_ROOT/smoke"++# Fresh shared Debug unit-test bundle containing the new migration suite.+T1734_UNIT="$T1734_RUN_ROOT/unit"+make prepare-cache-dirs DERIVED_DATA="$T1734_UNIT"+XDG_CACHE_HOME="$T1734_UNIT/Caches" \+TMPDIR="$T1734_UNIT/tmp" \+SWIFTPM_MODULECACHE_OVERRIDE="$T1734_UNIT/Caches/org.swift.swiftpm" \+xcodebuild build-for-testing \+  -project Transit/Transit.xcodeproj -scheme Transit -configuration Debug \+  -destination 'platform=macOS,arch=arm64' -jobs 2 \+  -parallel-testing-enabled NO -disableAutomaticPackageResolution \+  -onlyUsePackageVersionsFromResolvedFile -derivedDataPath "$T1734_UNIT" \+  CLANG_MODULE_CACHE_PATH="$T1734_UNIT/ModuleCache.noindex" \+  CODE_SIGN_IDENTITY=- CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM=++# Fail-closed signature, identity, entitlements, mode and exact-host checks.+# Produces a new run file with only the verified unit target and suite.+python3 tests/typed-task-links/prepare_unit_run.py "$T1734_UNIT/Build/Products"++# Prospective RED may return nonzero. Capture that status and inspect xcresult.+T1734_TEST_STATUS=0+xcodebuild test-without-building \+  -xctestrun "$T1734_UNIT/Build/Products/T1734Migration.xctestrun" \+  -destination 'platform=macOS,arch=arm64' -parallel-testing-enabled NO \+  -only-testing:TransitTests/TaskLinkMigrationTests \+  -resultBundlePath "$T1734_UNIT/Build/Products/T1734Migration.xcresult" \+  || T1734_TEST_STATUS=$?+printf '%s\n' "$T1734_TEST_STATUS" > "$T1734_RUN_ROOT/migration-exit-status.txt"+```++The helper requires `me.nore.ig.Transit.development`, development signing, no iCloud/push/App Group entitlements, `TRANSIT_PERSISTENCE_MODE=unit-test`, and the exact preflighted host. It supplies startup smoke attestation and excludes UI targets. The dedicated smoke must also establish memory-only host persistence, disabled CloudKit counter adapters and private sidecars. `TransitDevelopment` is not the unit-test scheme.++## Expected focused inventory and interpretation++Two source declarations produce **three anticipated expanded cases**:++1. `defaultSchemaRegistersCloudCompatibleLinkEntity(name:)`, parameter `TaskLinkOccurrence`.+2. The same declaration, parameter `TaskLinkRemovalEvidence`.+3. `preFeatureDiskBaselinePreservesRawFieldsAndReceiptBytes`, synthetic six-entity saved-state control.++Inspect the xcresult for actual discovery, executed cases, individual outcomes and any unexpected suite. Two missing-model assertion failures are prospective registration-capability RED; the control is expected to pass, but neither outcome is claimed before execution. Compilation failure, crash or zero tests is not behavioral RED. A failing saved-state control is a prerequisite problem to diagnose before graph work.++The disk control observes a fresh context in a retained container. It does not prove a closed-store schema upgrade. Process-separated seed/upgrade migration, development CloudKit compatibility and remaining approved task1 coverage stay outstanding. Task1 remains incomplete even if this initial run yields its expected outcomes. Migration task2, atomic-save task4, bounded-capture task8 and later graph/write integration retain their approved gates. No production graph models or shared graph/write APIs are introduced by this preparation.++Live Transit mutations, client activation, production schema promotion and deployment remain held. Foundation ownership and canonical main/`.kiro` are unchanged.
tests/typed-task-links/development-cloudkit/README.md Changed +25 / -0
diff --git a/tests/typed-task-links/development-cloudkit/README.md b/tests/typed-task-links/development-cloudkit/README.mdnew file mode 100644index 00000000..6306a038--- /dev/null+++ b/tests/typed-task-links/development-cloudkit/README.md@@ -0,0 +1,25 @@+# Opt-in development schema/deletion smoke source++Deferred destination: **T-2402 — Set up isolated CloudKit integration testing**, created and freshly verified by the parent through the installed UI (Transit, Idea/Research). No duplicate live ticket write.++Owner `Sentinel_42e647a603ac81918cbb949ed1ca67bb` explicitly defers CloudKit test isolation to a separate ticket and authorizes T-1734 to proceed without it. This optional source remains uncompiled/unexecuted, outside default targets, and is not a T-1734 task2 completion gate. Parent owns the deferred ticket and any future setup/execution clearance; no live verification or remote compatibility is claimed.++`Smoke.swift` is outside Xcode source groups and default unit runs. Its typed body inserts the real task2 occurrence, observes its exported CloudKit record, deletes it through SwiftData while saving separate removal evidence, then observes the platform deletion event and exported evidence. It checks every scalar field locally and against the reviewed server mapping. It performs no direct CloudKit save/delete, schema initialization, query-index setup or framework-history purge. Successful evidence proves only this reserved development run, not global convergence or CloudKit-wide atomicity.++Compilation is deferred until task2 provides the real model declarations. Required initializer contracts are explicit in source: occurrence `(id, kindRawValue, sourceTaskID, targetTaskID, createdAt)` and evidence `(id, edgeId, kindRawValue, sourceTaskID, targetTaskID, createdAt, occurrenceRevision, removedAt)`. The future designated smoke host includes these two real models; their scalar endpoints require no task relationships or other model registrations. No production initializer or target change is included here.++An authorized operator must supply an existing **reserved development** container/schema, the zone used by that host's SwiftData exports, and a reviewed JSON contract. SwiftData's server field names are not inferred from local Schema metadata. The contract requires:++- `containerID`, `zoneName`, `ownerName`, `reservedDevelopmentEnvironment: true`.+- `uuidRepresentation`: exactly `uuid-string` or `uuid-data`; unsupported mappings fail closed.+- `occurrence` and `removal`: each contains the verified `recordType`, an existing `exemplarRecordName` in the pinned zone, and a complete `fields` map from each model's scalar property to its actual server field name.++Both existing exemplars are fetched by exact record ID and checked **before constructing the CloudKit-backed SwiftData store**. Missing exemplars/types/fields stop the fixture. This isolated schema includes exactly those two real scalar models and does not initialize the six original model types. The fixture is not a development schema initializer. Unsupported zone mapping, authorization, signing, export timing or schema representation remains a genuine task2 prerequisite/failure, with no fallback to another container or production environment.++The separately provisioned app host must have bundle ID `me.nore.ig.Transit.development.cloudkit-smoke`, executable `TaskLinkDevelopmentSmoke`, development signing, sandbox and exactly the reviewed CloudKit container entitlement with `icloud-container-environment = Development`. It has no push or App Group entitlement. `preflight.py` verifies these facts and the operator-reviewed contract SHA256 before any host launch. It defaults to validation only; `--run` is a future explicit invocation after parent environment and heavy-slot clearance. The current isolated Transit host has no CloudKit entitlement and cannot run this smoke.++Each run uses a new UUID-named store under the smoke host's sandbox `Data/tmp`. It retains the synthetic store and result evidence. Remote observation uses the public `CKDatabase.recordZoneChanges` API only in the pinned reserved zone, a 64-page/120-second observation budget and 5-second request/10-second resource limits; the outer runner stops at 180 seconds, terminates only its exact owned child on timeout, and verifies owned PID drain after ordinary completion. A timeout is failure, not convergence evidence. No cleanup removes remote or local evidence. The source's environment flag is only an opt-in marker: verified signing/entitlements and the reviewed operator contract in the wrapper supply the required development preflight; raw direct invocation is unsupported.++Public API signatures were checked in the installed SDK's `CloudKit.swiftinterface`: `record(for:)` (line 451), `configuredWith` (449), and `recordZoneChanges` (686), including modification/deletion fields (667–679); SwiftData's public `ModelConfiguration(... cloudKitDatabase: .private(...))` and model container initializer were also checked. This is source-level API evidence only. The future task2 compiler/runtime gate remains mandatory.++Before timeout termination, the wrapper samples only its exact owned child for two seconds at a 10 ms interval, with an eight-second sampler timeout. It retains the UUID-named trace under the smoke host's private `Data/tmp` and reports sampling errors without delaying the existing 10/5-second termination bounds.
tests/typed-task-links/participating-commit-scope-proposal.md Changed +206 / -0
diff --git a/tests/typed-task-links/participating-commit-scope-proposal.md b/tests/typed-task-links/participating-commit-scope-proposal.mdnew file mode 100644index 00000000..8eadb294--- /dev/null+++ b/tests/typed-task-links/participating-commit-scope-proposal.md@@ -0,0 +1,206 @@+# Task4 proposed commit scope — unapplied owner handoff++Reviewed source base: `c2b77cc`, inherited coordinator baseline `327390a`+(tested upstream blobs `e26efd4d2ce0ba534d2e4168aadd13cac6fb0ebe`).+Updated against the T2384 owner's reviewed source+`fc1b7d9d034cdcee1af7b822d3423c8830e01722` and+`/Users/arjen/Documents/Codex/2026-10-03/task-4/reviews/t1734-participating-commit-owner-review.md`.+The owner conditionally accepts the direction, retains shared-source ownership,+and has not applied or authorized a coordinator patch through that review.+This is a concrete patch request/interface sketch, not implemented source or+a passing runtime result. The existing 15-case source job stays pinned at+`de6ea49`; this update changes no test or runner source.++The amended contract coordinates participating shared-MCP operations on MainActor.+It does not fence independent containers or platform imports. Current `commit`+already performs policy validation, apply, terminal encoding and save without an+await. Its freshness gap is that policy/apply use the long-lived registered-model+cache in `services.context`. `includePendingChanges = false` alone does not prove+scalar refresh. The new existing-policy source test requires a conflict after a+peer saved revision change without injecting a fresh custom validator; its actual+RED/GREEN result is pending the assigned runtime slot.++## Proposed exact owner paths++1. `Transit/Transit/MCP/BatchWrites/MCPBatchWritePolicy.swift`: optional commit-services+   factory, nil by default to preserve existing callers. Proposed shape:++   ```swift+   let makeCommitServices: (@MainActor (ModelContext) throws -> MCPWriteCommitServices)?+   ```++   Requested initializer order against **fc1b7d9**, preserving every existing label:++   ```text+   makeCommitServices: ... = nil,+   onPendingEditsStop: ... = {},+   validateBeforeApply: ... = existing identity validator+   ```++   The factory is first, the current typed pending-stop observer second, and+   validation last. Audit labeled and trailing-closure callers rather than+   silently rebinding a validator to the observer. Preserve default nil-policy+   and policy-without-factory behavior. Preserve the owner's Task10 invocation+   of `onPendingEditsStop` at the actual synchronous dirty-stop branch; do not+   infer it from uncertain result text or post-await `hasChanges`.+   Expiry publication must read the fresh terminal+   receipt's expiry, not the original registered acceptance model.++   Keep the existing synchronous `validateBeforeApply` callback. The feature-local+   factory captures the caller's **original instances** of task and milestone+   DisplayIDAllocator and constructs a sealed `MCPWriteCommitServices` wrapper.+   Its only construction input is `(context, taskAllocator, milestoneAllocator)`;+   it constructs TaskService, ProjectService, CommentService and MilestoneService+   internally with exactly that context and their default context fetchers.+   No initializer accepts arbitrary `MCPWriteCommandServices`, a custom fetcher,+   or independently provided services. Read-only services/context access is+   sufficient for the coordinator. Thus construction proves all four private+   service contexts; checking only the plain services struct's `.context` does not.+   Do not expose/copy private allocator fields or create replacement allocators.+   The sealed shared wrapper's placement and source delivery need the coordinator+   owner's interface agreement; T1734 owns the feature-local factory and tests,+   not an unapproved shared-type source edit. No factory is implemented here.++2. `Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift`: inside the existing fresh+   validated-bindings phase, and after existing shared-context clean checks, create+   one `ModelContext(services.context.container)` when this factory is supplied.+   Disable autosave and retain that context for the whole synchronous phase.+   Require the sealed wrapper to reference that exact context and remain clean+   with autosave disabled; never trust an arbitrary struct context field as proof+   of its constituent services. The coordinator owns this context's lifetime.+   Resolve the accepted receipt in this fresh context using the existing receipt+   store and original tool/key/local scope. Validate guard receipt ID, canonical+   request payload, format version and compatible retained state before applying.+   A valid fresh terminal receipt replays its original bytes/error immediately,+   bypassing graph/domain validation. Missing, inconsistent or unreadable accepted+   evidence stops apply and requires original-key reconciliation; never invent a+   new receipt/no-effect conclusion or move the shared acceptance model across+   contexts. A failed/mismatched factory never falls back to shared apply or+   saving/rolling back UI drafts. Revalidate the existing durable binding within+   its synchronous owned phase; do not replace the guard store or reset its key.++   Proposed flow (not compilable replacement code):++   ```text+   shared context clean checks and existing reservation binding validation+   fresh same-container context + sealed factory services + fresh receipt store+   refetch/validate exact receipt; terminal -> immutable replay+   missing/inconsistent/unreadable -> original-key uncertainty/reconciliation+   validateBeforeApply(command, freshContext)+   command.apply(prepared IDs/values, using: freshServices)+   stageTerminal(freshReceipt, encodedEnvelope)+   save(freshContext, .commit)+   existing sidecar expiry publication+   ```++   All source/endpoint/edge/removal predicates and the eventual full plan are+   validated immediately before apply from this fresh saved scope. Prepared+   creation/task commands carry IDs/values and can resolve in those services.+   No ModelData/private CoreData bridge, extra save, transaction marker, global+   lock, second coordinator or new store is proposed.++   Roll back only this owned scope on encode/apply/save failure. Durable recovery+   still uses existing independently resolved receipt evidence and original-key+   semantics. Rejection must stage and save its receipt in the corresponding+   owned scope; parameterize the existing rejection helper's context/receipt+   store rather than accidentally saving `services.context`. Preserve uncertain+   recovery and don't roll back pending UI drafts or downgrade a durable commit.+   A stale acceptance model left registered in the original context must not+   authorize repeat application: retain durable-before-live replay and route+   fresh acceptance/repair/rejection lookups through the owned scope as needed.++   Required branch audit for the owner patch:++   | Existing method/branch | Scope rule and preserved behavior |+   | --- | --- |+   | `runAccepted` preparation success | Recheck shared drafts after await, then create the fresh owned final phase; prepared values contain no models. |+   | `runAccepted` preparation error | Recheck shared drafts before rejection. Rejection/refetch/save must use the selected owned receipt scope; do not save shared drafts. |+   | `commit` success | Fresh guard/receipt and all four services, saved source/endpoint/edge/removal predicates, apply, terminal encoding and exactly one terminal save with no await. |+   | `commit` catch | Discard/rollback only owned staged changes; probe durable receipt before outcome selection. Durable terminal replays unchanged; only proven accepted-but-uncommitted evidence allows rejection. |+   | `completeRejection` | Parameterize chosen context/store and stage the corresponding refetched receipt there. Encode/save/recovery failures retain uncertainty; no stale original receipt or shared-context save. |+   | `recover` | Keep original-key durable evidence and terminal replay first. Route a required accepted-only rejection through owned refetch; don't let stale shared accepted state authorize reapply. |+   | `rejectBeforeDomain` | Preserve acceptance failure/reconciliation semantics and existing no-effect proof requirements. If scope cannot be constructed, don't infer effect absence or roll back/save UI state. |+   | Every dirty stop and dirty retained replay | No factory, reserve, expiry repair, cleanup, recovery hook, domain lookup or draft mutation. Preserve typed pending-stop observer and accepted/outcome/retryAction evidence. |++   No envelope-format changes are requested. Audit/refactor the chosen-scope+   parameters in `MCPWriteCoordinator.swift` rather than expanding Outcomes+   presentation or changing historic text/optional-error semantics.++3. Later startup/adapter wiring at `Transit/Transit/TransitApp.swift`, shared+   coordinator construction near line162, and the actual link adapter callsites:+   caller-known allocator/service factory only. This requires an explicit owner+   grant and real caller integration. Do not change startup storage, sidecars,+   lifetime, isolation settings, tool schema or handler construction incidentally.++   A default-nil factory does **not** fix the actual-SUT `.init()` stale-source+   expectation. Task4 must configure the real fresh-services factory in the+   participating policy exercised by that test and every feature graph-covered+   standalone and per-item batch callsite, then rerun the same stale-source+   rejection expectation against that configured SUT. Keep legacy/default-nil+   behavior separately labeled; a link-only opt-in does not establish freshness+   for all participating graph-covered property/status/comment operations.+   Factory/coordinator source alone is not GREEN until these callers are wired.+   The current limited import has no per-item batch runner handoff. T2384 must+   identify and refresh its approved merged per-item caller paths before that+   wiring; do not invent or import a batch executor here. The standalone routing+   owner path `Transit/Transit/MCP/MCPToolHandler.swift` currently calls+   `writeCoordinator.execute(tool:arguments:)` without a policy. The later link+   adapter must configure the concrete participating policy on graph-covered+   fresh routes there, preserving retained replay and leaving no nil-policy bypass.++`MCPWriteCoordinator+Outcomes.swift` and `MCPWriteOutcome.swift` need no proposed+format changes; keep existing dirty/replay envelopes and encoder. Existing default+batch policy behavior must remain covered. T2384 retains shared-file ownership;+none of these source edits is authorized by this document itself.++## Remaining evidence and dependent work++The 15-case prepared job covers existing-SUT source revision freshness, positive+fresh endpoint/cycle validation controls, participating phase ordering, originating+domain/graph/removal/terminal save success and failures, drafts and immutable replay.+Graph staging is test-owned, not a public link adapter or complete plan implementation.+Actual graph-covered endpoint/source guards and projection diagnostics still require+tasks5/6,9/10 and later adapter/integrated tests21/22. Primitive counterexample and+abort results remain documented limits; neither is an amended completion gate.+No CloudKit or all-writer proof is required or claimed.++## Owner patch request and delivery sequence++Parent schedules T2384's sole-writer patch from **fc1b7d9 or its explicitly+refreshed owner base**, preserving the active Task9/10 chain and pending-stop+observer. Do not replace that source with the older T1734 import. Requested+delivery: coordinator/policy plus agreed sealed-wrapper interface, exact component+manifest/base and owner source review. T1734 then supplies feature-local factory+construction/guards and acceptance fixtures against that interface. Caller owner+separately wires standalone startup/routing; T2384 separately wires the actual+Task10 per-item execution seam using existing UUID validation and the per-invocation+pending-stop observer. Current declaration shell/test adapter is not that runner.+Preserve original protected arguments/key and the same receipt engine throughout.++No shared-file editing is granted by this document. This is an implementation+handoff within the amended approved contract, with no new product decision.++## Acceptance-test matrix after the interface handoff++These are future acceptance requirements; the pinned 15-case run is unchanged.+Only its actual runtime result may be reported as executed evidence.++| Fixture/control | Required observation and minimum acceptance |+| --- | --- |+| Stale registered source, actual configured participating factory | Preload original source in shared context, save a peer change, submit the unchanged old revision. Production validator **and** apply resolve fresh scope; conflict contains current saved record, no domain/graph effect, retained rejection byte-identical. No custom prevalidation callback fakes SUT freshness. |+| Separately labeled legacy/default nil | Preserve baseline semantics and replay; never count this as fresh-scope GREEN. |+| Stale registered endpoint and changed cycle before apply | Factory-backed actual guards read fresh endpoint revisions and complete saved predicate; reject before owned effects. Full plan/projection semantics await their real components. |+| Sealed service ownership | Constructor's original context/allocator inputs build all four services; callback/apply resolve the supplied fresh context. No arbitrary services/custom fetchers, mismatched context or dirty factory output is accepted. |+| Factory throws / scope construction or receipt fetch fails | No domain apply/save and no shared UI rollback/save; preserve durable acceptance and original-key reconciliation. |+| Missing, duplicate, inconsistent scope/tool/key/ID/payload/format receipt | Stop without apply or fresh-key advice; ambiguity remains uncertainty, not chosen physical receipt. |+| Fresh terminal found before validation | Replay original bytes/optional error; zero graph validation/apply and no terminal rewrite or repair caused by replay. |+| Participating final-phase order | Validation, domain/graph staging, encode and terminal save remain synchronous; queued participating MainActor operation enters afterward. No import-exclusion claim. |+| Owned success | Source fields, exact edges/removal evidence and terminal receipt appear together in independently observed saved state; historic receipts untouched and expiry published from fresh receipt. |+| Apply/encode/save failure | Owned domain/graph changes absent when accepted-uncommitted is proven; corresponding rejection saved in chosen context. If durable terminal exists, replay rather than downgrade. |+| Recovery fails / outcome unavailable | Uncertain result retains acceptance/effect evidence and original-key action; no guessed no-effect result or reapply from stale shared receipt. |+| Preparation errors, `recover`, `rejectBeforeDomain` | Exercise each chosen-scope rejection/save path, not only `commit` success; no shared draft save/rollback. |+| Dirty before acceptance and after await success/error | Preserve inserted/edited/deleted UI drafts; stop through typed observer branch where applicable, zero factory/repair/save on dirty replay. |+| Retained replay after edits/deletion/new graph faults | Original content/error/revision bytes unchanged; bypass current graph/source lookup and preserve draft state. |+| Creation allocator identity and prepared values | Use original task/milestone allocator instances; creation resolves prepared IDs/scalars in owned services without model transfer or duplicate allocation. |+| Every graph-covered standalone and per-item route | Confirm actual factory opt-in for property/status/comment/create/update consumers as applicable, original tool/key/arguments retained, no nil-policy bypass; keep per-item pending-stop notification. No whole-batch atomicity claim. |+| Outside writer after validation | Preserve committed originating receipt and observed later saved evidence; actual projections update valid status assessments and report available invalid graph evidence, with no automatic repair or historical-race diagnosis. |
tests/typed-task-links/schema-registration-inventory.md Changed +24 / -0
diff --git a/tests/typed-task-links/schema-registration-inventory.md b/tests/typed-task-links/schema-registration-inventory.mdnew file mode 100644index 00000000..728172ef--- /dev/null+++ b/tests/typed-task-links/schema-registration-inventory.md@@ -0,0 +1,24 @@+# Schema registration inventory and historical ownership proposal++Current status: all seven current schema factories register both link entities; app/default test schema is eight entities. Exact list-only ownership handoffs were granted and implemented before later sole-worker integration. `audit_schema_sources.py --check` inventories actual current source. Probe.seed-old remains the historical five-entity fixture, the migration baseline remains six entities, and development-isolation controls remain intentionally graph-free. Runtime migration/metadata gates passed locally; live Development CloudKit verification is deferred to T2402 by owner amendment. The adjacent patch and the proposal below are historical review artifacts, not outstanding permission or publication gates.++Source checkpoint: `4459a96451588266c6b13c3475bac5a3243c9cc3`, branch `T-1734/typed-task-links`. The adjacent `pending-schema-registration.patch` is a review artifact only; it has not been applied. Ownership agreement is pending. Owners must adapt these narrow additions against their actual latest integrated source rather than replace files from this checkpoint.++| File / context anchor | Minimal proposed change | Proposed coordination |+| --- | --- | --- |+| `Transit/Transit/TransitApp.swift`, `init`, `let schema = Schema([` | Add the two model types after MCPWriteReceipt. No initializer, persistence-mode, CloudKit, allocator or server changes. | Containment/App owner applies or explicitly hands off this schema-list hunk. |+| `Transit/TransitTests/TestModelContainer.swift`, default `init()` | Register both model types in the default schema. Keep owning retention, custom-schema initializer and CloudKit `.none` unchanged. | Parent-designated common-fixture owner confirms the exact list-only handoff; T-63/containment coordinate current integrated source. |+| `Transit/TransitTests/MCPWritePersistenceProbeTests.swift`, computed `schema` | Add both models to this current receipt/task schema; no fixture lifecycle changes. | Parent confirms test-file ownership. |+| `tests/mcp-write-probe/ServiceProbe.swift`, `main`, literal schema | Add both model types; keep storage and service construction intact. | Parent-designated MCP write-probe owner confirms list-only handoff; do not infer T-63 ownership. |+| `tests/mcp-write-probe/CoordinatorProbe.swift`, `main`, literal schema | Add both model types; no coordinator or receipt logic changes. | Parent-designated MCP write-probe owner confirms list-only handoff; do not infer T-63 ownership. |+| `tests/mcp-write-probe/FoundationProbe.swift`, `receiptStorage`, literal schema | Add both model types to the receipt-storage schema. | Parent-designated MCP write-probe owner confirms list-only handoff; do not infer T-63 ownership. |+| `tests/mcp-write-probe/Probe.swift`, `if mode != "seed-old"` | Append both models only inside the existing nonhistorical-mode branch, alongside MCPWriteReceipt. Preserve the historical five-model seed-old branch exactly. | Parent-designated MCP write-probe owner confirms mode-specific handoff; do not infer T-63 ownership. |+| `Makefile`, `MCP_PROBE_MODELS` | Add the two definition filenames to the existing standalone compiler source list. No commands, flags, targets or run policy changes. | Makefile/probe owner coordinates this compile-list hunk. |++T-1734 proposes to own new `Models/TaskLinkOccurrence.swift` and `Models/TaskLinkRemovalEvidence.swift` only after the task 1 boundary and ownership split are resolved. The approved shape has defaulted scalar UUID/String/Date storage, explicit UUID/time construction, programmatically immutable identity/endpoint/kind fields, and no relationships, cascades, uniqueness or validation shortcuts. No model definitions are included in this patch.++The schema list changes require those real model definitions. Applying the patch without them causes compilation failure and supplies no runtime migration evidence. The existing current-schema RED is not an implementation substitute.++The six-entity `TaskLinkPreFeatureDiskFixture`, five-entity `Probe.seed-old`, and intentionally graph-free development-isolation migration fixture remain unchanged. `ContainerFactory` receives its caller's schema and needs no registration change. JSONSchema is unrelated. This patch neither changes the snapshot/revision contract nor grants access to an owner’s other shared files.++Task 2's disk migration and separately cleared development CloudKit schema/deletion evidence remain required before dependent work. These proposed source additions authorize no build, runtime probe, client activation, schema initialization/promotion or live record mutation.

Things to double-check

Final provenance Final tested application/test/Makefile source is bbe3a2560584f7fb822aa8006b20f08d22284ce4. Later commits are documentation only. Fresh origin/main and merge base remain e04c1268ee37bd4ae925d4d686954cf2121005c7. Earlier remote 0714ce01 reviews and 81f78e7 runtime evidence remain separately identified.
Historical evidence and limits Earlier RED, compile-only failures, 14 initial full-run failures and interrupted UI diagnostics remain recorded. Final definitive results have exit 0 and drain evidence. Five opt-ins remain intentionally skipped. No live CloudKit setup/export/deletion or installed-client activation was performed.
Actual remote merge verification PR state MERGED at 2026-10-05T05:19:48Z; squash SHA 169ac244a11ebfbdacce3d4a25fcddfe395ac6d2; merged tree 3257c89bbcd12abfff866c667c31d1db4aa88150. Whole-tree equality and source equality asserted in merge-verification.json. Local feature branch remains clean and preserved; no local main checkout.